From d79d002dd33c013962b5275be8687138b50c1973 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 09:46:55 +0000 Subject: [PATCH 01/93] Added 'getAllSentMessages' command to API --- src/bitmessagemain.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 8d9bc461..74d4b211 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3696,6 +3696,22 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 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 += ']}' return data + elif method == 'getAllSentMessages': + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, status FROM sent where folder='sent' ORDER BY lastactiontime''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"sentMessages":[' + for row in queryreturn: + msgid, toAddress, fromAddress, subject, lastactiontime, message, status = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + if len(data) > 25: + data += ',' + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) + data += ']}' + return data elif method == 'trashMessage': if len(params) == 0: return 'API Error 0000: I need parameters!' From fba402ab186001cab36fc8a9da174e3c9bca2847 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 11:57:41 +0000 Subject: [PATCH 02/93] Added 'getSentMessageById' command to API --- src/bitmessagemain.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 74d4b211..1a61438d 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3712,6 +3712,22 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) data += ']}' return data + elif method == 'getSentMessageById': + msgid = params[0].decode('hex') + v = (msgid,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, status FROM sent WHERE msgid=?''') + shared.sqlSubmitQueue.put(v) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"sentMessage":[' + for row in queryreturn: + toAddress, fromAddress, subject, received, message, = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + 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 += ']}' + return data elif method == 'trashMessage': if len(params) == 0: return 'API Error 0000: I need parameters!' From ce8113b36e14a20763fae1cbdd52accd2cd38108 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 12:02:52 +0000 Subject: [PATCH 03/93] Changed received to 'lastActionTime' for 'getSentMessageById' command. --- src/bitmessagemain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 1a61438d..7397fbb5 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3725,7 +3725,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): toAddress, fromAddress, subject, received, message, = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) - 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,'lastActionTime':lastactiontime},indent=4, separators=(',', ': ')) data += ']}' return data elif method == 'trashMessage': From 3f07f895bc1389f630bc393ecd5aafcf0db41e34 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 12:06:46 +0000 Subject: [PATCH 04/93] Added 'getAllInboxMessages' command to API. --- src/bitmessagemain.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 7397fbb5..346d8a66 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3696,6 +3696,22 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 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 += ']}' return data + elif method == 'getInboxMessageById': + msgid = params[0].decode('hex') + v = (msgid,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, received, message FROM inbox WHERE msgid=?''') + shared.sqlSubmitQueue.put(v) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"inboxMessage":[' + for row in queryreturn: + msgid, toAddress, fromAddress, subject, received, message, = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + 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 += ']}' + return data elif method == 'getAllSentMessages': shared.sqlLock.acquire() shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, status FROM sent where folder='sent' ORDER BY lastactiontime''') From b8250ae04f10670d55b49d93896ffa1dab812e61 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 13:10:25 +0100 Subject: [PATCH 05/93] Fixed indentation error. From 28ed9676ccc768e6877747d9a5a5cc2f5a57eb79 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Wed, 19 Jun 2013 12:29:28 +0000 Subject: [PATCH 06/93] Fixed indentation error (previous commit contained no files) --- src/bitmessagemain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 346d8a66..a0da58fa 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3728,7 +3728,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) data += ']}' return data - elif method == 'getSentMessageById': + elif method == 'getSentMessageById': msgid = params[0].decode('hex') v = (msgid,) shared.sqlLock.acquire() From 72643471829e0bca5cb7f2f9d9480dfd348d1d76 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Wed, 19 Jun 2013 22:50:00 +0100 Subject: [PATCH 07/93] Added parameters check for getInboxMessageById and getSentMessageById API commands --- src/bitmessagemain.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index a0da58fa..fc7ce7fe 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3697,6 +3697,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data elif method == 'getInboxMessageById': + if len(params) == 0: + return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') v = (msgid,) shared.sqlLock.acquire() @@ -3729,6 +3731,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data elif method == 'getSentMessageById': + if len(params) == 0: + return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') v = (msgid,) shared.sqlLock.acquire() From 21ec1de7ca58bd700705bd4a862b0f0040d1d613 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Wed, 19 Jun 2013 23:02:36 +0100 Subject: [PATCH 08/93] Created API commands: 'trashInboxMessage' and 'trashSentMessage'. Also, identation fix caused by accidental tabs instead of spaces. --- src/bitmessagemain.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index fc7ce7fe..2335540a 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3697,7 +3697,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data elif method == 'getInboxMessageById': - if len(params) == 0: + if len(params) == 0: return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') v = (msgid,) @@ -3731,7 +3731,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data elif method == 'getSentMessageById': - if len(params) == 0: + if len(params) == 0: return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') v = (msgid,) @@ -3748,7 +3748,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'lastActionTime':lastactiontime},indent=4, separators=(',', ': ')) data += ']}' return data - elif method == 'trashMessage': + elif (method == 'trashMessage') or (method == 'trashInboxMessage'): if len(params) == 0: return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') @@ -3760,7 +3760,20 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid)) - return 'Trashed message (assuming message existed).' + return 'Trashed inbox message (assuming message existed).' + elif method == 'trashSentMessage': + if len(params) == 0: + return 'API Error 0000: I need parameters!' + msgid = params[0].decode('hex') + t = (msgid,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''UPDATE sent SET folder='trash' WHERE msgid=?''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('removeSentRowByMsgid',msgid)) + return 'Trashed sent message (assuming message existed).' elif method == 'sendMessage': if len(params) == 0: return 'API Error 0000: I need parameters!' From c655b9a50602c4e5288b6ee29b30b88525f5ce91 Mon Sep 17 00:00:00 2001 From: Joshua Noble Date: Thu, 20 Jun 2013 00:49:28 -0400 Subject: [PATCH 09/93] Add getInboxMessagesByAddress API command --- src/bitmessagemain.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index e347d561..6b778a97 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3712,6 +3712,24 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 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 += ']}' return data + elif method == 'getInboxMessagesByAddress': + toAddress = params[0] + v = (toAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, fromaddress, subject, received, message FROM inbox WHERE toAddress=?''') + shared.sqlSubmitQueue.put(v) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"inboxMessages":[' + for row in queryreturn: + msgid, fromAddress, subject, received, message, = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + if len(data) > 25: + 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 += ']}' + return data elif method == 'trashMessage': if len(params) == 0: return 'API Error 0000: I need parameters!' From 29c5282d48391ea6c3cc9fd38068c2b4a531970b Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Thu, 20 Jun 2013 07:52:39 -0400 Subject: [PATCH 10/93] manual merge acejam-master --- src/bitmessagemain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 158fb560..3735d8d2 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4412,7 +4412,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' - data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) data += ']}' return data elif method == 'getInboxMessagesByAddress': From 58f33042448d448ca9ae21ccbf4a5889b3edc5be Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Thu, 20 Jun 2013 07:58:37 -0400 Subject: [PATCH 11/93] When using API command getInboxMessagesByAddress, display true encoding type saved in table --- src/bitmessagemain.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 3735d8d2..798841ff 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4419,18 +4419,18 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): toAddress = params[0] v = (toAddress,) shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''SELECT msgid, fromaddress, subject, received, message FROM inbox WHERE toAddress=?''') + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE toAddress=?''') shared.sqlSubmitQueue.put(v) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() data = '{"inboxMessages":[' for row in queryreturn: - msgid, fromAddress, subject, received, message, = row + msgid, toAddress, fromAddress, subject, received, message, encodingtype= row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' - data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'received':received},indent=4, separators=(',', ': ')) data += ']}' return data elif method == 'getSentMessageById': From e49e9a60b0c556b372c2190a033a815ca69acc64 Mon Sep 17 00:00:00 2001 From: "jordan@hall05.co.uk" <1337One> Date: Thu, 20 Jun 2013 13:04:34 +0000 Subject: [PATCH 12/93] New API command getSentMessageByAckData and modified the getAllSentMessages and getSentMessageById commands to return ackData --- src/bitmessagemain.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 798841ff..f1fa80bc 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4401,18 +4401,18 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): return data elif method == 'getAllSentMessages': shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status FROM sent where folder='sent' ORDER BY lastactiontime''') + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent where folder='sent' ORDER BY lastactiontime''') shared.sqlSubmitQueue.put('') queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() data = '{"sentMessages":[' for row in queryreturn: - msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status = row + msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' - data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status,'ackData':ackdata.encode('hex')},indent=4, separators=(',', ': ')) data += ']}' return data elif method == 'getInboxMessagesByAddress': @@ -4439,16 +4439,34 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): msgid = params[0].decode('hex') v = (msgid,) shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status FROM sent WHERE msgid=?''') + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE msgid=?''') shared.sqlSubmitQueue.put(v) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() data = '{"sentMessage":[' for row in queryreturn: - msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status = row + msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) - data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status},indent=4, separators=(',', ': ')) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status,'ackData':ackdata.encode('hex')},indent=4, separators=(',', ': ')) + data += ']}' + return data + elif method == 'getSentMessageByAckData': + if len(params) == 0: + return 'API Error 0000: I need parameters!' + ackData = params[0].decode('hex') + v = (ackData,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE ackdata=?''') + shared.sqlSubmitQueue.put(v) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"sentMessage":[' + for row in queryreturn: + msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status,'ackData':ackdata.encode('hex')},indent=4, separators=(',', ': ')) data += ']}' return data elif (method == 'trashMessage') or (method == 'trashInboxMessage'): From a6c9ff288ebce62cdade84557f3e5638159a5263 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Thu, 20 Jun 2013 16:04:50 -0400 Subject: [PATCH 13/93] manuall merge github issue #229 --- src/pyelliptic/openssl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index de073fab..09df5ca4 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -427,7 +427,7 @@ except: lib_path = path.join(sys._MEIPASS, "libeay32.dll") OpenSSL = _OpenSSL(lib_path) except: - if 'linux' in sys.platform or 'darwin' in sys.platform: + if 'linux' in sys.platform or 'darwin' in sys.platform or 'freebsd' in sys.platform: try: from ctypes.util import find_library OpenSSL = _OpenSSL(find_library('ssl')) From 936369da0ab79fb15c17be4823e8a2871136aee4 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Thu, 20 Jun 2013 16:41:14 -0400 Subject: [PATCH 14/93] manual implement Github issue #223 --- src/bitmessagemain.py | 7 +++++-- src/bitmessageqt/__init__.py | 12 ++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 798841ff..8f018337 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -68,14 +68,17 @@ class outgoingSynSender(threading.Thread): if shared.shutdown: break random.seed() + shared.knownNodesLock.acquire() HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) + shared.knownNodesLock.release() alreadyAttemptedConnectionsListLock.acquire() while HOST in alreadyAttemptedConnectionsList or HOST in shared.connectedHostsList: alreadyAttemptedConnectionsListLock.release() # print 'choosing new sample' random.seed() - HOST, = random.sample(shared.knownNodes[ - self.streamNumber], 1) + shared.knownNodesLock.acquire() + HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) + shared.knownNodesLock.release() time.sleep(1) # Clear out the alreadyAttemptedConnectionsList every half # hour so that this program will again attempt a connection diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 22f957e3..3f0c7e6f 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -1076,8 +1076,8 @@ class MyForm(QtGui.QMainWindow): shared.statusIconColor = 'red' # if the connection is lost then show a notification if self.connected: - self.notifierShow('Bitmessage', _translate( - "MainWindow", "Connection lost")) + self.notifierShow('Bitmessage', unicode(_translate( + "MainWindow", "Connection lost").toUtf8(),'utf-8')) self.connected = False if self.actionStatus is not None: @@ -1109,8 +1109,8 @@ class MyForm(QtGui.QMainWindow): QIcon(":/newPrefix/images/greenicon.png")) shared.statusIconColor = 'green' if not self.connected: - self.notifierShow('Bitmessage', _translate( - "MainWindow", "Connected")) + self.notifierShow('Bitmessage', unicode(_translate( + "MainWindow", "Connected").toUtf8(),'utf-8')) self.connected = True if self.actionStatus is not None: @@ -1582,12 +1582,12 @@ class MyForm(QtGui.QMainWindow): newItem = QtGui.QTableWidgetItem(unicode(fromAddress, 'utf-8')) newItem.setToolTip(unicode(fromAddress, 'utf-8')) if shared.config.getboolean('bitmessagesettings', 'showtraynotifications'): - self.notifierShow('New Message', 'From ' + fromAddress) + self.notifierShow(unicode(_translate("MainWindow",'New Message').toUtf8(),'utf-8'), unicode(_translate("MainWindow",'From ').toUtf8(),'utf-8') + unicode(fromAddress, 'utf-8')) else: newItem = QtGui.QTableWidgetItem(unicode(fromLabel, 'utf-8')) newItem.setToolTip(unicode(unicode(fromLabel, 'utf-8'))) if shared.config.getboolean('bitmessagesettings', 'showtraynotifications'): - self.notifierShow('New Message', 'From ' + fromLabel) + self.notifierShow(unicode(_translate("MainWindow",'New Message').toUtf8(),'utf-8'), unicode(_translate("MainWindow",'From ').toUtf8(),'utf-8') + unicode(fromLabel, 'utf-8')) newItem.setData(Qt.UserRole, str(fromAddress)) newItem.setFont(font) self.ui.tableWidgetInbox.setItem(0, 1, newItem) From ebc62b9edc1d0c0ea9eba3b8d24f442bce9d82f9 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Thu, 20 Jun 2013 22:23:03 +0100 Subject: [PATCH 15/93] Moving certain classes outside of bitmessagemain.py --- src/bitmessagemain.py | 444 +----------------------------------- src/class_singleCleaner.py | 122 ++++++++++ src/class_singleListener.py | 76 ++++++ src/class_sqlThread.py | 255 +++++++++++++++++++++ 4 files changed, 458 insertions(+), 439 deletions(-) create mode 100644 src/class_singleCleaner.py create mode 100644 src/class_singleListener.py create mode 100644 src/class_sqlThread.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 798841ff..59479bb9 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -48,6 +48,11 @@ from subprocess import call # used when the API must execute an outside program import singleton import proofofwork +# Classes +from class_singleListener import * +from class_sqlThread import * +from class_singleCleaner import * + # For each stream to which we connect, several outgoingSynSender threads # will exist and will collectively create 8 connections with peers. @@ -205,78 +210,6 @@ class outgoingSynSender(threading.Thread): 'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: %s\n' % err) 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) - - -class singleListener(threading.Thread): - - def __init__(self): - threading.Thread.__init__(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. - while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': - time.sleep(300) - - shared.printLock.acquire() - print 'Listening for incoming connections.' - shared.printLock.release() - HOST = '' # Symbolic name meaning all available interfaces - PORT = shared.config.getint('bitmessagesettings', 'port') - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - # This option apparently avoids the TIME_WAIT state so that we can - # rebind faster - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.bind((HOST, PORT)) - sock.listen(2) - - while True: - # We don't want to accept incoming connections if the user is using - # a SOCKS proxy. If the user eventually select proxy 'none' then - # this will start listening for connections. - while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': - time.sleep(10) - while len(shared.connectedHostsList) > 220: - shared.printLock.acquire() - print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' - shared.printLock.release() - time.sleep(10) - 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. - while HOST in shared.connectedHostsList: - shared.printLock.acquire() - print 'We are already connected to', HOST + '. Ignoring connection.' - shared.printLock.release() - a.close() - a, (HOST, PORT) = sock.accept() - objectsOfWhichThisRemoteNodeIsAlreadyAware = {} - a.settimeout(20) - - sd = sendDataThread() - sd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) - sd.start() - - rd = receiveDataThread() - rd.daemon = True # close the main program even if there are threads left - rd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) - rd.start() - - shared.printLock.acquire() - print self, 'connected to', HOST, 'during INCOMING request.' - shared.printLock.release() # This thread is created either by the synSenderThread(for outgoing # connections) or the singleListenerThread(for incoming connectiosn). @@ -2651,375 +2584,8 @@ def isHostInPrivateIPRange(host): return True 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. -class sqlThread(threading.Thread): - - def __init__(self): - threading.Thread.__init__(self) - - def run(self): - self.conn = sqlite3.connect(shared.appdata + 'messages.dat') - self.conn.text_factory = str - self.cur = self.conn.cursor() - try: - self.cur.execute( - '''CREATE TABLE inbox (msgid blob, toaddress text, fromaddress text, subject text, received text, message text, folder text, encodingtype int, read bool, UNIQUE(msgid) ON CONFLICT REPLACE)''' ) - 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)''' ) - self.cur.execute( - '''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: - # 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. - # 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. - 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('lastvacuumtime',?)''', ( - int(time.time()),)) - self.conn.commit() - print 'Created messages database file' - except Exception as err: - if str(err) == 'table inbox already exists': - shared.printLock.acquire() - print 'Database file already exists.' - shared.printLock.release() - else: - sys.stderr.write( - 'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err)) - os._exit(0) - - # 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: - item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' ''' - parameters = '' - self.cur.execute(item, parameters) - self.conn.commit() - - shared.config.set('bitmessagesettings', 'settingsversion', '3') - with open(shared.appdata + 'keys.dat', 'wb') as 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. - if shared.config.getint('bitmessagesettings', 'settingsversion') == 3: - item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' ''' - parameters = '' - self.cur.execute(item, parameters) - - item = '''ALTER TABLE inbox ADD read bool DEFAULT '1' ''' - parameters = '' - self.cur.execute(item, parameters) - - item = '''ALTER TABLE sent ADD encodingtype int DEFAULT '2' ''' - parameters = '' - self.cur.execute(item, parameters) - self.conn.commit() - - shared.config.set('bitmessagesettings', 'settingsversion', '4') - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - if shared.config.getint('bitmessagesettings', 'settingsversion') == 4: - shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str( - shared.networkDefaultProofOfWorkNonceTrialsPerByte)) - shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str( - shared.networkDefaultPayloadLengthExtraBytes)) - shared.config.set('bitmessagesettings', 'settingsversion', '5') - - if shared.config.getint('bitmessagesettings', 'settingsversion') == 5: - shared.config.set( - 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0') - shared.config.set( - 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0') - shared.config.set('bitmessagesettings', 'settingsversion', '6') - with open(shared.appdata + 'keys.dat', 'wb') as 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. - item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';''' - parameters = '' - self.cur.execute(item, parameters) - if self.cur.fetchall() == []: - # The settings table doesn't exist. We need to make it. - 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( '''INSERT INTO settings VALUES('version','1')''') - self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( - int(time.time()),)) - 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( - '''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM 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( - '''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM 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.' - self.cur.execute( - '''delete from inventory where objecttype = 'pubkey';''') - print 'replacing Bitmessage announcements mailing list with a new one.' - self.cur.execute( - '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' ''') - self.cur.execute( - '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') - print 'Commiting.' - self.conn.commit() - print 'Vacuuming message.dat. You might notice that the file size gets much smaller.' - self.cur.execute( ''' VACUUM ''') - - # After code refactoring, the possible status values for sent messages - # as changed. - self.cur.execute( - '''update sent set status='doingmsgpow' where status='doingpow' ''') - 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() - - try: - testpayload = '\x00\x00' - t = ('1234', testpayload, '12345678', 'no') - self.cur.execute( '''INSERT INTO pubkeys VALUES(?,?,?,?)''', t) - self.conn.commit() - self.cur.execute( - '''SELECT transmitdata FROM pubkeys WHERE hash='1234' ''') - queryreturn = self.cur.fetchall() - for row in queryreturn: - transmitdata, = row - self.cur.execute('''DELETE FROM pubkeys WHERE hash='1234' ''') - self.conn.commit() - 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('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) - except Exception as 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. - item = '''SELECT value FROM settings WHERE key='lastvacuumtime';''' - parameters = '' - self.cur.execute(item, parameters) - queryreturn = self.cur.fetchall() - for row in queryreturn: - value, = row - if int(value) < int(time.time()) - 2592000: - print 'It has been a long time since the messages.dat file has been vacuumed. Vacuuming now...' - self.cur.execute( ''' VACUUM ''') - item = '''update settings set value=? WHERE key='lastvacuumtime';''' - parameters = (int(time.time()),) - self.cur.execute(item, parameters) - - while True: - item = shared.sqlSubmitQueue.get() - if item == 'commit': - self.conn.commit() - elif item == 'exit': - self.conn.close() - shared.printLock.acquire() - print 'sqlThread exiting gracefully.' - shared.printLock.release() - return - elif item == 'movemessagstoprog': - shared.printLock.acquire() - print 'the sqlThread is moving the messages.dat file to the local program directory.' - shared.printLock.release() - self.conn.commit() - self.conn.close() - shutil.move( - shared.lookupAppdataFolder() + 'messages.dat', 'messages.dat') - self.conn = sqlite3.connect('messages.dat') - self.conn.text_factory = str - self.cur = self.conn.cursor() - elif item == 'movemessagstoappdata': - shared.printLock.acquire() - print 'the sqlThread is moving the messages.dat file to the Appdata folder.' - shared.printLock.release() - self.conn.commit() - self.conn.close() - shutil.move( - 'messages.dat', shared.lookupAppdataFolder() + 'messages.dat') - self.conn = sqlite3.connect(shared.appdata + 'messages.dat') - self.conn.text_factory = str - self.cur = self.conn.cursor() - elif item == 'deleteandvacuume': - self.cur.execute('''delete from inbox where folder='trash' ''') - self.cur.execute('''delete from sent where folder='trash' ''') - self.conn.commit() - self.cur.execute( ''' VACUUM ''') - else: - parameters = shared.sqlSubmitQueue.get() - # print 'item', item - # print 'parameters', parameters - try: - self.cur.execute(item, parameters) - except Exception as err: - 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('This program shall now abruptly exit!\n') - shared.printLock.release() - os._exit(0) - - shared.sqlReturnQueue.put(self.cur.fetchall()) - # shared.sqlSubmitQueue.task_done() - - -'''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) - -It cleans these tables on the disk: - inventory (clears data more than 2 days and 12 hours old) - pubkeys (clears pubkeys older than 4 weeks old which we have not used personally) - -It resends messages when there has been no response: - resends getpubkey 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): - - def __init__(self): - threading.Thread.__init__(self) - - def run(self): - timeWeLastClearedInventoryAndPubkeysTables = 0 - - while True: - shared.sqlLock.acquire() - shared.UISignalQueue.put(( - 'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)')) - for hash, storedValue in shared.inventory.items(): - objectType, streamNumber, payload, receivedTime = storedValue - if int(time.time()) - 3600 > receivedTime: - t = (hash, objectType, streamNumber, payload, receivedTime) - shared.sqlSubmitQueue.put( - '''INSERT INTO inventory VALUES (?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - del shared.inventory[hash] - shared.sqlSubmitQueue.put('commit') - shared.UISignalQueue.put(('updateStatusBar', '')) - 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. - # 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'): - shared.UISignalQueue.queue.clear() - if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380: - timeWeLastClearedInventoryAndPubkeysTables = int(time.time()) - # inventory (moves data from the inventory data structure to - # the on-disk sql database) - shared.sqlLock.acquire() - # inventory (clears pubkeys after 28 days and everything else - # after 2 days and 12 hours) - t = (int(time.time()) - lengthOfTimeToLeaveObjectsInInventory, int( - time.time()) - lengthOfTimeToHoldOnToAllPubkeys) - shared.sqlSubmitQueue.put( - '''DELETE FROM inventory WHERE (receivedtime'pubkey') OR (receivedtime (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))): - print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.' - 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. - except: - pass - - shared.UISignalQueue.put(( - 'updateStatusBar', 'Doing work necessary to again attempt to request a public key...')) - t = (int( - time.time()), pubkeyretrynumber + 1, toripe) - shared.sqlSubmitQueue.put( - '''UPDATE sent SET lastactiontime=?, pubkeyretrynumber=?, status='msgqueued' WHERE toripe=?''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.workerQueue.put(('sendmessage', '')) - else: # status == msgsent - 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.' - t = (int( - time.time()), msgretrynumber + 1, 'msgqueued', ackdata) - shared.sqlSubmitQueue.put( - '''UPDATE sent SET lastactiontime=?, msgretrynumber=?, status=? WHERE ackdata=?''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.workerQueue.put(('sendmessage', '')) - shared.UISignalQueue.put(( - 'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...')) - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - time.sleep(300) # This thread, of which there is only one, does the heavy lifting: # calculating POWs. diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py new file mode 100644 index 00000000..999cda26 --- /dev/null +++ b/src/class_singleCleaner.py @@ -0,0 +1,122 @@ +import threading +import shared +import time +from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers + +'''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) + +It cleans these tables on the disk: + inventory (clears data more than 2 days and 12 hours old) + pubkeys (clears pubkeys older than 4 weeks old which we have not used personally) + +It resends messages when there has been no response: + resends getpubkey 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): + + def __init__(self): + threading.Thread.__init__(self) + + def run(self): + timeWeLastClearedInventoryAndPubkeysTables = 0 + + while True: + shared.sqlLock.acquire() + shared.UISignalQueue.put(( + 'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)')) + for hash, storedValue in shared.inventory.items(): + objectType, streamNumber, payload, receivedTime = storedValue + if int(time.time()) - 3600 > receivedTime: + t = (hash, objectType, streamNumber, payload, receivedTime) + shared.sqlSubmitQueue.put( + '''INSERT INTO inventory VALUES (?,?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + del shared.inventory[hash] + shared.sqlSubmitQueue.put('commit') + shared.UISignalQueue.put(('updateStatusBar', '')) + 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. + # 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'): + shared.UISignalQueue.queue.clear() + if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380: + timeWeLastClearedInventoryAndPubkeysTables = int(time.time()) + # inventory (moves data from the inventory data structure to + # the on-disk sql database) + shared.sqlLock.acquire() + # inventory (clears pubkeys after 28 days and everything else + # after 2 days and 12 hours) + t = (int(time.time()) - lengthOfTimeToLeaveObjectsInInventory, int( + time.time()) - lengthOfTimeToHoldOnToAllPubkeys) + shared.sqlSubmitQueue.put( + '''DELETE FROM inventory WHERE (receivedtime'pubkey') OR (receivedtime (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))): + print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.' + 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. + except: + pass + + shared.UISignalQueue.put(( + 'updateStatusBar', 'Doing work necessary to again attempt to request a public key...')) + t = (int( + time.time()), pubkeyretrynumber + 1, toripe) + shared.sqlSubmitQueue.put( + '''UPDATE sent SET lastactiontime=?, pubkeyretrynumber=?, status='msgqueued' WHERE toripe=?''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.workerQueue.put(('sendmessage', '')) + else: # status == msgsent + 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.' + t = (int( + time.time()), msgretrynumber + 1, 'msgqueued', ackdata) + shared.sqlSubmitQueue.put( + '''UPDATE sent SET lastactiontime=?, msgretrynumber=?, status=? WHERE ackdata=?''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.workerQueue.put(('sendmessage', '')) + shared.UISignalQueue.put(( + 'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...')) + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + time.sleep(300) diff --git a/src/class_singleListener.py b/src/class_singleListener.py new file mode 100644 index 00000000..9e982a24 --- /dev/null +++ b/src/class_singleListener.py @@ -0,0 +1,76 @@ +import threading +import shared +import socket + +# 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): + + def __init__(self): + threading.Thread.__init__(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. + while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': + time.sleep(300) + + shared.printLock.acquire() + print 'Listening for incoming connections.' + shared.printLock.release() + HOST = '' # Symbolic name meaning all available interfaces + PORT = shared.config.getint('bitmessagesettings', 'port') + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # This option apparently avoids the TIME_WAIT state so that we can + # rebind faster + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind((HOST, PORT)) + sock.listen(2) + + while True: + # We don't want to accept incoming connections if the user is using + # a SOCKS proxy. If the user eventually select proxy 'none' then + # this will start listening for connections. + while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': + time.sleep(10) + while len(shared.connectedHostsList) > 220: + shared.printLock.acquire() + print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' + shared.printLock.release() + time.sleep(10) + 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. + while HOST in shared.connectedHostsList: + shared.printLock.acquire() + print 'We are already connected to', HOST + '. Ignoring connection.' + shared.printLock.release() + a.close() + a, (HOST, PORT) = sock.accept() + objectsOfWhichThisRemoteNodeIsAlreadyAware = {} + a.settimeout(20) + + sd = sendDataThread() + sd.setup( + a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) + sd.start() + + rd = receiveDataThread() + rd.daemon = True # close the main program even if there are threads left + rd.setup( + a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) + rd.start() + + shared.printLock.acquire() + print self, 'connected to', HOST, 'during INCOMING request.' + shared.printLock.release() diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py new file mode 100644 index 00000000..e483284f --- /dev/null +++ b/src/class_sqlThread.py @@ -0,0 +1,255 @@ +import threading +import shared +import sqlite3 +import time + +# 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): + + def __init__(self): + threading.Thread.__init__(self) + + def run(self): + self.conn = sqlite3.connect(shared.appdata + 'messages.dat') + self.conn.text_factory = str + self.cur = self.conn.cursor() + try: + self.cur.execute( + '''CREATE TABLE inbox (msgid blob, toaddress text, fromaddress text, subject text, received text, message text, folder text, encodingtype int, read bool, UNIQUE(msgid) ON CONFLICT REPLACE)''' ) + 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)''' ) + self.cur.execute( + '''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: + # 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. + # 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. + 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('lastvacuumtime',?)''', ( + int(time.time()),)) + self.conn.commit() + print 'Created messages database file' + except Exception as err: + if str(err) == 'table inbox already exists': + shared.printLock.acquire() + print 'Database file already exists.' + shared.printLock.release() + else: + sys.stderr.write( + 'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err)) + os._exit(0) + + # 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: + item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' ''' + parameters = '' + self.cur.execute(item, parameters) + self.conn.commit() + + shared.config.set('bitmessagesettings', 'settingsversion', '3') + with open(shared.appdata + 'keys.dat', 'wb') as 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. + if shared.config.getint('bitmessagesettings', 'settingsversion') == 3: + item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' ''' + parameters = '' + self.cur.execute(item, parameters) + + item = '''ALTER TABLE inbox ADD read bool DEFAULT '1' ''' + parameters = '' + self.cur.execute(item, parameters) + + item = '''ALTER TABLE sent ADD encodingtype int DEFAULT '2' ''' + parameters = '' + self.cur.execute(item, parameters) + self.conn.commit() + + shared.config.set('bitmessagesettings', 'settingsversion', '4') + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + + if shared.config.getint('bitmessagesettings', 'settingsversion') == 4: + shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str( + shared.networkDefaultProofOfWorkNonceTrialsPerByte)) + shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str( + shared.networkDefaultPayloadLengthExtraBytes)) + shared.config.set('bitmessagesettings', 'settingsversion', '5') + + if shared.config.getint('bitmessagesettings', 'settingsversion') == 5: + shared.config.set( + 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0') + shared.config.set( + 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0') + shared.config.set('bitmessagesettings', 'settingsversion', '6') + with open(shared.appdata + 'keys.dat', 'wb') as 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. + item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';''' + parameters = '' + self.cur.execute(item, parameters) + if self.cur.fetchall() == []: + # The settings table doesn't exist. We need to make it. + 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( '''INSERT INTO settings VALUES('version','1')''') + self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( + int(time.time()),)) + 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( + '''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM 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( + '''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM 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.' + self.cur.execute( + '''delete from inventory where objecttype = 'pubkey';''') + print 'replacing Bitmessage announcements mailing list with a new one.' + self.cur.execute( + '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' ''') + self.cur.execute( + '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') + print 'Commiting.' + self.conn.commit() + print 'Vacuuming message.dat. You might notice that the file size gets much smaller.' + self.cur.execute( ''' VACUUM ''') + + # After code refactoring, the possible status values for sent messages + # as changed. + self.cur.execute( + '''update sent set status='doingmsgpow' where status='doingpow' ''') + 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() + + try: + testpayload = '\x00\x00' + t = ('1234', testpayload, '12345678', 'no') + self.cur.execute( '''INSERT INTO pubkeys VALUES(?,?,?,?)''', t) + self.conn.commit() + self.cur.execute( + '''SELECT transmitdata FROM pubkeys WHERE hash='1234' ''') + queryreturn = self.cur.fetchall() + for row in queryreturn: + transmitdata, = row + self.cur.execute('''DELETE FROM pubkeys WHERE hash='1234' ''') + self.conn.commit() + 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('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) + except Exception as 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. + item = '''SELECT value FROM settings WHERE key='lastvacuumtime';''' + parameters = '' + self.cur.execute(item, parameters) + queryreturn = self.cur.fetchall() + for row in queryreturn: + value, = row + if int(value) < int(time.time()) - 2592000: + print 'It has been a long time since the messages.dat file has been vacuumed. Vacuuming now...' + self.cur.execute( ''' VACUUM ''') + item = '''update settings set value=? WHERE key='lastvacuumtime';''' + parameters = (int(time.time()),) + self.cur.execute(item, parameters) + + while True: + item = shared.sqlSubmitQueue.get() + if item == 'commit': + self.conn.commit() + elif item == 'exit': + self.conn.close() + shared.printLock.acquire() + print 'sqlThread exiting gracefully.' + shared.printLock.release() + return + elif item == 'movemessagstoprog': + shared.printLock.acquire() + print 'the sqlThread is moving the messages.dat file to the local program directory.' + shared.printLock.release() + self.conn.commit() + self.conn.close() + shutil.move( + shared.lookupAppdataFolder() + 'messages.dat', 'messages.dat') + self.conn = sqlite3.connect('messages.dat') + self.conn.text_factory = str + self.cur = self.conn.cursor() + elif item == 'movemessagstoappdata': + shared.printLock.acquire() + print 'the sqlThread is moving the messages.dat file to the Appdata folder.' + shared.printLock.release() + self.conn.commit() + self.conn.close() + shutil.move( + 'messages.dat', shared.lookupAppdataFolder() + 'messages.dat') + self.conn = sqlite3.connect(shared.appdata + 'messages.dat') + self.conn.text_factory = str + self.cur = self.conn.cursor() + elif item == 'deleteandvacuume': + self.cur.execute('''delete from inbox where folder='trash' ''') + self.cur.execute('''delete from sent where folder='trash' ''') + self.conn.commit() + self.cur.execute( ''' VACUUM ''') + else: + parameters = shared.sqlSubmitQueue.get() + # print 'item', item + # print 'parameters', parameters + try: + self.cur.execute(item, parameters) + except Exception as err: + 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('This program shall now abruptly exit!\n') + shared.printLock.release() + os._exit(0) + + shared.sqlReturnQueue.put(self.cur.fetchall()) + # shared.sqlSubmitQueue.task_done() From 423e83d77c97bae5a29ef51c5e7e5392dc394687 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Thu, 20 Jun 2013 23:55:04 +0100 Subject: [PATCH 16/93] Split off some bootstrap and startup helper functions into their own files --- src/bitmessagemain.py | 132 +++------------------------------------- src/helper_bootstrap.py | 44 ++++++++++++++ src/helper_startup.py | 92 ++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+), 124 deletions(-) create mode 100644 src/helper_bootstrap.py create mode 100644 src/helper_startup.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 5bc7ed31..d2d92a61 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -53,6 +53,10 @@ from class_singleListener import * from class_sqlThread import * from class_singleCleaner import * +# Helper Functions +import helper_startup +import helper_bootstrap + # For each stream to which we connect, several outgoingSynSender threads # will exist and will collectively create 8 connections with peers. @@ -4364,129 +4368,11 @@ 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 os._exit(0) - # First try to load the config file (the keys.dat file) from the program - # directory - shared.config = ConfigParser.SafeConfigParser() - shared.config.read('keys.dat') - try: - shared.config.get('bitmessagesettings', 'settingsversion') - print 'Loading config files from same directory as program' - shared.appdata = '' - except: - # Could not load the keys.dat file in the program directory. Perhaps it - # is in the appdata directory. - shared.appdata = shared.lookupAppdataFolder() - shared.config = ConfigParser.SafeConfigParser() - shared.config.read(shared.appdata + 'keys.dat') - try: - shared.config.get('bitmessagesettings', 'settingsversion') - print 'Loading existing config files from', shared.appdata - except: - # 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.set('bitmessagesettings', 'settingsversion', '6') - shared.config.set('bitmessagesettings', 'port', '8444') - shared.config.set( - 'bitmessagesettings', 'timeformat', '%%a, %%d %%b %%Y %%I:%%M %%p') - shared.config.set('bitmessagesettings', 'blackwhitelist', 'black') - shared.config.set('bitmessagesettings', 'startonlogon', 'false') - 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. - else: - shared.config.set( - 'bitmessagesettings', 'minimizetotray', 'true') - shared.config.set( - 'bitmessagesettings', 'showtraynotifications', 'true') - shared.config.set('bitmessagesettings', 'startintray', 'false') - shared.config.set('bitmessagesettings', 'socksproxytype', 'none') - shared.config.set( - 'bitmessagesettings', 'sockshostname', 'localhost') - shared.config.set('bitmessagesettings', 'socksport', '9050') - shared.config.set( - 'bitmessagesettings', 'socksauthentication', 'false') - shared.config.set('bitmessagesettings', 'socksusername', '') - shared.config.set('bitmessagesettings', 'sockspassword', '') - shared.config.set('bitmessagesettings', 'keysencrypted', 'false') - shared.config.set( - 'bitmessagesettings', 'messagesencrypted', 'false') - 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', 'maxacceptablenoncetrialsperbyte', '0') - shared.config.set( - 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0') + helper_startup.loadConfig() - if storeConfigFilesInSameDirectoryAsProgramByDefault: - # Just use the same directory as the program and forget about - # the appdata folder - shared.appdata = '' - print 'Creating new config files in same directory as program.' - else: - print 'Creating new config files in', shared.appdata - if not os.path.exists(shared.appdata): - os.makedirs(shared.appdata) - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - 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', 'socksproxytype', 'none') - shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') - shared.config.set('bitmessagesettings', 'socksport', '9050') - shared.config.set('bitmessagesettings', 'socksauthentication', 'false') - shared.config.set('bitmessagesettings', 'socksusername', '') - shared.config.set('bitmessagesettings', 'sockspassword', '') - shared.config.set('bitmessagesettings', 'keysencrypted', 'false') - shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - try: - # 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') - shared.knownNodes = pickle.load(pickleFile) - pickleFile.close() - except: - createDefaultKnownNodes(shared.appdata) - pickleFile = open(shared.appdata + 'knownnodes.dat', 'rb') - shared.knownNodes = pickle.load(pickleFile) - pickleFile.close() - if shared.config.getint('bitmessagesettings', 'settingsversion') > 6: - print 'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.' - 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. - if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none': - try: - for item in socket.getaddrinfo('bootstrap8080.bitmessage.org', 80): - print 'Adding', item[4][0], 'to knownNodes based on DNS boostrap method' - shared.knownNodes[1][item[4][0]] = (8080, int(time.time())) - except: - print 'bootstrap8080.bitmessage.org DNS bootstraping failed.' - try: - for item in socket.getaddrinfo('bootstrap8444.bitmessage.org', 80): - print 'Adding', item[4][0], 'to knownNodes based on DNS boostrap method' - shared.knownNodes[1][item[4][0]] = (8444, int(time.time())) - except: - print 'bootstrap8444.bitmessage.org DNS bootstrapping failed.' - else: - print 'DNS bootstrap skipped because SOCKS is used.' + helper_bootstrap.knownNodes() + helper_bootstrap.dns() + # Start the address generation thread addressGeneratorThread = addressGenerator() addressGeneratorThread.daemon = True # close the main program even if there are threads left @@ -4540,8 +4426,6 @@ if __name__ == "__main__": if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): try: - from PyQt4.QtCore import * - from PyQt4.QtGui import * from PyQt4 import QtCore, QtGui 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' diff --git a/src/helper_bootstrap.py b/src/helper_bootstrap.py new file mode 100644 index 00000000..2dcd285c --- /dev/null +++ b/src/helper_bootstrap.py @@ -0,0 +1,44 @@ +import shared +import socket +import defaultKnownNodes +import pickle + +def knownNodes(): + try: + # 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') + shared.knownNodes = pickle.load(pickleFile) + pickleFile.close() + except: + defaultKnownNodes.createDefaultKnownNodes(shared.appdata) + pickleFile = open(shared.appdata + 'knownnodes.dat', 'rb') + shared.knownNodes = pickle.load(pickleFile) + pickleFile.close() + if shared.config.getint('bitmessagesettings', 'settingsversion') > 6: + print 'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.' + raise SystemExit + + +def dns(): + # 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': + try: + for item in socket.getaddrinfo('bootstrap8080.bitmessage.org', 80): + print 'Adding', item[4][0], 'to knownNodes based on DNS boostrap method' + shared.knownNodes[1][item[4][0]] = (8080, int(time.time())) + except: + print 'bootstrap8080.bitmessage.org DNS bootstraping failed.' + try: + for item in socket.getaddrinfo('bootstrap8444.bitmessage.org', 80): + print 'Adding', item[4][0], 'to knownNodes based on DNS boostrap method' + shared.knownNodes[1][item[4][0]] = (8444, int(time.time())) + except: + print 'bootstrap8444.bitmessage.org DNS bootstrapping failed.' + else: + print 'DNS bootstrap skipped because SOCKS is used.' + diff --git a/src/helper_startup.py b/src/helper_startup.py new file mode 100644 index 00000000..b7e9e607 --- /dev/null +++ b/src/helper_startup.py @@ -0,0 +1,92 @@ +import shared +import ConfigParser +import time + +def loadConfig(): + # First try to load the config file (the keys.dat file) from the program + # directory + shared.config = ConfigParser.SafeConfigParser() + shared.config.read('keys.dat') + try: + shared.config.get('bitmessagesettings', 'settingsversion') + print 'Loading config files from same directory as program' + shared.appdata = '' + except: + # Could not load the keys.dat file in the program directory. Perhaps it + # is in the appdata directory. + shared.appdata = shared.lookupAppdataFolder() + shared.config = ConfigParser.SafeConfigParser() + shared.config.read(shared.appdata + 'keys.dat') + try: + shared.config.get('bitmessagesettings', 'settingsversion') + print 'Loading existing config files from', shared.appdata + except: + # 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.set('bitmessagesettings', 'settingsversion', '6') + shared.config.set('bitmessagesettings', 'port', '8444') + shared.config.set( + 'bitmessagesettings', 'timeformat', '%%a, %%d %%b %%Y %%I:%%M %%p') + shared.config.set('bitmessagesettings', 'blackwhitelist', 'black') + shared.config.set('bitmessagesettings', 'startonlogon', 'false') + 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. + else: + shared.config.set( + 'bitmessagesettings', 'minimizetotray', 'true') + shared.config.set( + 'bitmessagesettings', 'showtraynotifications', 'true') + shared.config.set('bitmessagesettings', 'startintray', 'false') + shared.config.set('bitmessagesettings', 'socksproxytype', 'none') + shared.config.set( + 'bitmessagesettings', 'sockshostname', 'localhost') + shared.config.set('bitmessagesettings', 'socksport', '9050') + shared.config.set( + 'bitmessagesettings', 'socksauthentication', 'false') + shared.config.set('bitmessagesettings', 'socksusername', '') + shared.config.set('bitmessagesettings', 'sockspassword', '') + shared.config.set('bitmessagesettings', 'keysencrypted', 'false') + shared.config.set( + 'bitmessagesettings', 'messagesencrypted', 'false') + 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', 'maxacceptablenoncetrialsperbyte', '0') + shared.config.set( + 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0') + + if storeConfigFilesInSameDirectoryAsProgramByDefault: + # Just use the same directory as the program and forget about + # the appdata folder + shared.appdata = '' + print 'Creating new config files in same directory as program.' + else: + print 'Creating new config files in', shared.appdata + if not os.path.exists(shared.appdata): + os.makedirs(shared.appdata) + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + + 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', 'socksproxytype', 'none') + shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') + shared.config.set('bitmessagesettings', 'socksport', '9050') + shared.config.set('bitmessagesettings', 'socksauthentication', 'false') + shared.config.set('bitmessagesettings', 'socksusername', '') + shared.config.set('bitmessagesettings', 'sockspassword', '') + shared.config.set('bitmessagesettings', 'keysencrypted', 'false') + shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) From 138877f5f7d424abc837e594ab6b22bfffda4665 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Fri, 21 Jun 2013 00:25:01 +0100 Subject: [PATCH 17/93] Placed repeated inbox and sent SQL operations into appropriate helper functions --- src/bitmessagemain.py | 68 +++++++++++-------------------------------- src/helper_inbox.py | 22 ++++++++++++++ src/helper_sent.py | 11 +++++++ 3 files changed, 50 insertions(+), 51 deletions(-) create mode 100644 src/helper_inbox.py create mode 100644 src/helper_sent.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index d2d92a61..8e336fdc 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -56,6 +56,8 @@ from class_singleCleaner import * # Helper Functions import helper_startup import helper_bootstrap +import helper_inbox +import helper_sent # For each stream to which we connect, several outgoingSynSender threads # will exist and will collectively create 8 connections with peers. @@ -742,15 +744,11 @@ class receiveDataThread(threading.Thread): toAddress = '[Broadcast subscribers]' if messageEncodingType != 0: - shared.sqlLock.acquire() + t = (self.inventoryHash, toAddress, fromAddress, subject, int( time.time()), body, 'inbox', messageEncodingType, 0) - shared.sqlSubmitQueue.put( - '''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_inbox.insert(t) + shared.UISignalQueue.put(('displayNewInboxMessage', ( self.inventoryHash, toAddress, fromAddress, subject, body))) @@ -902,15 +900,11 @@ class receiveDataThread(threading.Thread): toAddress = '[Broadcast subscribers]' if messageEncodingType != 0: - shared.sqlLock.acquire() + t = (self.inventoryHash, toAddress, fromAddress, subject, int( time.time()), body, 'inbox', messageEncodingType, 0) - shared.sqlSubmitQueue.put( - '''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_inbox.insert(t) + shared.UISignalQueue.put(('displayNewInboxMessage', ( self.inventoryHash, toAddress, fromAddress, subject, body))) @@ -1226,15 +1220,10 @@ class receiveDataThread(threading.Thread): body = 'Unknown encoding type.\n\n' + repr(message) subject = '' if messageEncodingType != 0: - shared.sqlLock.acquire() t = (self.inventoryHash, toAddress, fromAddress, subject, int( time.time()), body, 'inbox', messageEncodingType, 0) - shared.sqlSubmitQueue.put( - '''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_inbox.insert(t) + shared.UISignalQueue.put(('displayNewInboxMessage', ( self.inventoryHash, toAddress, fromAddress, subject, body))) @@ -1269,15 +1258,10 @@ class receiveDataThread(threading.Thread): 32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating. toAddress = '[Broadcast subscribers]' ripe = '' - shared.sqlLock.acquire() + t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int( time.time()), 'broadcastqueued', 1, 1, 'sent', 2) - shared.sqlSubmitQueue.put( - '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_sent.insert(t) shared.UISignalQueue.put(('displayNewSentMessage', ( toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata))) @@ -4046,15 +4030,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): if len(params) == 0: return 'API Error 0000: I need parameters!' msgid = params[0].decode('hex') - t = (msgid,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE inbox SET folder='trash' WHERE msgid=?''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid)) + helper_inbox.trash(msgid) return 'Trashed inbox message (assuming message existed).' elif method == 'trashSentMessage': if len(params) == 0: @@ -4126,15 +4102,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): return 'API Error 0014: Your fromAddress is disabled. Cannot send.' ackdata = OpenSSL.rand(32) - shared.sqlLock.acquire() + t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int( time.time()), 'msgqueued', 1, 1, 'sent', 2) - shared.sqlSubmitQueue.put( - '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_sent.insert(t) toLabel = '' t = (toAddress,) @@ -4195,15 +4166,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): toAddress = '[Broadcast subscribers]' ripe = '' - shared.sqlLock.acquire() + t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int( time.time()), 'broadcastqueued', 1, 1, 'sent', 2) - shared.sqlSubmitQueue.put( - '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() + helper_sent.insert(t) toLabel = '[Broadcast subscribers]' shared.UISignalQueue.put(('displayNewSentMessage', ( diff --git a/src/helper_inbox.py b/src/helper_inbox.py new file mode 100644 index 00000000..fc420825 --- /dev/null +++ b/src/helper_inbox.py @@ -0,0 +1,22 @@ +import shared + +def insert(t): + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + +def trash(msgid): + t = (msgid,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE inbox SET folder='trash' WHERE msgid=?''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid)) + diff --git a/src/helper_sent.py b/src/helper_sent.py new file mode 100644 index 00000000..dcfe844e --- /dev/null +++ b/src/helper_sent.py @@ -0,0 +1,11 @@ +import shared + +def insert(t): + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + From b64bbda82aafa1eca09e225dc6fbc7cd458784eb Mon Sep 17 00:00:00 2001 From: Joshua Noble Date: Fri, 21 Jun 2013 00:54:11 -0400 Subject: [PATCH 18/93] Added folder to select statement for getInboxMessagesByAddress --- src/bitmessagemain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 79d1b6af..db4db315 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4422,7 +4422,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): toAddress = params[0] v = (toAddress,) shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE toAddress=?''') + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE folder='inbox' AND toAddress=?''') shared.sqlSubmitQueue.put(v) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() From 894de2da34b95728d85153b5e7b6a0922f95d9c9 Mon Sep 17 00:00:00 2001 From: Joshua Noble Date: Fri, 21 Jun 2013 00:55:24 -0400 Subject: [PATCH 19/93] Changed received to receivedTime --- src/bitmessagemain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index db4db315..4279a259 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4433,7 +4433,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' - data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'received':received},indent=4, separators=(',', ': ')) + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'receivedTime':received},indent=4, separators=(',', ': ')) data += ']}' return data elif method == 'getSentMessageById': From 8f81c35a6f48d26d2562cd9e12adde95ebae40fe Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Fri, 21 Jun 2013 10:10:13 +0100 Subject: [PATCH 20/93] Split off a few generic functions and Bitcoin related functions in seperate helper files --- src/bitmessagemain.py | 94 ++++--------------------------------------- src/helper_bitcoin.py | 43 ++++++++++++++++++++ src/helper_generic.py | 33 +++++++++++++++ 3 files changed, 84 insertions(+), 86 deletions(-) create mode 100644 src/helper_bitcoin.py create mode 100644 src/helper_generic.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 8e336fdc..7f30fc64 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -58,6 +58,8 @@ import helper_startup import helper_bootstrap import helper_inbox import helper_sent +import helper_generic +import helper_bitcoin # For each stream to which we connect, several outgoingSynSender threads # will exist and will collectively create 8 connections with peers. @@ -1131,7 +1133,7 @@ class receiveDataThread(threading.Thread): print 'ECDSA verify failed', err return shared.printLock.acquire() - print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' + print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' shared.printLock.release() # calculate the fromRipe. sha = hashlib.new('sha512') @@ -1867,7 +1869,7 @@ class receiveDataThread(threading.Thread): if data[28 + lengthOfNumberOfAddresses + (34 * i)] == '\x7F': print 'Ignoring IP address in loopback range:', hostFromAddrMessage continue - if isHostInPrivateIPRange(hostFromAddrMessage): + if helper_generic.isHostInPrivateIPRange(hostFromAddrMessage): print 'Ignoring IP address in private range:', hostFromAddrMessage continue timeSomeoneElseReceivedMessageFromThisNode, = unpack('>I', data[lengthOfNumberOfAddresses + ( @@ -2065,7 +2067,7 @@ class receiveDataThread(threading.Thread): for i in range(500): random.seed() HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) - if isHostInPrivateIPRange(HOST): + if helper_generic.isHostInPrivateIPRange(HOST): continue addrsInMyStream[HOST] = shared.knownNodes[ self.streamNumber][HOST] @@ -2074,7 +2076,7 @@ class receiveDataThread(threading.Thread): random.seed() HOST, = random.sample(shared.knownNodes[ self.streamNumber * 2], 1) - if isHostInPrivateIPRange(HOST): + if helper_generic.isHostInPrivateIPRange(HOST): continue addrsInChildStreamLeft[HOST] = shared.knownNodes[ self.streamNumber * 2][HOST] @@ -2083,7 +2085,7 @@ class receiveDataThread(threading.Thread): random.seed() HOST, = random.sample(shared.knownNodes[ (self.streamNumber * 2) + 1], 1) - if isHostInPrivateIPRange(HOST): + if helper_generic.isHostInPrivateIPRange(HOST): continue addrsInChildStreamRight[HOST] = shared.knownNodes[ (self.streamNumber * 2) + 1][HOST] @@ -2421,71 +2423,6 @@ def isInSqlInventory(hash): return True -def convertIntToString(n): - a = __builtins__.hex(n) - if a[-1:] == 'L': - a = a[:-1] - if (len(a) % 2) == 0: - return a[2:].decode('hex') - else: - return ('0' + a[2:]).decode('hex') - - -def convertStringToInt(s): - return int(s.encode('hex'), 16) - - -# This function expects that pubkey begin with \x04 -def calculateBitcoinAddressFromPubkey(pubkey): - 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.' - return "error" - ripe = hashlib.new('ripemd160') - sha = hashlib.new('sha256') - sha.update(pubkey) - ripe.update(sha.digest()) - ripeWithProdnetPrefix = '\x00' + ripe.digest() - - checksum = hashlib.sha256(hashlib.sha256( - ripeWithProdnetPrefix).digest()).digest()[:4] - binaryBitcoinAddress = ripeWithProdnetPrefix + checksum - numberOfZeroBytesOnBinaryBitcoinAddress = 0 - while binaryBitcoinAddress[0] == '\x00': - numberOfZeroBytesOnBinaryBitcoinAddress += 1 - binaryBitcoinAddress = binaryBitcoinAddress[1:] - base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) - return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded - - -def calculateTestnetAddressFromPubkey(pubkey): - 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.' - return "error" - ripe = hashlib.new('ripemd160') - sha = hashlib.new('sha256') - sha.update(pubkey) - ripe.update(sha.digest()) - ripeWithProdnetPrefix = '\x6F' + ripe.digest() - - checksum = hashlib.sha256(hashlib.sha256( - ripeWithProdnetPrefix).digest()).digest()[:4] - binaryBitcoinAddress = ripeWithProdnetPrefix + checksum - numberOfZeroBytesOnBinaryBitcoinAddress = 0 - while binaryBitcoinAddress[0] == '\x00': - numberOfZeroBytesOnBinaryBitcoinAddress += 1 - binaryBitcoinAddress = binaryBitcoinAddress[1:] - base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) - return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded - - -def signal_handler(signal, frame): - if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): - shared.doCleanShutdown() - sys.exit(0) - else: - print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.' - - def connectToStream(streamNumber): selfInitiatedConnections[streamNumber] = {} if sys.platform[0:3] == 'win': @@ -2563,21 +2500,6 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] return datatosend + payload - -def isHostInPrivateIPRange(host): - if host[:3] == '10.': - return True - if host[:4] == '172.': - if host[6] == '.': - if int(host[4:6]) >= 16 and int(host[4:6]) <= 31: - return True - if host[:8] == '192.168.': - return True - return False - - - - # This thread, of which there is only one, does the heavy lifting: # calculating POWs. @@ -4326,7 +4248,7 @@ if __name__ == "__main__": # is the application already running? If yes then exit. thisapp = singleton.singleinstance() - signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGINT, helper_generic.signal_handler) # signal.signal(signal.SIGINT, signal.SIG_DFL) # Check the Major version, the first element in the array diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py new file mode 100644 index 00000000..9ac966d6 --- /dev/null +++ b/src/helper_bitcoin.py @@ -0,0 +1,43 @@ +import hashlib + +# This function expects that pubkey begin with \x04 +def calculateBitcoinAddressFromPubkey(pubkey): + 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.' + return "error" + ripe = hashlib.new('ripemd160') + sha = hashlib.new('sha256') + sha.update(pubkey) + ripe.update(sha.digest()) + ripeWithProdnetPrefix = '\x00' + ripe.digest() + + checksum = hashlib.sha256(hashlib.sha256( + ripeWithProdnetPrefix).digest()).digest()[:4] + binaryBitcoinAddress = ripeWithProdnetPrefix + checksum + numberOfZeroBytesOnBinaryBitcoinAddress = 0 + while binaryBitcoinAddress[0] == '\x00': + numberOfZeroBytesOnBinaryBitcoinAddress += 1 + binaryBitcoinAddress = binaryBitcoinAddress[1:] + base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) + return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded + + +def calculateTestnetAddressFromPubkey(pubkey): + 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.' + return "error" + ripe = hashlib.new('ripemd160') + sha = hashlib.new('sha256') + sha.update(pubkey) + ripe.update(sha.digest()) + ripeWithProdnetPrefix = '\x6F' + ripe.digest() + + checksum = hashlib.sha256(hashlib.sha256( + ripeWithProdnetPrefix).digest()).digest()[:4] + binaryBitcoinAddress = ripeWithProdnetPrefix + checksum + numberOfZeroBytesOnBinaryBitcoinAddress = 0 + while binaryBitcoinAddress[0] == '\x00': + numberOfZeroBytesOnBinaryBitcoinAddress += 1 + binaryBitcoinAddress = binaryBitcoinAddress[1:] + base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) + return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded diff --git a/src/helper_generic.py b/src/helper_generic.py new file mode 100644 index 00000000..99c1c2d3 --- /dev/null +++ b/src/helper_generic.py @@ -0,0 +1,33 @@ +import shared + +def convertIntToString(n): + a = __builtins__.hex(n) + if a[-1:] == 'L': + a = a[:-1] + if (len(a) % 2) == 0: + return a[2:].decode('hex') + else: + return ('0' + a[2:]).decode('hex') + + +def convertStringToInt(s): + return int(s.encode('hex'), 16) + + +def signal_handler(signal, frame): + if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): + shared.doCleanShutdown() + sys.exit(0) + else: + print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.' + +def isHostInPrivateIPRange(host): + if host[:3] == '10.': + return True + if host[:4] == '172.': + if host[6] == '.': + if int(host[4:6]) >= 16 and int(host[4:6]) <= 31: + return True + if host[:8] == '192.168.': + return True + return False From 0b258be363c6d1ca10ec8188f74ab79769d4eb3e Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Fri, 21 Jun 2013 12:58:36 +0100 Subject: [PATCH 21/93] Fixed missing arithmetic import in helper_bitcoin file --- src/helper_bitcoin.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py index 9ac966d6..d56e395b 100644 --- a/src/helper_bitcoin.py +++ b/src/helper_bitcoin.py @@ -1,4 +1,5 @@ import hashlib +from pyelliptic import arithmetic # This function expects that pubkey begin with \x04 def calculateBitcoinAddressFromPubkey(pubkey): From e7fffe7ecde2074b8133a54801c9709d5f938518 Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Fri, 21 Jun 2013 13:44:37 +0100 Subject: [PATCH 22/93] Seperated out class_addressGenerator - not perfectly --- src/bitmessagemain.py | 279 ++-------------------------------- src/class_addressGenerator.py | 276 +++++++++++++++++++++++++++++++++ 2 files changed, 292 insertions(+), 263 deletions(-) create mode 100644 src/class_addressGenerator.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 7f30fc64..1ced22ac 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -52,6 +52,7 @@ import proofofwork from class_singleListener import * from class_sqlThread import * from class_singleCleaner import * +from class_addressGenerator import * # Helper Functions import helper_startup @@ -2434,34 +2435,6 @@ def connectToStream(streamNumber): a.setup(streamNumber) a.start() -# Does an EC point multiplication; turns a private key into a public key. - - -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. - k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1')) - priv_key = OpenSSL.BN_bin2bn(secret, 32, 0) - group = OpenSSL.EC_KEY_get0_group(k) - pub_key = OpenSSL.EC_POINT_new(group) - - OpenSSL.EC_POINT_mul(group, pub_key, priv_key, None, None, None) - OpenSSL.EC_KEY_set_private_key(k, priv_key) - OpenSSL.EC_KEY_set_public_key(k, pub_key) - # print 'priv_key',priv_key - # print 'pub_key',pub_key - - size = OpenSSL.i2o_ECPublicKey(k, 0) - mb = ctypes.create_string_buffer(size) - OpenSSL.i2o_ECPublicKey(k, ctypes.byref(ctypes.pointer(mb))) - # print 'mb.raw', mb.raw.encode('hex'), 'length:', len(mb.raw) - # print 'mb.raw', mb.raw, 'length:', len(mb.raw) - - OpenSSL.EC_POINT_free(pub_key) - # OpenSSL.BN_CTX_free(ctx) - OpenSSL.BN_free(priv_key) - OpenSSL.EC_KEY_free(k) - return mb.raw def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): @@ -3350,241 +3323,6 @@ class singleWorker(threading.Thread): return headerData + payload -class addressGenerator(threading.Thread): - - def __init__(self): - # QThread.__init__(self, parent) - threading.Thread.__init__(self) - - def run(self): - while True: - queueValue = shared.addressGeneratorQueue.get() - nonceTrialsPerByte = 0 - payloadLengthExtraBytes = 0 - if len(queueValue) == 7: - command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue - elif len(queueValue) == 9: - command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue - 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) - 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) - if nonceTrialsPerByte == 0: - nonceTrialsPerByte = shared.config.getint( - 'bitmessagesettings', 'defaultnoncetrialsperbyte') - if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: - nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte - if payloadLengthExtraBytes == 0: - payloadLengthExtraBytes = shared.config.getint( - 'bitmessagesettings', 'defaultpayloadlengthextrabytes') - if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: - payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - if addressVersionNumber == 3: # currently the only one supported. - if command == 'createRandomAddress': - shared.UISignalQueue.put(( - 'updateStatusBar', _translate("MainWindow", "Generating one new address"))) - # 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, - # we won't store the \x00 or \x00\x00 bytes thus making the - # address shorter. - startTime = time.time() - numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 - potentialPrivSigningKey = OpenSSL.rand(32) - potentialPubSigningKey = pointMult(potentialPrivSigningKey) - while True: - numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 - potentialPrivEncryptionKey = OpenSSL.rand(32) - potentialPubEncryptionKey = pointMult( - potentialPrivEncryptionKey) - # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') - # print 'potentialPubEncryptionKey', - # potentialPubEncryptionKey.encode('hex') - ripe = hashlib.new('ripemd160') - sha = hashlib.new('sha512') - sha.update( - potentialPubSigningKey + potentialPubEncryptionKey) - ripe.update(sha.digest()) - # print 'potential ripe.digest', - # ripe.digest().encode('hex') - if eighteenByteRipe: - if ripe.digest()[:2] == '\x00\x00': - break - else: - if ripe.digest()[:1] == '\x00': - break - print 'Generated address with ripe digest:', ripe.digest().encode('hex') - print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.' - address = encodeAddress(3, streamNumber, ripe.digest()) - - # 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 - privSigningKey = '\x80' + potentialPrivSigningKey - checksum = hashlib.sha256(hashlib.sha256( - privSigningKey).digest()).digest()[0:4] - privSigningKeyWIF = arithmetic.changebase( - privSigningKey + checksum, 256, 58) - # print 'privSigningKeyWIF',privSigningKeyWIF - - privEncryptionKey = '\x80' + potentialPrivEncryptionKey - checksum = hashlib.sha256(hashlib.sha256( - privEncryptionKey).digest()).digest()[0:4] - privEncryptionKeyWIF = arithmetic.changebase( - privEncryptionKey + checksum, 256, 58) - # print 'privEncryptionKeyWIF',privEncryptionKeyWIF - - shared.config.add_section(address) - shared.config.set(address, 'label', label) - shared.config.set(address, 'enabled', 'true') - shared.config.set(address, 'decoy', 'false') - shared.config.set(address, 'noncetrialsperbyte', str( - nonceTrialsPerByte)) - shared.config.set(address, 'payloadlengthextrabytes', str( - payloadLengthExtraBytes)) - shared.config.set( - address, 'privSigningKey', privSigningKeyWIF) - shared.config.set( - address, 'privEncryptionKey', privEncryptionKeyWIF) - with open(shared.appdata + 'keys.dat', 'wb') as 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. - apiAddressGeneratorReturnQueue.put(address) - - shared.UISignalQueue.put(( - 'updateStatusBar', _translate("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) - shared.UISignalQueue.put(('writeNewAddressToTable', ( - label, address, streamNumber))) - shared.reloadMyAddressHashes() - shared.workerQueue.put(( - 'doPOWForMyV3Pubkey', ripe.digest())) - - elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress': - 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.') - if command == 'createDeterministicAddresses': - statusbar = 'Generating ' + str( - numberOfAddressesToMake) + ' new addresses.' - shared.UISignalQueue.put(( - 'updateStatusBar', statusbar)) - signingKeyNonce = 0 - 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. - - for i in range(numberOfAddressesToMake): - # 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 - # into a Bitmessage address, we won't store the \x00 or - # \x00\x00 bytes thus making the address shorter. - startTime = time.time() - numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 - while True: - numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 - potentialPrivSigningKey = hashlib.sha512( - deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] - potentialPrivEncryptionKey = hashlib.sha512( - deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] - potentialPubSigningKey = pointMult( - potentialPrivSigningKey) - potentialPubEncryptionKey = pointMult( - potentialPrivEncryptionKey) - # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') - # print 'potentialPubEncryptionKey', - # potentialPubEncryptionKey.encode('hex') - signingKeyNonce += 2 - encryptionKeyNonce += 2 - ripe = hashlib.new('ripemd160') - sha = hashlib.new('sha512') - sha.update( - potentialPubSigningKey + potentialPubEncryptionKey) - ripe.update(sha.digest()) - # print 'potential ripe.digest', - # ripe.digest().encode('hex') - if eighteenByteRipe: - if ripe.digest()[:2] == '\x00\x00': - break - else: - if ripe.digest()[:1] == '\x00': - break - - print 'ripe.digest', ripe.digest().encode('hex') - print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.' - address = encodeAddress(3, streamNumber, ripe.digest()) - - if command == 'createDeterministicAddresses': - # 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 - privSigningKey = '\x80' + potentialPrivSigningKey - checksum = hashlib.sha256(hashlib.sha256( - privSigningKey).digest()).digest()[0:4] - privSigningKeyWIF = arithmetic.changebase( - privSigningKey + checksum, 256, 58) - - privEncryptionKey = '\x80' + \ - potentialPrivEncryptionKey - checksum = hashlib.sha256(hashlib.sha256( - privEncryptionKey).digest()).digest()[0:4] - privEncryptionKeyWIF = arithmetic.changebase( - privEncryptionKey + checksum, 256, 58) - - try: - shared.config.add_section(address) - print 'label:', label - shared.config.set(address, 'label', label) - shared.config.set(address, 'enabled', 'true') - shared.config.set(address, 'decoy', 'false') - shared.config.set(address, 'noncetrialsperbyte', str( - nonceTrialsPerByte)) - shared.config.set(address, 'payloadlengthextrabytes', str( - payloadLengthExtraBytes)) - shared.config.set( - address, 'privSigningKey', privSigningKeyWIF) - shared.config.set( - address, 'privEncryptionKey', privEncryptionKeyWIF) - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - shared.UISignalQueue.put(('writeNewAddressToTable', ( - label, address, str(streamNumber)))) - listOfNewAddressesToSendOutThroughTheAPI.append( - address) - # 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.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( - potentialPrivEncryptionKey.encode('hex')) - shared.myAddressesByHash[ - ripe.digest()] = address - shared.workerQueue.put(( - 'doPOWForMyV3Pubkey', ripe.digest())) - except: - print address, 'already exists. Not adding it again.' - - # Done generating addresses. - 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. - apiAddressGeneratorReturnQueue.put( - listOfNewAddressesToSendOutThroughTheAPI) - shared.UISignalQueue.put(( - 'updateStatusBar', _translate("MainWindow", "Done generating address"))) - # shared.reloadMyAddressHashes() - elif command == 'getDeterministicAddress': - apiAddressGeneratorReturnQueue.put(address) - else: - 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 class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros). @@ -4341,6 +4079,21 @@ if __name__ == "__main__": while True: time.sleep(20) +def translateText(context, text): + if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): + try: + from PyQt4 import QtCore, QtGui + 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 'Error message:', err + os._exit(0) + return QtGui.QApplication.translate(context, text) + else: + if '%' in text: + return translateClass(context, text.replace('%','',1)) + else: + return text + # So far, the creation of and management of the Bitmessage protocol and this # client is a one-man operation. Bitcoin tips are quite appreciated. diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py new file mode 100644 index 00000000..3059bc90 --- /dev/null +++ b/src/class_addressGenerator.py @@ -0,0 +1,276 @@ +import shared +import threading +import bitmessagemain +import time +from pyelliptic.openssl import OpenSSL +import ctypes +import hashlib +from addresses import * + +class addressGenerator(threading.Thread): + + def __init__(self): + # QThread.__init__(self, parent) + threading.Thread.__init__(self) + + def run(self): + while True: + queueValue = shared.addressGeneratorQueue.get() + nonceTrialsPerByte = 0 + payloadLengthExtraBytes = 0 + if len(queueValue) == 7: + command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue + elif len(queueValue) == 9: + command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue + 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) + 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) + if nonceTrialsPerByte == 0: + nonceTrialsPerByte = shared.config.getint( + 'bitmessagesettings', 'defaultnoncetrialsperbyte') + if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: + nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte + if payloadLengthExtraBytes == 0: + payloadLengthExtraBytes = shared.config.getint( + 'bitmessagesettings', 'defaultpayloadlengthextrabytes') + if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: + payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes + if addressVersionNumber == 3: # currently the only one supported. + if command == 'createRandomAddress': + shared.UISignalQueue.put(( + 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Generating one new address"))) + # 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, + # we won't store the \x00 or \x00\x00 bytes thus making the + # address shorter. + startTime = time.time() + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 + potentialPrivSigningKey = OpenSSL.rand(32) + potentialPubSigningKey = pointMult(potentialPrivSigningKey) + while True: + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 + potentialPrivEncryptionKey = OpenSSL.rand(32) + potentialPubEncryptionKey = pointMult( + potentialPrivEncryptionKey) + # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') + # print 'potentialPubEncryptionKey', + # potentialPubEncryptionKey.encode('hex') + ripe = hashlib.new('ripemd160') + sha = hashlib.new('sha512') + sha.update( + potentialPubSigningKey + potentialPubEncryptionKey) + ripe.update(sha.digest()) + # print 'potential ripe.digest', + # ripe.digest().encode('hex') + if eighteenByteRipe: + if ripe.digest()[:2] == '\x00\x00': + break + else: + if ripe.digest()[:1] == '\x00': + break + print 'Generated address with ripe digest:', ripe.digest().encode('hex') + print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.' + address = encodeAddress(3, streamNumber, ripe.digest()) + + # 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 + privSigningKey = '\x80' + potentialPrivSigningKey + checksum = hashlib.sha256(hashlib.sha256( + privSigningKey).digest()).digest()[0:4] + privSigningKeyWIF = arithmetic.changebase( + privSigningKey + checksum, 256, 58) + # print 'privSigningKeyWIF',privSigningKeyWIF + + privEncryptionKey = '\x80' + potentialPrivEncryptionKey + checksum = hashlib.sha256(hashlib.sha256( + privEncryptionKey).digest()).digest()[0:4] + privEncryptionKeyWIF = arithmetic.changebase( + privEncryptionKey + checksum, 256, 58) + # print 'privEncryptionKeyWIF',privEncryptionKeyWIF + + shared.config.add_section(address) + shared.config.set(address, 'label', label) + shared.config.set(address, 'enabled', 'true') + shared.config.set(address, 'decoy', 'false') + shared.config.set(address, 'noncetrialsperbyte', str( + nonceTrialsPerByte)) + shared.config.set(address, 'payloadlengthextrabytes', str( + payloadLengthExtraBytes)) + shared.config.set( + address, 'privSigningKey', privSigningKeyWIF) + shared.config.set( + address, 'privEncryptionKey', privEncryptionKeyWIF) + with open(shared.appdata + 'keys.dat', 'wb') as 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. + bitmessagemain.apiAddressGeneratorReturnQueue.put(address) + + shared.UISignalQueue.put(( + 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) + shared.UISignalQueue.put(('writeNewAddressToTable', ( + label, address, streamNumber))) + shared.reloadMyAddressHashes() + shared.workerQueue.put(( + 'doPOWForMyV3Pubkey', ripe.digest())) + + elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress': + 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.') + if command == 'createDeterministicAddresses': + statusbar = 'Generating ' + str( + numberOfAddressesToMake) + ' new addresses.' + shared.UISignalQueue.put(( + 'updateStatusBar', statusbar)) + signingKeyNonce = 0 + 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. + + for i in range(numberOfAddressesToMake): + # 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 + # into a Bitmessage address, we won't store the \x00 or + # \x00\x00 bytes thus making the address shorter. + startTime = time.time() + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 + while True: + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 + potentialPrivSigningKey = hashlib.sha512( + deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] + potentialPrivEncryptionKey = hashlib.sha512( + deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] + potentialPubSigningKey = pointMult( + potentialPrivSigningKey) + potentialPubEncryptionKey = pointMult( + potentialPrivEncryptionKey) + # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') + # print 'potentialPubEncryptionKey', + # potentialPubEncryptionKey.encode('hex') + signingKeyNonce += 2 + encryptionKeyNonce += 2 + ripe = hashlib.new('ripemd160') + sha = hashlib.new('sha512') + sha.update( + potentialPubSigningKey + potentialPubEncryptionKey) + ripe.update(sha.digest()) + # print 'potential ripe.digest', + # ripe.digest().encode('hex') + if eighteenByteRipe: + if ripe.digest()[:2] == '\x00\x00': + break + else: + if ripe.digest()[:1] == '\x00': + break + + print 'ripe.digest', ripe.digest().encode('hex') + print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.' + address = encodeAddress(3, streamNumber, ripe.digest()) + + if command == 'createDeterministicAddresses': + # 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 + privSigningKey = '\x80' + potentialPrivSigningKey + checksum = hashlib.sha256(hashlib.sha256( + privSigningKey).digest()).digest()[0:4] + privSigningKeyWIF = arithmetic.changebase( + privSigningKey + checksum, 256, 58) + + privEncryptionKey = '\x80' + \ + potentialPrivEncryptionKey + checksum = hashlib.sha256(hashlib.sha256( + privEncryptionKey).digest()).digest()[0:4] + privEncryptionKeyWIF = arithmetic.changebase( + privEncryptionKey + checksum, 256, 58) + + try: + shared.config.add_section(address) + print 'label:', label + shared.config.set(address, 'label', label) + shared.config.set(address, 'enabled', 'true') + shared.config.set(address, 'decoy', 'false') + shared.config.set(address, 'noncetrialsperbyte', str( + nonceTrialsPerByte)) + shared.config.set(address, 'payloadlengthextrabytes', str( + payloadLengthExtraBytes)) + shared.config.set( + address, 'privSigningKey', privSigningKeyWIF) + shared.config.set( + address, 'privEncryptionKey', privEncryptionKeyWIF) + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + + shared.UISignalQueue.put(('writeNewAddressToTable', ( + label, address, str(streamNumber)))) + listOfNewAddressesToSendOutThroughTheAPI.append( + address) + # 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.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( + potentialPrivEncryptionKey.encode('hex')) + shared.myAddressesByHash[ + ripe.digest()] = address + shared.workerQueue.put(( + 'doPOWForMyV3Pubkey', ripe.digest())) + except: + print address, 'already exists. Not adding it again.' + + # Done generating addresses. + 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. + bitmessagemain.apiAddressGeneratorReturnQueue.put( + listOfNewAddressesToSendOutThroughTheAPI) + shared.UISignalQueue.put(( + 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address"))) + # shared.reloadMyAddressHashes() + elif command == 'getDeterministicAddress': + bitmessagemain.apiAddressGeneratorReturnQueue.put(address) + else: + raise Exception( + "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command) + + +# Does an EC point multiplication; turns a private key into a public key. + + +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. + k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1')) + priv_key = OpenSSL.BN_bin2bn(secret, 32, 0) + group = OpenSSL.EC_KEY_get0_group(k) + pub_key = OpenSSL.EC_POINT_new(group) + + OpenSSL.EC_POINT_mul(group, pub_key, priv_key, None, None, None) + OpenSSL.EC_KEY_set_private_key(k, priv_key) + OpenSSL.EC_KEY_set_public_key(k, pub_key) + # print 'priv_key',priv_key + # print 'pub_key',pub_key + + size = OpenSSL.i2o_ECPublicKey(k, 0) + mb = ctypes.create_string_buffer(size) + OpenSSL.i2o_ECPublicKey(k, ctypes.byref(ctypes.pointer(mb))) + # print 'mb.raw', mb.raw.encode('hex'), 'length:', len(mb.raw) + # print 'mb.raw', mb.raw, 'length:', len(mb.raw) + + OpenSSL.EC_POINT_free(pub_key) + # OpenSSL.BN_CTX_free(ctx) + OpenSSL.BN_free(priv_key) + OpenSSL.EC_KEY_free(k) + return mb.raw + + From c2cfff2a2e9b3fabb9a2f637491a5a1ab912ba0e Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Fri, 21 Jun 2013 13:55:09 +0100 Subject: [PATCH 23/93] Reworked translate function to be more accommodating --- src/bitmessagemain.py | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 1ced22ac..e6bd90eb 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4058,27 +4058,18 @@ if __name__ == "__main__": print 'Error message:', err os._exit(0) - try: - _encoding = QtGui.QApplication.UnicodeUTF8 - def _translate(context, text): # A non-QT version of _translate is defined below. - return QtGui.QApplication.translate(context, text) - except Exception as err: - print 'Error:', err - import bitmessageqt bitmessageqt.run() else: - def _translate(context, text): # A QT version of _translate is defined above. - if '%' in text: - return translateClass(context, text.replace('%','',1)) - else: - return text shared.printLock.acquire() print 'Running as a daemon. You can use Ctrl+C to exit.' shared.printLock.release() while True: time.sleep(20) +def _translate(context, text): + return translateText(context, text) + def translateText(context, text): if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): try: From d2d2d8c3808546e996e36945dc23e1da97b68b26 Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Fri, 21 Jun 2013 16:24:04 +0100 Subject: [PATCH 24/93] Fixed translate functions not being found as they were being defined after the QT GUI was started --- src/bitmessagemain.py | 83 +++++++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 42 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index e6bd90eb..4383b0ac 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -193,7 +193,7 @@ class outgoingSynSender(threading.Thread): shared.printLock.release() except socks.Socks5AuthError as err: shared.UISignalQueue.put(( - 'updateStatusBar', _translate( + 'updateStatusBar', translateText( "MainWindow", "SOCKS5 Authentication problem: %1").arg(str(err)))) except socks.Socks5Error as err: pass @@ -1022,7 +1022,7 @@ class receiveDataThread(threading.Thread): shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], _translate("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) return else: @@ -2734,7 +2734,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -2769,7 +2769,7 @@ class singleWorker(threading.Thread): payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) print '(For broadcast message) Doing proof of work...' shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Doing work necessary to send broadcast...")))) + ackdata, translateText("MainWindow", "Doing work necessary to send broadcast...")))) initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce @@ -2784,7 +2784,7 @@ class singleWorker(threading.Thread): shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, _translate("MainWindow", "Broadcast sent on %1").arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Broadcast sent on %1").arg(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 @@ -2808,7 +2808,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -2856,7 +2856,7 @@ class singleWorker(threading.Thread): payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) print '(For broadcast message) Doing proof of work...' shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Doing work necessary to send broadcast...")))) + ackdata, translateText("MainWindow", "Doing work necessary to send broadcast...")))) initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce @@ -2871,7 +2871,7 @@ class singleWorker(threading.Thread): shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, _translate("MainWindow", "Broadcast sent on %1").arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Broadcast sent on %1").arg(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 @@ -2929,7 +2929,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, _translate("MainWindow",'Encryption key was requested earlier.')))) + toripe, translateText("MainWindow",'Encryption key was requested earlier.')))) else: # We have not yet sent a request for the pubkey t = (toaddress,) @@ -2941,7 +2941,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, _translate("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + toripe, translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) self.requestPubKey(toaddress) shared.sqlLock.acquire() # Get all messages that are ready to be sent, and also all messages @@ -2983,7 +2983,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, _translate("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + toripe, translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) self.requestPubKey(toaddress) continue ackdataForWhichImWatching[ackdata] = 0 @@ -2992,7 +2992,7 @@ class singleWorker(threading.Thread): fromStatus, fromAddressVersionNumber, fromStreamNumber, fromHash = decodeAddress( fromaddress) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Looking up the receiver\'s public key")))) + ackdata, translateText("MainWindow", "Looking up the receiver\'s public key")))) shared.printLock.acquire() print 'Found a message in our database that needs to be sent with this pubkey.' print 'First 150 characters of message:', repr(message[:150]) @@ -3055,7 +3055,7 @@ class singleWorker(threading.Thread): requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) + ackdata, translateText("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) elif toAddressVersionNumber == 3: requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( pubkeyPayload[readPosition:readPosition + 10]) @@ -3067,7 +3067,7 @@ class singleWorker(threading.Thread): requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, _translate("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes))))) 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): @@ -3081,7 +3081,7 @@ class singleWorker(threading.Thread): shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, _translate("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes)).arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) continue @@ -3102,7 +3102,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -3148,7 +3148,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, _translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -3205,7 +3205,7 @@ class singleWorker(threading.Thread): queryreturn = shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,_translate("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) + shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,translateText("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) continue encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) @@ -3228,7 +3228,7 @@ class singleWorker(threading.Thread): objectType = 'msg' shared.inventory[inventoryHash] = ( objectType, toStreamNumber, encryptedPayload, int(time.time())) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, _translate("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(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') shared.broadcastToSendDataQueues(( @@ -3266,7 +3266,7 @@ class singleWorker(threading.Thread): statusbar = 'Doing the computations necessary to request the recipient\'s public key.' shared.UISignalQueue.put(('updateStatusBar', statusbar)) shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - ripe, _translate("MainWindow",'Doing work necessary to request encryption key.')))) + ripe, translateText("MainWindow",'Doing work necessary to request encryption key.')))) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) initialHash = hashlib.sha512(payload).digest() @@ -3294,8 +3294,8 @@ class singleWorker(threading.Thread): shared.sqlLock.release() shared.UISignalQueue.put(( - 'updateStatusBar', _translate("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) - shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, _translate("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( + 'updateStatusBar', translateText("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) + shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime): @@ -3947,7 +3947,7 @@ class singleAPI(threading.Thread): se.register_introspection_functions() se.serve_forever() -# This is used so that the _translate function can be used when we are in daemon mode and not using any QT functions. +# This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions. class translateClass: def __init__(self, context, text): self.context = context @@ -3958,6 +3958,24 @@ class translateClass: else: return self.text +def _translate(context, text): + return translateText(context, text) + +def translateText(context, text): + if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): + try: + from PyQt4 import QtCore, QtGui + 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 'Error message:', err + os._exit(0) + return QtGui.QApplication.translate(context, text) + else: + if '%' in text: + return translateClass(context, text.replace('%','',1)) + else: + return text + selfInitiatedConnections = {} # This is a list of current connections (the thread pointers at least) @@ -4067,25 +4085,6 @@ if __name__ == "__main__": while True: time.sleep(20) -def _translate(context, text): - return translateText(context, text) - -def translateText(context, text): - if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): - try: - from PyQt4 import QtCore, QtGui - 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 'Error message:', err - os._exit(0) - return QtGui.QApplication.translate(context, text) - else: - if '%' in text: - return translateClass(context, text.replace('%','',1)) - else: - return text - - # So far, the creation of and management of the Bitmessage protocol and this # client is a one-man operation. Bitcoin tips are quite appreciated. # 1H5XaDA6fYENLbknwZyjiYXYPQaFjjLX2u From af9dbda5d37321e1a5472208e4c69c5fa5ce0a7e Mon Sep 17 00:00:00 2001 From: Jaxkr Date: Fri, 21 Jun 2013 12:26:33 -0600 Subject: [PATCH 25/93] Fixed capitalization of Application Support, which causes problems for people with a case sensitive OS X file system --- src/shared.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared.py b/src/shared.py index 256008c1..031585a0 100644 --- a/src/shared.py +++ b/src/shared.py @@ -39,7 +39,7 @@ def lookupAppdataFolder(): from os import path, environ if sys.platform == 'darwin': if "HOME" in environ: - dataFolder = path.join(os.environ["HOME"], "Library/Application support/", APPNAME) + '/' + dataFolder = path.join(os.environ["HOME"], "Library/Application Support/", APPNAME) + '/' else: print 'Could not find home folder, please report this message and your OS X version to the BitMessage Github.' sys.exit() From 32aaaf20234bea3cf217513493337374a8ddfa07 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 21 Jun 2013 15:44:28 -0400 Subject: [PATCH 26/93] Fix bugs in githup pull request #238 --- src/bitmessagemain.py | 79 ++++++++++++++++++++++++++++++++--- src/class_addressGenerator.py | 1 + src/class_singleListener.py | 76 --------------------------------- src/class_sqlThread.py | 1 + src/helper_bootstrap.py | 1 + 5 files changed, 76 insertions(+), 82 deletions(-) delete mode 100644 src/class_singleListener.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 4383b0ac..52e89846 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -19,7 +19,6 @@ useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the encryptedBroadcastSwitchoverTime = 1369735200 import sys -import ConfigParser import Queue from addresses import * import shared @@ -33,13 +32,11 @@ import pickle import random import sqlite3 from time import strftime, localtime, gmtime -import shutil # used for moving the messages.dat file import string import socks import highlevelcrypto from pyelliptic.openssl import OpenSSL -import ctypes -from pyelliptic import arithmetic +#import ctypes import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. # The next 3 are used for the API from SimpleXMLRPCServer import * @@ -49,7 +46,6 @@ import singleton import proofofwork # Classes -from class_singleListener import * from class_sqlThread import * from class_singleCleaner import * from class_addressGenerator import * @@ -223,10 +219,81 @@ class outgoingSynSender(threading.Thread): 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) + +class singleListener(threading.Thread): + + def __init__(self): + threading.Thread.__init__(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. + while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': + time.sleep(300) + + shared.printLock.acquire() + print 'Listening for incoming connections.' + shared.printLock.release() + HOST = '' # Symbolic name meaning all available interfaces + PORT = shared.config.getint('bitmessagesettings', 'port') + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # This option apparently avoids the TIME_WAIT state so that we can + # rebind faster + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind((HOST, PORT)) + sock.listen(2) + + while True: + # We don't want to accept incoming connections if the user is using + # a SOCKS proxy. If the user eventually select proxy 'none' then + # this will start listening for connections. + while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': + time.sleep(10) + while len(shared.connectedHostsList) > 220: + shared.printLock.acquire() + print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' + shared.printLock.release() + time.sleep(10) + 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. + while HOST in shared.connectedHostsList: + shared.printLock.acquire() + print 'We are already connected to', HOST + '. Ignoring connection.' + shared.printLock.release() + a.close() + a, (HOST, PORT) = sock.accept() + objectsOfWhichThisRemoteNodeIsAlreadyAware = {} + a.settimeout(20) + + sd = sendDataThread() + sd.setup( + a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) + sd.start() + + rd = receiveDataThread() + rd.daemon = True # close the main program even if there are threads left + rd.setup( + a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) + rd.start() + + shared.printLock.acquire() + print self, 'connected to', HOST, 'during INCOMING request.' + shared.printLock.release() + # This thread is created either by the synSenderThread(for outgoing # connections) or the singleListenerThread(for incoming connectiosn). - class receiveDataThread(threading.Thread): def __init__(self): diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 3059bc90..e22fdd51 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -6,6 +6,7 @@ from pyelliptic.openssl import OpenSSL import ctypes import hashlib from addresses import * +from pyelliptic import arithmetic class addressGenerator(threading.Thread): diff --git a/src/class_singleListener.py b/src/class_singleListener.py deleted file mode 100644 index 9e982a24..00000000 --- a/src/class_singleListener.py +++ /dev/null @@ -1,76 +0,0 @@ -import threading -import shared -import socket - -# 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): - - def __init__(self): - threading.Thread.__init__(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. - while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': - time.sleep(300) - - shared.printLock.acquire() - print 'Listening for incoming connections.' - shared.printLock.release() - HOST = '' # Symbolic name meaning all available interfaces - PORT = shared.config.getint('bitmessagesettings', 'port') - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - # This option apparently avoids the TIME_WAIT state so that we can - # rebind faster - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.bind((HOST, PORT)) - sock.listen(2) - - while True: - # We don't want to accept incoming connections if the user is using - # a SOCKS proxy. If the user eventually select proxy 'none' then - # this will start listening for connections. - while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': - time.sleep(10) - while len(shared.connectedHostsList) > 220: - shared.printLock.acquire() - print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' - shared.printLock.release() - time.sleep(10) - 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. - while HOST in shared.connectedHostsList: - shared.printLock.acquire() - print 'We are already connected to', HOST + '. Ignoring connection.' - shared.printLock.release() - a.close() - a, (HOST, PORT) = sock.accept() - objectsOfWhichThisRemoteNodeIsAlreadyAware = {} - a.settimeout(20) - - sd = sendDataThread() - sd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) - sd.start() - - rd = receiveDataThread() - rd.daemon = True # close the main program even if there are threads left - rd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) - rd.start() - - shared.printLock.acquire() - print self, 'connected to', HOST, 'during INCOMING request.' - shared.printLock.release() diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index e483284f..210a78e3 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -2,6 +2,7 @@ import threading import shared import sqlite3 import time +import shutil # used for moving the messages.dat file # 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 diff --git a/src/helper_bootstrap.py b/src/helper_bootstrap.py index 2dcd285c..296dda6b 100644 --- a/src/helper_bootstrap.py +++ b/src/helper_bootstrap.py @@ -2,6 +2,7 @@ import shared import socket import defaultKnownNodes import pickle +import time def knownNodes(): try: From 85ea62d678f32087444ff53f1cc9ab73af6a65b8 Mon Sep 17 00:00:00 2001 From: Jaxkr Date: Fri, 21 Jun 2013 14:13:59 -0600 Subject: [PATCH 27/93] Added icns with transparency --- src/images/bitmessage.icns | Bin 39467 -> 32984 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/images/bitmessage.icns b/src/images/bitmessage.icns index a796f9d46a94f3562bf5a283857c7d943d3c78e4..5fe52d4e37f925df8d458316a15cbe5fb794c4ae 100644 GIT binary patch literal 32984 zcmeI52YeM(`uB%k6|5*If+8rrN^c^FqO$6`y6f)WwiaAm0F!y0*1)V?}X)d$s`sTQ{L32`F$Uu#o`%SXW z#o>UtC)dAxUI^x1+p^*LxH*a{uXRRjBmw))~}FDQeVfpecMX=fqkk*M*F9L;|~BP0_o!Trl^{mRB!e=H7mM>u+$# z!3`h&37k3^x$)(er`L|TlzYrxd^i8LOWWgWV!96|A`jel>#fVzY<_Obh66_yLF(Lx zR{vU~G%5J$2X_o+p7mMT1*WHb|GdF%WCt&I%jf%swvfg0n0o;-Z0hcYSgd$NJs;7; z^h<{`Bgoh#2Ol4?`2$xEe1HYlI6@4mLB^NX@qKNlkx5!IQxoWH;-(^#Gjk}u&Sn`N zTR)v!q|@VSi2PJ!(&_A+GgS>tei||{D=DLxSpWA!$k^7_-b2XDMw7|lR9g*N1BF=Vc|HjAlkG;p<+MyufzGL1>ES*2%V^g6mG^)}a4om356l4maM&xdbn5dk- z6lC&?&%ANAwVA;bKqH@8_wd3G7%Wj5GU?52>sK#%i={e^OxV9|$F`lHWFli#}la{;p;@fd}T&^NRHbd@Ttp^>lV_Sv8I&9B^F;so@`2 za~%m>msxam*D-!B*Rh$p5w4@lz0E%Jutm}Hzs1pj>z>=Xed~?^*X4a>^+9e}U`T z2BXewaB3P2S|g2Io1T_i01=rn4R?ieynYt$>`Dydk)R~r%<$7oS3>KrDGQ7_=Cg+hx)Dds@baX4(f&B)VP z8yk%fbu5La*=GXRd5sWtRI#)Y}#@ z)A_yNx|g4S`+Qr7%@#u=pWC!#>0g*}*S)iA%leh?a@63uU+>!e#Gb!H)cyX~&tR_m zAl`wEAJH-Vz$^cMH~WO`=^xL$W);S7%J;{jN5)?x!@TsS7%Zw;*GNBvrN*MU*K*ER zklK$PoPCYMk)6Jn|Jd?@9(c~3W8>Lwzklw$IS;lMieGXA!muN+#wSFW=u?*CpQwqw7g z)BD=E9p9#3xN7=p6r3WNjZD1f&Z`|hmyWr#>#3`y!M-qq75d>F=(`@R^y zt6iRNw;xN63FcnDdwA=&Q7pOj#o--StlW9J71EE4@cI=QCht3g7R|Y0=VhCd@4Z&E zT$b&>ZsWjv*bRKrni$-Nnvt=U7qn-QiT$;8{H9=ADKd#tN7n|r!oebBS`3e;qfO!N zuurZpK&F>wWYxJlyE}u5stY>UPD{_pqIb9Iai!H{Z2>YZIlHJJSHe6~PT{Z%k!h(J zS=o67=kYWqpIeAb$vkx;Bkv5AbTOkCnZ(ZgE-kybA^!+62F?Oa>6BQ_86ox zyPZ}`YbZ)No|N(AH^_tTCa2BT+SL_?3O8D;1~sbIN_94eQKe?m@MQ?{mruS!Cdf2; zjmnr{zSrV(!e{_`YgB18Sxri*0yQ?;Q8C(i0(n4YGQxmDr{yW+T8+Y>k*Y)jfmA7! zqDraEXjq$q+$&cr6{v*GSIAJcOe&X~Oo3pqHDJUeOT+N77>u3u4&4wIg29cw7v_>Ni6@rMBdaX1E?x1vq z)!!9u7S-1!izc~Vx{MJgAnG%Y1FJ14*J0-nwi@*u`CQj#+B%V^|^%)uDTDZv$9 zJ;ofgx_FEwXFh#HF?R6!F{U!w{`+FAoFKDZ5o489fhpK>d5n>`8fRNH;?!JS+*j(^3n{ zN(*J|^Hp>{RB2j9Zhk>YNd<|?76~E7a??-c7N2L(s&gR5c)7skLkd@f?DD`WeKST%*^i zjR}@}tuB|^469}oHJPm@RHjs!><(0_>NmhbsffZyRcez#tr5zh z8w;8p8l}!)kg*x4Uc%w{ObVqyY=>@)FBj27GU&!wVxv~8*6E=et0c>9Zd2@>%<6$| z%MRWF~H+&qR$O%@Rx_KF{-}2lsQZ=5HTlhn0WdAYi-R+Zt06rpBOz^;>7p@sum4xiX?K7rMo;+zRGUjh(rDxBbxmZ_Y zwF=neIvOwSQ9z^12kiGg{QR$9`zALx`_$q6@<^wqG|$oPRMZsGYCqVvYTn)V%(`>j z_bNN#zDHr%!svWnz{mQpR|y}qtC3Qj2(+8N?6 z4!rtydF%Ve^QmeViLvTe25`Z7e z+rL?S_jTfU?A!$l9$oN8?zE>pYEgSE`tgX`UVU}KzPxY0I5l?cC#aT0Y5ej!Wyg;n z^R63Czid7-`RTIsO6$M=Q~vcPEFSw)Cm_h}^PYQZ+SMyDymv7L%N~n0t{&cXy_I__ z`v&s&e{{WULunKL(J_!c7TPfI@Ul`y?IHu}9RU9j3rEIYDSon9>DRwAnA#t$s zvDn2shIU^2ckJgw{YK2O{o2`vQ^tQYRGa9(Z|GXxZXP(GA9v-f!f=_Ft&D$;9;bE7 zs>^m?XXCC<*sXoGzyGJ08BxNVeSchk`PDrl@#gA(g$E9Nf=wMP{4-XWfw9ql{!76S zKa5O{#c)MMIEyFPflO)QSC*BtjV_O*6}iRB#FbwpNgZu%%`RUofZP^~5gIBlH1IWc zUu#b^;OmHak%ZW73Vg-+S{O7oHMfPkdwYYvW)E_AEM{WXU96$Y&7S7gaA#L{q_@lK ziMc^QVANJrQ6(lDGjxC6u!pcZ)xxBjzqdU!)+m-O+_x1c36I}CwyA8aW!iExFVX z?Tz-p@omjsiv(AanUQ~?Qe-wG59DW@%FN2i$xc09Z0_&t>BMTFq@2r2&pp?`Ao1;H zWbU!#tnA!^!or-ir1GX%q%G*wvM%POXO-4cSv+bjRP|_bZhm2LNpVqbS_-W*>Ng1L z3ez)+s{m!VY$n5kj6ZfVx1cDY`0k?o?9@ViNZwGIaXRk;fx%*PI1IMmg539AQg&Wp zQBh%GeqMG~HT8UUYWCTBDibpBILt<5^6}*K+`NMPoVo78dZ*oBS6VtdLS7@|Vik#0 zUtV_Z=pkhMnWRIBUlkx@qWyF(A~IdX7YgMjy+)}}x+34k4kOF$8b@cy=W!b4JO+&} zQ0tU6EQ8JE_WFHIUXRP|w5j=0jTxjkd!tTcu0?LK>6JpcMJ<-93`V2jka4Nm)zTA- zA&5n#R4G()I*F~&nauWpUrv{_bUH!F1Bocw+ZXL<)J7S|#F#@RM9rqd##LsMR;5&1 zgMD5u!_nL%mzcf&_DHm^L$39r3c1?ibeUxVzeXYw(AYAe+~{E-WBZ-v!=|+s6Ds0r zb#j%AP30IAGGBLZU#!2sSs=IQ1XQL%t5t~!1TvLUjjO8@E9opbOV)VEIn`#+YUEOx zRAFhOAS=DTCN-HZkaFt?91dTGs`x}QU#WLEP&%0*l*z~{DOI2q$fNWLG=WA|lb4!8Tt==ZDKqxjf`(=$Xx1Ns| zD0Mcc-R^WaY>jq{TJCJKa45(Mk;EwD2vIv~Y6-ekR1!xDy0w_5X=;!3g#8*O(c017 zA`_EDYQ4}C3biG4P45mv=N4{jZPc_ivMI)Z-uu-R=hnJq>!2}ftshz!0! zAQEsn92`p^l*%Mx^2Is_0C)h6_V$F^+rwRv-h{r1(GDYxq18~3i6OTF4R&=Tw5>G@ z$fl-CxdKHz@KLo&&ZE>b?FJfhe@nC8+|%FJ zYgaUOz*J4Rt=Z>w+YAay1Dk|nBv9uNtH~7=6pENlm+{DAhtp;?N@-*PJj1{WF_0Bq zHnp#>ug7Tcb~n3>3OENEwTN0>Re@vUr~(0x*1+d9RMwN(?vUTgV9OGu6HzTupwU@b z$lC5!wZiQ4>UbgnQ=+kXTvm-#NLHAHb$lrr2sPQb5+xs3Tg&c>gaaCopv4l@B0!dP zsI^L&Od_CDIU-Y*VQD{Dv-r`rBoso&?p>{ z7@LRg2-_trB%tDQ8sv7k?z|qmK`ccz0fSIwL&kT96&zLqatEJVD^ba1GAXo5XI2mh z5|3JsOwbFJ7GF;SGBzmZ9YQA1$vnvNrEG%2;L?e0I^aS`cY*p5t$$o ztKA+?f_q9+s3Qz_A(yyCgUkpp%Fo~!LZ!ys)Dl4b(4CDJ@U?+(LS#x01WR8OgjPS~ z9>3OQt%+vCL5 z;CKqP0o;fgfkJvZd?;pwDw2C3N3ergTgQ@tWMXr|paxC~)H7t}QYa)M8+u-3Zlk=R znj%4USUvnLVQ6SH((aN_$s__@qOw34S~aBxI<rU`j~^TD2#ix)gFd-j7{-Y;|X z!|kN6r#oa~H`Eg-Tp^!rM&@NdwRXemrH?#3f6kqEEqlAB4f6DcT@qX^fx;FF*>si> znIHRn-^NXAK{Z+M-~;#Fb?4dy4G?lzORB+=<3q@vR zy6*km8#ixQyK>o*M;9$jSTJMWz3Y?NEIOSdmPuJ0q0o%nuPJjb{Gm9^n3?qzwG4$7x+u7=+d$;=A9Dw0A*+y zCzDU6W>p&_Q4D3eyD(BQ@oS4MI+f8C4Z^*+C?m6^n#=+YVKE0$rZ}NwW^qAITCuT3i9eH> zo?lL4auT>>nVbQX$;mG&E-or6$ji>IrI+WV<(zAvv)LRjp9|gfi#Y^~r?)2o#AOQ08n-QdV~Ax2ZY# z1z_PUiOHnX8Tj%u<$yA^StnC7lD`Ae$S*7^tYEU~bZTXB=KeU!B%L~X6u1c>r?7&- zrq`FHeF-RYHf;c9FvKaWV$o^}PJ9R`b2N@J7~d4vHk{3RA5ex)A3~YToZS49{6Un# zmu9BtVJMT5o_;#{weO)!&-!O=u2tFJlWxHii0=mdrsH8`4@JFkl}bRtb4)0phuV8^vl zhD4%rrKq71#^fD?DC6n63}pxe5|Bq6c3L|lagq2fd5^)rsOl<<52m<6J^iBkn5#cK`FqC1`5!q5yZ*_VDaTo!V@yM9;8k{taGPruW z7>$EYXrRz=KnJKnpt2j088I`lmMl;Ji9pG1U6F*|DKL5$FsLL3sTL!ZZgLHQhoR08 zA@oK&nv_f$%we!7ag?d9XG&Fii`_j)A%Kx44xLJ+h=eQ{CUhX;x*D2TiLskEFhC)| zT4FklLS`uykY#SK3s-~Z#~}j)ggDBC11ii2Rjl+vj+QX1wvH{=0LuZdfd}F|WZ_Z) zRX9p53?v*1Tn#l|4_8xQ0GJ}}ZYdZc(xsY4C_|^E))IsOJ5Y~73;~qUvdCnZ5JE8= z(h70)OgTIr?C|)&&2h$PwF#gIB1^2&L1RK9I-Vrb7;R2ZQ?RuYgPjPtg9@}m7l>s_ zGjgk5%4A5Ptxf(weDKvXt+Uz0A`l4_o=`Z1GN%hk8gF}h3!LT%W(KHBNW?>62nF0Y z$`pR~;*;B-c>ew4czbsb1PM$hLuFNz20W1gfWZNjVSliD#iI|+#Zcx?XPtv6(_-e} z8i-V$SjYvG$=bVS{VITz`E%}?wfvnylyOT4^+cG-5OJBDILbV|VdI)Oq|Bdt_g(7} zwHV6i$aTQFB8h;>5nw3u@~qyVEpQTMJt$>lH@T!})) z;fa8D?$;K*ya^r-TD@}l(j`DL7|N_UOr zbebuEiAfF*P=+lsezPKHE2M17Q^X9FI+ox{ZiXFIN%~PL+0cAGAgG-5zPXdzJ zx@`-FGUK*C{`juM-3d>O-Gzb7)Ia|A`6u^03IBEvkj#f~zVPg`zuNIQkj!^UC%^sm zuQ8G-A1#t0mX;73fkTifK4H!IO0L;GKr$R+WhF)KY;PMT84{tUf*{n|{Ub>RC0A86 za5eU(5b*dVlCiMy)%7f;)f)ox0LtziAepdFX1zz*WNli)1$g4GUM-KtXV491^D5x)nK{*%06js^E%-p=(th93` znBs~=usKH{8RFU8oZ_ll2~2W4P>`LD=@bQ7r_NgX`yyTKEq=R_elb6%=pvCr6*-{u zNKVZwC@MWuT9BDq=^G#!PIXaE-Z>nTD_}H0=aH0JSX^3m_UxI$tPECH)Nc|slw{|g zsiksw0zetak(^doa;EHTSy@RzW~nixB%aUBDyk&0d3?Tr%?pAkb0Vdn_)J;ZnKLCt z`FZt>iu|mCay)~>^3lrKQCeDC|T?sytf(AVbVM zospAr6xvu^T3S-Y<}#U#nlm{sx{)abnJK4F9M6ZOgpx^BOfD0DKJy5GOa(mn`|SxJ z6HuZ`YFLcA;**~M$ecWSC@B-5r>MBB9(O+XuK+SISy6uc>!ef=Y6=RA$_kHxCZkY@ zNawP%O45^))8KjHtdw^KK*lP55;PgQ1vHtES-K>t(_}Ym zWo(ud=BrtJi9(gAnWdh8Mz^`CRL6m_PU4}&&-GC^g7Qv+6VbdxzJb;L5tifI{p9!LjLS`8h zWfa;bl~SRxf+!;o2DDPKfWc9S6>(9f&tW-ie!^l_iFsO`LM`XgK$MaD2Spj7!m1O{ zSW2BvErBr*omNZ0HAqk6KH}Qo2wtl*x5o-*h@9Q!)kapGx)ZQkwfJ!36lm(r_k@AQ{ zc%W1y;qz6fOeEEbF!6#+HU>f-`Q^HdUayMlGAP;{@?g4*NkWFJoqM}xw4bx>nlmQnsxusl6T$izPIRtxW zi%r9j@q{p~2f?q>s1$r^1IuBgAzMI~v0%E4LuqRt)@AHQB^A#h6JWBDMyjDyRne#t z4nxkTN}QN3BV$m7Z~?IgbQ!I`uP1r_>kpG`2;2CGEzIH%ar3eGK0hGYK{g}DCjcd#1geT(KFRO zB+E!zL2e1Ms?HPHpaxidEkRXWmJtecm&r290OS+W08>!vW$E{mQjktsH?SOP?k|QLO#d_Lvjuxk0vnX@UpJg=LeSQOzatlu}lJS zJWU`L2{BowrLHuqn5_1+wS|UQrW@dnOeB#x(1pcWrsRuPp4q+kr4N$`mslq3N9hD2 znI#hQ*uXOUKR>;0#iI)zc;Jy8ADwprfMBu=une9+W(Xt#aO}LiXE$tJj|nC7XU|!E zpl(2xaZ8EyWY9{)96FeqA4}Z7ZTm)$N)|uz@Pl(^Z~RghXBlcefyNO^giJOcW0@nr z+qPp1PzdB&xbVT*5B-6Ru?(?+$`(o_0xHHbC2wupxoy*9t5<;N0&>dyxlfz{;fz6L z0?P<#aAQFpFnsj%wjEnHu8Wh(;zu7{G*tT`kFpDf(xFeGV&x|P8Fy6b5D={D3wG9Ac3lIq=u7G^= z$RBVjwMxO{0?Y6;?>@C1lTx;Bi382LwJX=2Qkhl2GV-$@Y}=Xm`1GAnd>mR}4&1hB|K}aRGTY$^`NX|r_F(Yx_`ZF>GQ0QgeJWvJ;?rZF+V>o= z%zLl>=GkYSg@60@fhzOafsfyP<;53Y+Or2(CMh-T*l%9}mZ_?|F_!rx{@DGF8+q0m zxw+i*z)cU_^uSFI-1NXr58U*?O%L4kzz_An#Bo3Lh@UI}xJeIe*tX^OYvJ9g|CMFV zo?`5K8};k2@jBb+R%+VvkI3!uHy_}-@a#lz)M>r3;Pl4v!2fnUa~y6mVeE! z?EDA|*E?j^{;%P2%*vCq3ad)1JlM%ne$Yt_j|VEI|^>(W#J!a?~3eW?%00*NHS5t!_jcMxi>BgY|Gdo=#SiIqI81DP6$2VO0t;Q?LyK?hn{93V)zIf~EpKCbaHeNheQBiTR zo)BLYSm)B!(cY@pXtlafuo=E^6E6b$)B5#YSC;>uw&y*ze*LcUSj=hu^wEX$m#91FW$Zdl-1#$Yfgy-?R0bK+`~(o0LzP96F8zd!pw2OBo6A6!=d zVDkgjyKl{!Rl9Nxdac2rQ>(OEtp=5X*YlPmNaAqgVv^jWUwo%+?1~w!eifNU`Sy3O z{QBj8oYJ^n`cI9#k@PY5uU@^EaLF31b(^wYsUF;;torxsZ+y7_Yd^ep*xd&oiwTE) z7OS<<3y%)Dk2XAftAqa-%-cVn!>@>U-erf3qVM{Z{o!xcoeyri4 z-8aSXxzm_QcWCZ0r`;{pC`Gq(C`1*=nuRpu}k6bM8@gHk< z=(tb1^Z%v2yaLct_-sM2t+mx6iN;z3#`ai$7xT|)Et&7Vx%<)k@4si}eam;e`4t&_ zg6cZ2!g{Nzu*On8#phR-4WE2u+_n(zpE7%&0BZeamUP`#X5XQcsISJxIWz5AC3%Jf#0@JXE$bE`+2UQ zGdf&_rVnSra_i4zdcbevr#($+3XE7f`eNOW-FonA?7|H0-*+M%k97dp($D)@Ef1Zy zaZ{&{T;6uavhG4AO#WLF^f{FohdxV{4cPCqy*qTsX#S2D#^T>qoAkG~SPWhXi1Z9L zKk(O49cGW2e9MgKn1cne74h~>fv@ZJjOhIRABN_dlxe8#rio-eo;(tmw|6gC_k|ilQ1A z1jqVyuMX|}xqrvMZj5&@m;O9IYb4lA{ZuNGF-Fb&q?L7-EDx@|H}&Uk`{-uaZ~nPQ_0aS9d+|#CaySt^~S?D2UA90NSO5CzdYBnZ&^R;XMf84 zcNEt$-%GfWsjZ(DgLl2~{kzUkeT?sqx{Nh;LDKi`Iz#4THKVWNEXy_wo4azw{I}7L zzKL`Gd8N@y+ksPyMmhS%tUP&X=I4^(!8QKVqdoYT^4r00aevP?>=dkDoNk&4*c!$JyBQ%2k$*-`+A|!l>IHH}8u}Pc4nCMQ_^uV@LVg$F7QTcdR@< zg7=1N5GAge^b43r#!Q&8Ci9ACm!J~ShFz1#jk@#W-NN{3j~)5m?YHR^W6&f?@H@vH~`sS{i9=Pd&n;y97ftwz<>4BRb`2W-c{}&jzbw2^n&N<)jf8MK-3PCsS<({?L^F6`>Ro(sWx%-@b z_TInqzwfR8@HfBSv}y3sw|>3l=}nuyG`oM(`_!iPe(FojpfrBcjT=Fh5Y6jd#kGe)z)X!Hg0d#D>536D#!3+1Zqc0YA}iwe7|`E+Ry z^_4bN(UeRXs{Jl?t#>e)<`mweu4`}}-aTW?y-R(i6}621(PXXB-a}o}E{0vHy%@ys zrq2w<8aHegMaKZE;IyER$y#iVb72EnU!JEVW8GYqS_mrgg`7-3I*?$3!-a zMOU(9JC5;PdGU^Xnad{g;@nuWY*NFY5oczpi?| ztN-}cUy)UNO^mf^2@7Vh^Y8WTHbn)sh4yjk+LT(H>zb@80IjX%{hbAuxj7w1LE_95!VYQna-_t@0jIb*#apSOp)tyQa4sYW50j_c+0 zlgB3n(Hd6w9qDAcP%M_4A-BtGu{t6apTpwtB+6LgUvAY3efe($WLk&AWO3*XCQmFJ zh%~772h^=Gw@afj>oi)q%N>gc?X{1nTN>%GFYML|9WtTI7tgj1P+x78-I+u^Vh)7@ z&4bj}+LS>MO;@ROG9N>9?Wb;PQ9hnGM>$edy<9&;U7usy60J1NdYJlZHOW(jD-9Vp z*KQr8ZmJ~Y#zLm;TGr(2t&gdj>$!8U|En3QNarh})i!>Ri|)VYhqwMp#h04!;RkR< z%qjoZPj3I-FZG&GwswHJrIqp9wTo}P{@e@vP#((>_pisib`@*x$N^fU)at`eZfq9f z0lQYJj8pBy2>E(BpUG7kt;3Xa(`P40*PS4xHr-sCphb3;swin|6ZFZb&pmfu(wU&_ z+|cOM+`J^+nV=*l==k)d^XA59Cdfc0Xi60OJ0{3!b$XJOf4m9Gerke@!uZt_#19lG zXL@~tIQCR4L${F$O7YdvN<+?Do1mn^RLZv8H0|01<4-!VZUeUU^^TBS>`MNoEyiwRQEyA#AcHsN>A&&s+Jv@kY#a$!lD>P%3| zLHlUv^x_56l?bYn2uh_BCgtjxp;IEPvJDXw_PD)Pn>N!k4GnR%0+H}Vl93=*=YvMtk^Lve&PXl|tj25aP<`!>s4unKZ&SC{ z(;=r`Jn_!ap~QM;OVz9{n=KquYdp?K++s-< zQGO&c^^eiYRQk%_EoPiNoyH%ud2AYoOr}<7WO}>BX!ImnNMYY;+0810lp)Y*Jbt~^ zX%6{o)q1mN@t}OUqZJER0`{2K?c}fOm6!Amy~X9QT5a{C)HmC~n9XFh+cj#oF<{^^ z3)WyFQyqZ&3gvvhT=7$0iO*)%>*J%;ty!5RorzFQn=_fMrco!IpuUdYfy=Qa(qa5h zG@33Xf+yg-TPY347C?CrtW#7ulT0=S@Y9!S|b;h(yZP@rI{DgRK>m)x$L$^I^Ymk-NAglVP58% zGZoARCbN|f8x9_jRjEoNN?VmEL&aJPS68Ef|8&n?Klm34sv=mD3N*n&tu;X1-pu)& zzk2%V`)~W^!Q`??DzV|?P&M4%uEd@8)7!T_wfW)O|4OM68-1}t9oILqL6=ee?$+(k zZryU<8I#Hv&y^d;sc*K5F`v^c?O&Rs8V{S~?6s<>8DZx5AGCVnak}YJrH$+qz z5p`g2{ET$|1S|3Bh{}Xr2Fdt4$A+h-PbtFr&xxpF+-~ed)W_reVD|5gC>~#>R~x+v zxax}{s*p`&*CXoAzbB#&|DOw}@}~kSC$nTeC!ly-N9r>HrRCZ~`F1nZ_;f(67=5W) zv%p;os1=nvR%+G^bm>|^VewQ20%s^!Zw1+GJ6TSRTtrT{`ID7aK|)uT)*~t#atdwU zaIsOh(0G>YdPEhXhJzm~YE-2eXRxHoaH$hI?P@IeH+SFl!#_qyiI!y|Z5WZ(2`Rtp zKR)%;{kMPnP-;aimpa1hA(e31&urWJDZh(^)Em#gu=|N$+g*vmT1cfsKBq~+To^`3{lTd~ymUFFQX!wqtP+rr zVmcDp>Xncxq#}N&NiE^Aop z$D)OV)2v}!oEn#&QD3Aw}$PpE*1 zq6;h;WMq<~nuVz8@FxnAqhhOUc_*Tfqbl+6e|hlU`+uoIK+)tPZD>751wC(V-~PyV zzIP-=m&m2q1lDp?!s9%@^Z9MhJaOlLRwJMS@wFTk@tSoXJhyY#b2}bBj~ta)3#d{e z=&>q<`+xS*E3ZBC-)+wLT8^q`A_2EW$)%0`&wu-ee|*LlyON{Q(SXOQ5i#ax&$1lx z%!V9QNXLS1i&iG&Dq`yaRY5>S5K!UldO&q@)Rlnx^G+9d!*AUM{+31PXUzXeRp7nB z^gPh>K+gj`5A;0H^T6kO;4>Ngck2gl{Z~T4p8p#%YU)#eXF$b1|1SmgrBKph`JEc53xgxXpVwpM> zO|+r_Eq&D2bNUMt^J0@Xmd=ACP_cA7OnnQN7i^1D7X^BEG@UDzE7fYV?k@*`&RXa@ z-Sm?exEg09oiCRAtJjuGR65r3c0TW>wwEz|j-|4NleuEKulf}nv*$CVm?Z0=?jj!> zQ=hxYl3IevY@uAmnPj;Hz~wiwPPo0)T{-d0=;3qLSR|FlP4U}mrI<~Ito*Yhdu44m z_5IArJs%u6a{RozT_e9H=DAGNDZMmu^!PDh-9q)Z?`~1`mH#y~G&p!<@305GPaPkU z&%}M2<%wfQM=#8&YG&$fa#`rWk)adA!$Zg49}M8Sav>8B7}=+f9~nAF6R#MWChFmK zyVb%!l;Pdc;gRu)iIIW5(>OlLr@}Vj%+Qg6lS@3IeAx%@>Io<8Yu(?h*PDvH_4& z0-=Pb%3-F~FUQr1pkMUf;K=Cs_~_W!=-BAcv4Nq91rDFj6^i6~Te46>Goq%RXk$#x zMy-^?(V9hg@X*Nc(7}U4<72QpF}=7d;Ip}+)m5E0k4jjPaw3+lu31{`v;GX}z|JZTdXJmrDa_qz7vjUCH6Nsk4H`-DRtdDxU z-Emkr0HTVvQ!N*;Idkv+?+*?gg_DOSMm{=thNH4Lec^bf2nSrE_JU0Hp?Ta47Sp0C z#SY7JIbf?%YuHntoH%oA?}wipIev8iha)tF$>9x=pzN4#YVU*Tm#EH-pKe4PCcQ?f zjyCe?XviPH5FAd2WctM9%nIYu*uKAg`-1}mvm%4t6C{yTZ8qBnsdv$IeyN=8&t01> zmO(iB$X3!vZK;IKYQ4i93`hN{aJ7(2`jkMXBHF3Z3mlPDz-H1fP7RM=u#IafGSUYP5Qj#o{CC6`xwJu?MpyaLIhyB8j^6qUBR(XU?6Sq097U ztx6^q@a0B_%NL476S)eg%`xgL2EEZ_cKYMhe(D3j_G{aeOA*fWrEkmT3)zUrqGr(4 z66P|UFHx$seVY4p8nuk3(HV_mp2aAW>YQ$y$*9LLOrChLS}m2Z;sAVaiiQ21MWEJL z60HxhIeeGOs6tdJlS~9mGA^4XHdr0AEN3W@%jYuviSH$oQI{m0%H~oKN<_nn_9z=In=6^av_&aMqGNO-s;}t{XLIA0e}9W-HhvuTA5n2I?qwr0+B?f zs9!~gAF+baSDWzmmm5KQA5cc4QY_}P>0}}vizQN-LKQ&{`gBcax9MwMSFa(i{LXi+ z+w3;ITBY|@+IcP`o=dC6zGSY9J*KJA<&Aoc&K(T7wZ)=Cr&X~;2CXfSZnhhZdSC6@ zYPAlCMR@vI$bp*8M!ixh?kU__EM(Jhzgce43z;0RQI&s(dc3Ss`EBAAmeFZ9Di;@* z7|e6?mu8h(8b>d-#*>LeG8y-K;AM;65N^%jGy7Zbz#VrYMWNaph?`i;OtDI{V%0HZ0hwBvi>NimOXue4{j{5wSC;8axj(20l6jfl8t9K~3in5D2W8r-#f(!!vLwKk(kNjC#$wCfoQcPWVks#PzE4GsxlVzpkY zy(3KIO?)+pWoF%tHDCZJEVqF@!qF$}&$blPhIXvsoikIu%Hy)|CZk zwvbeoNf>>pjn#ESt5Hu_9V$P0qTAcGyiQljM}1D0+o`0@v-r#vcAw;%G6|0-yd;oH zlq!Xse(F-Z+G^x9eblwpN~PYw^1rU(X0Sr-_A2!vh`&x#tRr44ZlOAmPA8M8WHO!2 zX3{D#-I32BUWKBiI8_Q*SSpbe!KhJd4Q7)@M7to$wc1P^8`R4cJ-BeI9hHUZwZ6v9 zm0T(o^Sg|z3lhcxw~zHb`Yh}G44a|iGd27rbrj3qrDD=#V0NW;n?pTWuLZRkqzJdQ zOyxojwL+ye8Rg7#=VzA0i%h9R!dj4v7iSh%`SEPp&lG6-RM#84nL-gzh(|rwu2yXF zKr-RrD`l$+b087(m=$uGF`%54>rL5QIwDjVWs7qc1+7{oV{+DtrE^`WR;?MwLcn5rc+^uL~SzW&EyzEgGp@mH#XJxG``<#H5v+63v!Qy z@}ky%1J>SPHkb#v7# z<11~UViUhrVSBi~jmb2`0WU%-hgpHOiHYS{cXzME13=t*10msx9wi7My}+q$_Nh#%TA3 z6Oeeca=yab_#C*h7SSmb28SmQaH-WbIZCL0>YFwBGA2cj%ot8$uuZDzg)FBZi>_IL zyE8$D)nYOG>Iyilh5CrPqusKs(D_QO#qA5lGble$U9~k{s!|7a>tDvcC4+7e zOSWS|1!zkgxzj}>dUyMzxkyW#@~-i?`%_f-X)fVj33)CHcG68 zaw#UAU#{8lgzr$_X{u&vLN&lM@-jXPi>#IpE7|;09((ts_j_&1JwMM?>ASbfliSrx zNi&bdq^~wQRcwYa%aZ9#4v#;Q$dY?BDmky1&7$$=^KRO(=cl(jT$>!du z7h>8z_V3X|?6?!PADm&IUEpbO1nUb%aM(d^Qcl_VY!;iY62z_4eVtmV+=$UGu$4ND zB@m8hO9+ZaEf3rPcq&1Nu_W-sJo zs81EtL*&R1g>E>ky)-Y-8Ev?KG?hobY&ObSw}6GG6zW4rpYOq^kG7h%5)P;R9`ou2 zmfB!(dV_f6Qmu}vtPoMMm`oZ+<;dYorrCT4N3t@Mk|?E6*?1gg;YFH)3@8werHa)W zvQjx^;jXUI7*c&OQ>@gG#u|NO_Bzp8gIU0Bv#4nE{I2gJiF_GJtWnGRBn&2<##b18 zNwg{CXRvFxCD`$sNR{!R+iKEq7M7((Jby5PiVIt5yBuYN}*?PM?0XbhZODNNpI7Uw}VIJDgsQ(N2Z zdL@tI(%}qBrv^_+yoFjWo+?)GIE_X%AC@ey(4a|_Kt|;br;2Nqoskm91l=CBL+oWp~|vu*KCQYZK%(yD76F5px|du?B4RkqYvMI*DW{P z^(PFpi%>vBR7>-8mQW$*@nnd`U?NXuq=`p_WgW8)-}n|^-TC~MCmwn5zI*Sz`?jy# z_rJnaqg}Dk=2n<|Ic_OZ8EtNy!gMV~)b=)JztAbx-K+m>#|zt^CboC~@SeNBe$!7y zR4b)km|x{dm2#dyuES#Lnj+eXX^Ski5Dv<1iobg5rDwN2`S>Fb-hc1i_uTjWo1QpF z*}42xF7|&BU!pOS!0Oz!Yuajc9@K3&>&!#X?%cU!%aeH8haR~9zWX2e#(hUMTniI0~Is zgz;LPFpZ~jc-UrJNbNx2kyZvHwwZNu_4zlq?%J_q>r+o{e*E#r9)0BD$G-pAh*+dE z$ORZMiJN#TTOgYka@wf2CM_c=z_*&po?+>y|A~J-He8fAYIOXPHfU zu~>x_-LXZl-8KFJZj6oyH}<%o{ZLEz?0vhp?Rx%s*l&Ag%hONwJ^8J>KX%*YLY%v~ z1JQUYLu|3~+kE6=GHS#>DqE+`V$>>lY}$LTZ{NM^g%@@{|J;u4+qQ1masR*2I8jSj zUH&iz-7zMspHHHuUd*K;LBH3Hz6I7IHhp3LKYw=j%l$8YuQP<_wmmm*MpAY9LeV6# zMIIo=JhcDFVsKbE0BiWnpp}cbjHS8bZ@u!uE3duU_sVx)+P!P{OFPE&DkH38AOs`^ zNLV5AxYQQ-jLcQQkD}aR?b@#{U7Q(v`%hlo{n{IEy#D%Yuf6g5%cqSxo0r@iv0U%( zZZI5#5xkbe8RnhJD-}YZ5X0s=Vn-@t1(vJ!k`x7z8 zK7*UX9Fb@zqgP1yEc)Wi=}Gj+`~Ta&{rOLR^wWR!jsOauPz;L%bJc3~qfFie>!)E| z%EY_Yu8y@*D&VXxUz#~Hi7tC=@c8lJa~!?RPO=i|`C6@a+h0cd<4~Ki2csE?hJ)m} z;WwjREfewC^yT^4bEl`LrcN!$9R7eGxd^DHT8Bt>50W9OHgeN^3T;e~Om=t7Qdq9i zmM&eqaQ^&7XnmpyOcGcNM%!-hB{_nF#+G1-Y$_4MfPH9g;cJZwmR!~IZ;(1f_04!hmqLNlJi@OwVmHL-l<=MW!Y@K)3!i(^Xb2nSN-`Pj`JF>xzTB^ z&7W&`ab7DSIdzVui`L4K(>T~T<7)X0^}2A+3E+qZi1JX`IIAbpmRKWpVuAzMjY;d$Db zIkwyu24|=cAXg==anQmU^mwV8@{$Wc4kel2b4__49s zOB-n3@!`SYk>P>&hk~Ga73@Ov5}L7bndadogm=e=ft)5s2lkx=%`2p% z4)KNIqbE)+^F@jkAJEoDny1`50X%o|bjNbV~0mBu!JI!SjMoBUHA&k%coPK_s7Pj!2Tx2M~9Ek z3(gE2I&qf97Ygv6Ces*5$ku4KNRwG3dkY1t2FEatO@(@X*oYK*W=y z`wyMt5dauT<+?=fYM6(VO46FcX4I-Roas+aoIVPecWmI;#~+Q*l@_E@&>(C?;DCPz z%xe}hu}~ls!G`Fv6PR}aFmH6<-y%d#%t}lSUzp%Pl2?8+m={4Xr2;=6INtZafaCQgzS`q>J&xDoc>f@d=OY{s`gCC0FXnjX zCl+{ML(b$EalDk2L*pn-zGOD-`wcjrkPakeN6lOQ4LP2S#*w4(^hZ;L-+<#OR@f4i z!A_2x3cn%8v(gv>6+wTf?a6ry;ds6;;CS?9u0n@oh~z_97U6i7v$4i1e#XW1G8LP(2UBA;F@MwDz^ z&Q-f$4=?q%zKjG0D{?NHO@=)Vt7wj{1pmX}6KMk18ue1z%44$Vt8zoA1ArQDcTwIJ zLI81Uj~8Cl^aTN80W7xTURc#~e(5TUK^Le{f1;WJ10-{cDvWg4CEN={PQzJTk)hxT zhGSS-Z~%_OVtVE(V53Z>wMRhd2pl7J5)fsOJo2)H&FnOa1Uiq~7fB@3z%+gJ?=;G3 z50}2mU`iAqdHy(oH^i_@@>(Ey1durbvZ=w-l0d1MPoyy>f*fjvh>S*OFoa5(NN)0w zlTR`e%Dl9wU!Uia$Hw(s2bRLAz7d++(i*M472wbGiU1tuS7 zdIF&WXP{&cAgkgs$s@<_gyj9jlP~Vry7{q(AAI1xd+xdahc|=dIr#!6PpZ~R1X7K~ z1u#aC+L~#rMc`D(>*$cY=bzvH^ybGNf${zK-v8ij_Z`;>xIB>>twRTkk$5Afn3OKb zLx%*NfE^@H^p{V*`0Tc)p9G0}80HT=0+J`;aFu$UM6A%;P>siunNBg?C3zsF=wp1~ zX?lfb=BLlRuzmY8Pd@p?V*q&|d3QZFDv=mWO0ir^3V9qHLEA!DX_w?dHqq%e99BpN zq(^pb+x6^@ZO=UY^kxF`9^L%ipR=tNqol*ch%LcdSV=JMl039S1gBXI8j!sAcWr&) zx#wWN6(H})zRlmd`;gbEl;Ge6TQh6{X~{CYLh=&eLTGfXU~zml?cLY5?RsG+Kps%w z)@PpHe%~Ky+!BQj3_jX1UZc^MNgg@s>rh0kLd>PlfAj}CcD>ZU`+J=sJiGPT1uH?r zfk-?JNOFbb?d+1gc!Yo@!XRPIqc6@K|MQohfBDr{UVizd-Me4d_2Q0kgT@T&1b7aK zbP`q@NM14;?7%de1uRX>TV0qvKmN|Yd1cqDKl;(@uf6)}8?V1|#%yo^YjyDD6_R&1 zA$j0hz*=1l*+Fs4<+-z`rv~2s)tj%p`lG%d-}0mFzm{38J`A03?W;&0)FB-zMmQwy zu9OJaw1t_|(-UKZ2mbq?{=rY*`2An(5dy{msgV;1cJM2^?7xCDPmBqPPXe%yq%s`eMRNHAiK1K3~RDnQ1pfgZYeMf?U3`bjD zTBPxGJ_0MrV%|XVI?@D~tTAGpMk$wwg+jhStT6dHO(+5#B=5lv$-@aNlnimuIgmfQ z)nY>Lrq$_9R#z~AwGQ`zKSi@gpd&KYdf?b4eaiYgBN4{(qR{Nzm0p1<-5~aUL{s zS*y~LtaZhC4fn$MX}%+vzfAL_XU=ns(dq`8m)6XjWGJovc(zW(E{pT>rn!^LGW?W0 z`UaX;w9`&Qv`j`$A<@oFM{U14VFg)KvB1BapJ`Ap!l*hkM_IRtCqRjgc zcPCGsnjAiGCP!di*eGngW8e+VIs^+ zia(s5I(@qD6fPehToj%kIW{uG5Q;@&sY0mDRX3tM=4qp;#Z8)%jFz+gs7w_aY8>pd}FIe2y|MAhmArQ?|Q$y3U4EECWfp-xkBlFTuuZ4PxY>#U^uabQ`cTEw;4jZ(2 z77Zj9M4P9EHZPwEsaIJt3FGwm98ao{@HouH)8o_gLX_A+a^`&n=Uv}&D-3#_Uf-vC z&R|9&tU{aTS1Ys*qRqpmnYKw{ZiAF|=KRH(^Ruf8gVm@}$|Mqn+3A5K0EPFOHqU4< znJlhAVojTO4dfAuaDS#F&5L5SFzIR;Yh_g+RcUp7+WVlwQ_!_~qgf)bTNHAG+vh?` zFzWSYZye|EI8Ff!2F=3>q#qgqy;^6DuS@eZVG4}{HXJ#h%N84Ljyd*aY2IC+d2VSs zO{94lX01KPYR%DfCje0micLn!lnfi-1bLT}V5G+NdISM4APwqRg( zlzAr8MrGa&Q0BooxlB6Qm-tF5jRk`F*?{t{UsL8;_t>`C?Kl=Q_#w^XGl?`$0%=}_ zNb|J1yve9Dcp%Nwm5NTJT#nd;=DjP;>##h?U5GC4y3S!!rL?E`^#X32PWa6Vt3kx( z`HbqWE>9h_NoZ`73$KDNEw8ZHGm8szDjkDskk}x~gD?-eJOERR!5C?MR+nd4;iC_^ zxGWSYO=c)7mc&}<^30qSmPD({Ea#(daCNKcv>=)^&M4 z;R@HC4a@8SHJ7JXGCI1vlv3&J=<*awnKz$Pg>*@WbP>8de_!;S$n^n(B2u*(n+$YI zR8Z>G3zhn$k!bR)Ool{fGn&;5OGlHJwenVoCQqkXkrlXvuZ zk3&x$L*rs%E=ie7d=LS~9Q(p7m#G%8w1O24b`YOS&8ExE(BqNA=;!OTkdEl_JT~a@ z!VXA*b!L--H8XQzMY_zANu}&1xnyZ}i6tO9R<6XjQ$r_DXrP14c zx`lPaE4P$dd!J=`5r>zY63<^-2}U6cOZU zE(`M1t6Z6e_V$F0azB{W)Qan zsGt_IoW*O_dp<{!R}d_6<&dy-lxBoabx__CeFMr<&#g)zMk9hcXaezh5ap>jqI2sg z@75OOU0fDwjYNcls<#SR$5%>83!lwlvb&h<$ebket7?oIEH;y+Fm^?G z>l}|@E|fulF;?yBk_fYn6#{gL(=8&&^UGKq)+#m%d{+Y!`x?hvm*nAb{0@tbw?tQv z$L|agcdOS6aUGM%V(=7dt$m%1Z2)=Xq}O3_nZ-f_KwcQ9X=p_V$g8B>Jo+k~B~!^s z6WZxn@q|}EUJ4>WcSv!1^qkB`Bzc!X9v~}&!Nf@A5T|xOs-rl<%v{g&zh9)GRPz1D^FPb^DVDJruO)w_kHV@`~E#^O_HakEi$=c zl~TZ$>8zJ6*Clym)}4XnH(q*i$1|G&0Uv(wJ70UaKSCsV=G6r{MM4?Xzp+kP$u$Wt#bv4si(@`xl4LSX`PH-J2#Ew{y? z{?FT9-}U^~r#CL&wk_Y~b`x1&_RLkTiUfcQVu3bBygQ#ySk=1Rz z`;WL5vw?s-z_@4vxP|D`)<7QQ8EMQ9VR0s%OvvB=>dseQdU5xzozFiDQC;8GZ#{6> z?NErI)9_%|0LVijOghM}BoFv886$|sX~(g;h{yWyCp$YJ?Zw?4S>6ke{6gzOIe|ll z4vZu1dDogq@`$8@NVV|Pu$J;!D~J9iFk1g>-+Sdn3}N@q7Z)vQh+q0NCf&FvuX zPRWEEkihBp|HF@8{mGke{(j$2Zu!|y-#Clv7xD#YC-BghC3ytoRq*y7?%u^(CcO$@ zC9%3Vd;Zk$`+xC=Z~XYpzJGShn=kwixy1st28waA*M3Tp*VVTXp4Pd$T8^f21){o> zQ=^~!zkl|}|IeF0|C4=U@`WZH1=7_Z58M`%i&%G<+B%E_2s}AGJuy5ueo3`MDr34*6a<6bgqUAn)Y-=4z04MUwaVAn&)7K+gj`5A;0H^FYr7JrDFe z(DOjg13eG)Jkaw%&jURV^gPh>K+gj`5A;0H^FYr7JrDFe(DOjg13eG)Jkaw%&jURV z^gPh>K+gj`5A;0H^FYr7JrDFe(DOjg13eG)Jn;W>5BzSwKG++5&jURV{0@8I{{uRH BjV1s9 From c7d9b316efca88d3b3db05cd08ba75821d777731 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Fri, 21 Jun 2013 22:32:22 +0100 Subject: [PATCH 28/93] Seperated out class_singleWorker (POW thread) --- src/bitmessagemain.py | 849 +------------------------------------ src/class_singleWorker.py | 858 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 859 insertions(+), 848 deletions(-) create mode 100644 src/class_singleWorker.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 4383b0ac..d22db71d 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -52,6 +52,7 @@ import proofofwork from class_singleListener import * from class_sqlThread import * from class_singleCleaner import * +from class_singleWorker import * from class_addressGenerator import * # Helper Functions @@ -2473,854 +2474,6 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] return datatosend + payload -# This thread, of which there is only one, does the heavy lifting: -# calculating POWs. - - -class singleWorker(threading.Thread): - - def __init__(self): - # QThread.__init__(self, parent) - threading.Thread.__init__(self) - - def run(self): - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT toripe FROM sent WHERE ((status='awaitingpubkey' OR status='doingpubkeypow') AND folder='sent')''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - toripe, = row - neededPubkeys[toripe] = 0 - - # Initialize the ackdataForWhichImWatching data structure using data - # from the sql database. - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT ackdata FROM sent where (status='msgsent' OR status='doingmsgpow')''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - ackdata, = row - print 'Watching for ackdata', ackdata.encode('hex') - ackdataForWhichImWatching[ackdata] = 0 - - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT DISTINCT toaddress FROM sent WHERE (status='doingpubkeypow' AND folder='sent')''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - toaddress, = row - self.requestPubKey(toaddress) - - 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.sendBroadcast() - # just in case there are any tasks for Broadcasts - # that have yet to be sent. - - while True: - command, data = shared.workerQueue.get() - if command == 'sendmessage': - self.sendMsg() - elif command == 'sendbroadcast': - self.sendBroadcast() - elif command == 'doPOWForMyV2Pubkey': - self.doPOWForMyV2Pubkey(data) - elif command == 'doPOWForMyV3Pubkey': - self.doPOWForMyV3Pubkey(data) - """elif command == 'newpubkey': - toAddressVersion,toStreamNumber,toRipe = data - if toRipe in neededPubkeys: - print 'We have been awaiting the arrival of this pubkey.' - del neededPubkeys[toRipe] - t = (toRipe,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - self.sendMsg() - else: - shared.printLock.acquire() - print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') - shared.printLock.release()""" - else: - shared.printLock.acquire() - sys.stderr.write( - 'Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command) - shared.printLock.release() - shared.workerQueue.task_done() - - def doPOWForMyV2Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW - # Look up my stream number based on my address hash - """configSections = shared.config.sections() - for addressInKeysFile in configSections: - if addressInKeysFile <> 'bitmessagesettings': - status,addressVersionNumber,streamNumber,hashFromThisParticularAddress = decodeAddress(addressInKeysFile) - if hash == hashFromThisParticularAddress: - myAddress = addressInKeysFile - break""" - myAddress = shared.myAddressesByHash[hash] - status, addressVersionNumber, streamNumber, hash = decodeAddress( - myAddress) - embeddedTime = int(time.time() + random.randrange( - -300, 300)) # the current time plus or minus five minutes - payload = pack('>I', (embeddedTime)) - payload += encodeVarint(addressVersionNumber) # Address version number - payload += encodeVarint(streamNumber) - payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). - - try: - privSigningKeyBase58 = shared.config.get( - myAddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - myAddress, 'privencryptionkey') - except Exception as err: - 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) - shared.printLock.release() - return - - privSigningKeyHex = shared.decodeWalletImportFormat( - privSigningKeyBase58).encode('hex') - privEncryptionKeyHex = shared.decodeWalletImportFormat( - privEncryptionKeyBase58).encode('hex') - pubSigningKey = highlevelcrypto.privToPub( - privSigningKeyHex).decode('hex') - pubEncryptionKey = highlevelcrypto.privToPub( - privEncryptionKeyHex).decode('hex') - - payload += pubSigningKey[1:] - payload += pubEncryptionKey[1:] - - # Do the POW for this pubkey message - target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + - 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - print '(For pubkey message) Doing proof of work...' - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce - payload = pack('>Q', nonce) + payload - """t = (hash,payload,embeddedTime,'no') - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release()""" - - inventoryHash = calculateInventoryHash(payload) - objectType = 'pubkey' - shared.inventory[inventoryHash] = ( - objectType, streamNumber, payload, embeddedTime) - - shared.printLock.acquire() - print 'broadcasting inv with hash:', inventoryHash.encode('hex') - shared.printLock.release() - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateStatusBar', '')) - shared.config.set( - myAddress, 'lastpubkeysendtime', str(int(time.time()))) - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - def doPOWForMyV3Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW - myAddress = shared.myAddressesByHash[hash] - status, addressVersionNumber, streamNumber, hash = decodeAddress( - myAddress) - embeddedTime = int(time.time() + random.randrange( - -300, 300)) # the current time plus or minus five minutes - payload = pack('>I', (embeddedTime)) - payload += encodeVarint(addressVersionNumber) # Address version number - payload += encodeVarint(streamNumber) - payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). - - try: - privSigningKeyBase58 = shared.config.get( - myAddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - myAddress, 'privencryptionkey') - except Exception as err: - 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) - shared.printLock.release() - return - - privSigningKeyHex = shared.decodeWalletImportFormat( - privSigningKeyBase58).encode('hex') - privEncryptionKeyHex = shared.decodeWalletImportFormat( - privEncryptionKeyBase58).encode('hex') - pubSigningKey = highlevelcrypto.privToPub( - privSigningKeyHex).decode('hex') - pubEncryptionKey = highlevelcrypto.privToPub( - privEncryptionKeyHex).decode('hex') - - payload += pubSigningKey[1:] - payload += pubEncryptionKey[1:] - - payload += encodeVarint(shared.config.getint( - myAddress, 'noncetrialsperbyte')) - payload += encodeVarint(shared.config.getint( - myAddress, 'payloadlengthextrabytes')) - signature = highlevelcrypto.sign(payload, privSigningKeyHex) - payload += encodeVarint(len(signature)) - payload += signature - - # Do the POW for this pubkey message - target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + - 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - print '(For pubkey message) Doing proof of work...' - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce - - payload = pack('>Q', nonce) + payload - """t = (hash,payload,embeddedTime,'no') - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release()""" - - inventoryHash = calculateInventoryHash(payload) - objectType = 'pubkey' - shared.inventory[inventoryHash] = ( - objectType, streamNumber, payload, embeddedTime) - - shared.printLock.acquire() - print 'broadcasting inv with hash:', inventoryHash.encode('hex') - shared.printLock.release() - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateStatusBar', '')) - shared.config.set( - myAddress, 'lastpubkeysendtime', str(int(time.time()))) - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) - - def sendBroadcast(self): - shared.sqlLock.acquire() - t = ('broadcastqueued',) - shared.sqlSubmitQueue.put( - '''SELECT fromaddress, subject, message, ackdata FROM sent WHERE status=? and folder='sent' ''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - fromaddress, subject, body, ackdata = row - status, addressVersionNumber, streamNumber, ripe = decodeAddress( - fromaddress) - if addressVersionNumber == 2 and int(time.time()) < encryptedBroadcastSwitchoverTime: - # We need to convert our private keys to public keys in order - # to include them. - try: - privSigningKeyBase58 = shared.config.get( - fromaddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - fromaddress, 'privencryptionkey') - except: - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) - continue - - privSigningKeyHex = shared.decodeWalletImportFormat( - 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. - 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 += encodeVarint(1) # broadcast version - payload += encodeVarint(addressVersionNumber) - payload += encodeVarint(streamNumber) - payload += '\x00\x00\x00\x01' # behavior bitfield - payload += pubSigningKey[1:] - payload += pubEncryptionKey[1:] - payload += ripe - payload += '\x02' # message encoding type - payload += encodeVarint(len( - 'Subject:' + subject + '\n' + 'Body:' + body)) # Type 2 is simple UTF-8 message encoding. - payload += 'Subject:' + subject + '\n' + 'Body:' + body - - signature = highlevelcrypto.sign(payload, privSigningKeyHex) - payload += encodeVarint(len(signature)) - payload += signature - - target = 2 ** 64 / ((len( - payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - print '(For broadcast message) Doing proof of work...' - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Doing work necessary to send broadcast...")))) - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce - - payload = pack('>Q', nonce) + payload - - inventoryHash = calculateInventoryHash(payload) - objectType = 'broadcast' - shared.inventory[inventoryHash] = ( - objectType, streamNumber, payload, int(time.time())) - print 'Broadcasting inv for my broadcast (within sendBroadcast function):', inventoryHash.encode('hex') - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Broadcast sent on %1").arg(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 - shared.sqlLock.acquire() - t = ('broadcastsent', int( - 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) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - elif addressVersionNumber == 3 or int(time.time()) > encryptedBroadcastSwitchoverTime: - # We need to convert our private keys to public keys in order - # to include them. - try: - privSigningKeyBase58 = shared.config.get( - fromaddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - fromaddress, 'privencryptionkey') - except: - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) - continue - - privSigningKeyHex = shared.decodeWalletImportFormat( - 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. - 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 += encodeVarint(2) # broadcast version - payload += encodeVarint(streamNumber) - - dataToEncrypt = encodeVarint(2) # broadcast version - dataToEncrypt += encodeVarint(addressVersionNumber) - dataToEncrypt += encodeVarint(streamNumber) - dataToEncrypt += '\x00\x00\x00\x01' # behavior bitfield - dataToEncrypt += pubSigningKey[1:] - dataToEncrypt += pubEncryptionKey[1:] - if addressVersionNumber >= 3: - dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'noncetrialsperbyte')) - dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'payloadlengthextrabytes')) - dataToEncrypt += '\x02' # message encoding type - dataToEncrypt += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding per the documentation on the wiki. - dataToEncrypt += 'Subject:' + subject + '\n' + 'Body:' + body - signature = highlevelcrypto.sign( - dataToEncrypt, privSigningKeyHex) - dataToEncrypt += encodeVarint(len(signature)) - dataToEncrypt += signature - - # Encrypt the broadcast with the information contained in the broadcaster's address. Anyone who knows the address can generate - # the private encryption key to decrypt the broadcast. This provides virtually no privacy; its purpose is to keep questionable - # and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties. - privEncryptionKey = hashlib.sha512(encodeVarint( - addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32] - pubEncryptionKey = pointMult(privEncryptionKey) - payload += highlevelcrypto.encrypt( - dataToEncrypt, pubEncryptionKey.encode('hex')) - - target = 2 ** 64 / ((len( - payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - print '(For broadcast message) Doing proof of work...' - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Doing work necessary to send broadcast...")))) - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce - - payload = pack('>Q', nonce) + payload - - inventoryHash = calculateInventoryHash(payload) - objectType = 'broadcast' - shared.inventory[inventoryHash] = ( - objectType, streamNumber, payload, int(time.time())) - print 'sending inv (within sendBroadcast function)' - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Broadcast sent on %1").arg(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 - shared.sqlLock.acquire() - t = ('broadcastsent', int( - 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) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - else: - shared.printLock.acquire() - sys.stderr.write( - 'Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n') - shared.printLock.release() - - def sendMsg(self): - # Check to see if there are any messages queued to be sent - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT DISTINCT toaddress FROM sent WHERE (status='msgqueued' AND folder='sent')''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: # For each address to which we need to send a message, check to see if we have its pubkey already. - toaddress, = row - toripe = decodeAddress(toaddress)[3] - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT hash FROM pubkeys WHERE hash=? ''') - shared.sqlSubmitQueue.put((toripe,)) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn != []: # If we have the needed pubkey, set the status to doingmsgpow (we'll do it further down) - t = (toaddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - else: # We don't have the needed pubkey. Set the status to 'awaitingpubkey' and request it if we haven't already - if toripe in neededPubkeys: - # We already sent a request for the pubkey - t = (toaddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='msgqueued' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, translateText("MainWindow",'Encryption key was requested earlier.')))) - else: - # We have not yet sent a request for the pubkey - t = (toaddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='doingpubkeypow' WHERE toaddress=? AND status='msgqueued' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) - self.requestPubKey(toaddress) - 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. - 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,)) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: # For each message we need to send.. - 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. - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT hash FROM pubkeys WHERE hash=? ''') - shared.sqlSubmitQueue.put((toripe,)) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn == [] and toripe not in neededPubkeys: - # We no longer have the needed pubkey and we haven't requested - # it. - 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')) - shared.printLock.release() - t = (toaddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='msgqueued' WHERE toaddress=? AND status='doingmsgpow' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) - self.requestPubKey(toaddress) - continue - ackdataForWhichImWatching[ackdata] = 0 - toStatus, toAddressVersionNumber, toStreamNumber, toHash = decodeAddress( - toaddress) - fromStatus, fromAddressVersionNumber, fromStreamNumber, fromHash = decodeAddress( - fromaddress) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Looking up the receiver\'s public key")))) - shared.printLock.acquire() - print 'Found a message in our database that needs to be sent with this pubkey.' - print 'First 150 characters of message:', repr(message[:150]) - shared.printLock.release() - - # mark the pubkey as 'usedpersonally' so that we don't ever delete - # it. - shared.sqlLock.acquire() - t = (toripe,) - shared.sqlSubmitQueue.put( - '''UPDATE pubkeys SET usedpersonally='yes' WHERE hash=?''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - 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. - shared.sqlSubmitQueue.put( - 'SELECT transmitdata FROM pubkeys WHERE hash=?') - shared.sqlSubmitQueue.put((toripe,)) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn == []: - shared.printLock.acquire() - sys.stderr.write( - '(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n') - shared.printLock.release() - return - for row in queryreturn: - 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. - readPosition = 8 # to bypass the nonce - pubkeyEmbeddedTime, = unpack( - '>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: - pubkeyEmbeddedTime, = unpack( - '>Q', pubkeyPayload[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - readPosition += 1 # to bypass the address version whose length is definitely 1 - streamNumber, streamNumberLength = decodeVarint( - pubkeyPayload[readPosition:readPosition + 10]) - readPosition += streamNumberLength - behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4] - readPosition += 4 # to bypass the bitfield of behaviors - # pubSigningKeyBase256 = - # pubkeyPayload[readPosition:readPosition+64] #We don't use this - # key for anything here. - readPosition += 64 - pubEncryptionKeyBase256 = pubkeyPayload[ - readPosition:readPosition + 64] - readPosition += 64 - if toAddressVersionNumber == 2: - requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte - requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) - elif toAddressVersionNumber == 3: - requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( - pubkeyPayload[readPosition:readPosition + 10]) - readPosition += varintLength - requiredPayloadLengthExtraBytes, varintLength = decodeVarint( - pubkeyPayload[readPosition:readPosition + 10]) - 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. - requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte - if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: - requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( - requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes))))) - 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): - # The demanded difficulty is more than we are willing - # to do. - shared.sqlLock.acquire() - t = (ackdata,) - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( - requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes)).arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) - continue - - 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. - if fromAddressVersionNumber == 2: - payload = '\x01' # Message version. - payload += encodeVarint(fromAddressVersionNumber) - 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 ) - - # We need to convert our private keys to public keys in order - # to include them. - try: - privSigningKeyBase58 = shared.config.get( - fromaddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - fromaddress, 'privencryptionkey') - except: - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) - continue - - privSigningKeyHex = shared.decodeWalletImportFormat( - privSigningKeyBase58).encode('hex') - privEncryptionKeyHex = shared.decodeWalletImportFormat( - privEncryptionKeyBase58).encode('hex') - - pubSigningKey = highlevelcrypto.privToPub( - 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 += 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 += '\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 - payload += encodeVarint(len(messageToTransmit)) - payload += messageToTransmit - fullAckPayload = self.generateFullAckMessage( - ackdata, toStreamNumber, embeddedTime) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out. - payload += encodeVarint(len(fullAckPayload)) - payload += fullAckPayload - signature = highlevelcrypto.sign(payload, privSigningKeyHex) - payload += encodeVarint(len(signature)) - payload += signature - - if fromAddressVersionNumber == 3: - payload = '\x01' # Message version. - payload += encodeVarint(fromAddressVersionNumber) - 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 ) - - # We need to convert our private keys to public keys in order - # to include them. - try: - privSigningKeyBase58 = shared.config.get( - fromaddress, 'privsigningkey') - privEncryptionKeyBase58 = shared.config.get( - fromaddress, 'privencryptionkey') - except: - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) - continue - - privSigningKeyHex = shared.decodeWalletImportFormat( - privSigningKeyBase58).encode('hex') - privEncryptionKeyHex = shared.decodeWalletImportFormat( - privEncryptionKeyBase58).encode('hex') - - pubSigningKey = highlevelcrypto.privToPub( - 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 += 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 shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(toaddress): - payload += encodeVarint( - shared.networkDefaultProofOfWorkNonceTrialsPerByte) - payload += encodeVarint( - shared.networkDefaultPayloadLengthExtraBytes) - else: - payload += encodeVarint(shared.config.getint( - 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 += '\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 - payload += encodeVarint(len(messageToTransmit)) - payload += messageToTransmit - fullAckPayload = self.generateFullAckMessage( - ackdata, toStreamNumber, embeddedTime) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out. - payload += encodeVarint(len(fullAckPayload)) - payload += fullAckPayload - signature = highlevelcrypto.sign(payload, privSigningKeyHex) - payload += encodeVarint(len(signature)) - payload += signature - - - # We have assembled the data that will be encrypted. - try: - encrypted = highlevelcrypto.encrypt(payload,"04"+pubEncryptionKeyBase256.encode('hex')) - except: - shared.sqlLock.acquire() - t = (ackdata,) - shared.sqlSubmitQueue.put('''UPDATE sent SET status='badkey' WHERE ackdata=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,translateText("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) - continue - encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted - target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) - 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 - shared.printLock.release() - powStartTime = time.time() - initialHash = hashlib.sha512(encryptedPayload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print '(For msg message) Found proof of work', trialValue, 'Nonce:', nonce - try: - print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' - except: - pass - shared.printLock.release() - encryptedPayload = pack('>Q', nonce) + encryptedPayload - - inventoryHash = calculateInventoryHash(encryptedPayload) - objectType = 'msg' - shared.inventory[inventoryHash] = ( - objectType, toStreamNumber, encryptedPayload, int(time.time())) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, translateText("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(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') - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - - # Update the status of the message in the 'sent' table to have a - # 'msgsent' status - shared.sqlLock.acquire() - t = (ackdata,) - shared.sqlSubmitQueue.put('''UPDATE sent SET status='msgsent' WHERE ackdata=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - - def requestPubKey(self, toAddress): - toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress( - toAddress) - if toStatus != 'success': - shared.printLock.acquire() - sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr( - toAddress) + '. Please report this error to Atheros.') - shared.printLock.release() - return - neededPubkeys[ripe] = 0 - payload = pack('>Q', (int(time.time()) + random.randrange( - -300, 300))) # the current time plus or minus five minutes. - payload += encodeVarint(addressVersionNumber) - payload += encodeVarint(streamNumber) - payload += ripe - shared.printLock.acquire() - print 'making request for pubkey with ripe:', ripe.encode('hex') - shared.printLock.release() - # print 'trial value', trialValue - statusbar = 'Doing the computations necessary to request the recipient\'s public key.' - shared.UISignalQueue.put(('updateStatusBar', statusbar)) - shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - ripe, translateText("MainWindow",'Doing work necessary to request encryption key.')))) - target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + - 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print 'Found proof of work', trialValue, 'Nonce:', nonce - shared.printLock.release() - - payload = pack('>Q', nonce) + payload - inventoryHash = calculateInventoryHash(payload) - objectType = 'getpubkey' - shared.inventory[inventoryHash] = ( - objectType, streamNumber, payload, int(time.time())) - print 'sending inv (for the getpubkey message)' - shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) - - t = (toAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='doingpubkeypow' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - - shared.UISignalQueue.put(( - 'updateStatusBar', translateText("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) - shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( - strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) - - def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime): - payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata - target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + - 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - shared.printLock.acquire() - print '(For ack message) Doing proof of work...' - shared.printLock.release() - powStartTime = time.time() - initialHash = hashlib.sha512(payload).digest() - trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print '(For ack message) Found proof of work', trialValue, 'Nonce:', nonce - try: - print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' - except: - pass - shared.printLock.release() - payload = pack('>Q', nonce) + payload - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' - headerData += pack('>L', len(payload)) - headerData += hashlib.sha512(payload).digest()[:4] - return headerData + payload diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py new file mode 100644 index 00000000..9e1582f9 --- /dev/null +++ b/src/class_singleWorker.py @@ -0,0 +1,858 @@ +import threading +import shared +import time +from time import strftime, localtime, gmtime +import random +from addresses import * +import bitmessagemain +import highlevelcrypto +import proofofwork + +# This thread, of which there is only one, does the heavy lifting: +# calculating POWs. + + +class singleWorker(threading.Thread): + + def __init__(self): + # QThread.__init__(self, parent) + threading.Thread.__init__(self) + + def run(self): + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT toripe FROM sent WHERE ((status='awaitingpubkey' OR status='doingpubkeypow') AND folder='sent')''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + toripe, = row + neededPubkeys[toripe] = 0 + + # Initialize the bitmessagemain.ackdataForWhichImWatching data structure using data + # from the sql database. + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT ackdata FROM sent where (status='msgsent' OR status='doingmsgpow')''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + ackdata, = row + print 'Watching for ackdata', ackdata.encode('hex') + bitmessagemain.ackdataForWhichImWatching[ackdata] = 0 + + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT DISTINCT toaddress FROM sent WHERE (status='doingpubkeypow' AND folder='sent')''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + toaddress, = row + self.requestPubKey(toaddress) + + 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.sendBroadcast() + # just in case there are any tasks for Broadcasts + # that have yet to be sent. + + while True: + command, data = shared.workerQueue.get() + if command == 'sendmessage': + self.sendMsg() + elif command == 'sendbroadcast': + self.sendBroadcast() + elif command == 'doPOWForMyV2Pubkey': + self.doPOWForMyV2Pubkey(data) + elif command == 'doPOWForMyV3Pubkey': + self.doPOWForMyV3Pubkey(data) + """elif command == 'newpubkey': + toAddressVersion,toStreamNumber,toRipe = data + if toRipe in neededPubkeys: + print 'We have been awaiting the arrival of this pubkey.' + del neededPubkeys[toRipe] + t = (toRipe,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + self.sendMsg() + else: + shared.printLock.acquire() + print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') + shared.printLock.release()""" + else: + shared.printLock.acquire() + sys.stderr.write( + 'Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command) + shared.printLock.release() + shared.workerQueue.task_done() + + def doPOWForMyV2Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW + # Look up my stream number based on my address hash + """configSections = shared.config.sections() + for addressInKeysFile in configSections: + if addressInKeysFile <> 'bitmessagesettings': + status,addressVersionNumber,streamNumber,hashFromThisParticularAddress = decodeAddress(addressInKeysFile) + if hash == hashFromThisParticularAddress: + myAddress = addressInKeysFile + break""" + myAddress = shared.myAddressesByHash[hash] + status, addressVersionNumber, streamNumber, hash = decodeAddress( + myAddress) + embeddedTime = int(time.time() + random.randrange( + -300, 300)) # the current time plus or minus five minutes + payload = pack('>I', (embeddedTime)) + payload += encodeVarint(addressVersionNumber) # Address version number + payload += encodeVarint(streamNumber) + payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). + + try: + privSigningKeyBase58 = shared.config.get( + myAddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + myAddress, 'privencryptionkey') + except Exception as err: + 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) + shared.printLock.release() + return + + privSigningKeyHex = shared.decodeWalletImportFormat( + privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = shared.decodeWalletImportFormat( + privEncryptionKeyBase58).encode('hex') + pubSigningKey = highlevelcrypto.privToPub( + privSigningKeyHex).decode('hex') + pubEncryptionKey = highlevelcrypto.privToPub( + privEncryptionKeyHex).decode('hex') + + payload += pubSigningKey[1:] + payload += pubEncryptionKey[1:] + + # Do the POW for this pubkey message + target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + print '(For pubkey message) Doing proof of work...' + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce + payload = pack('>Q', nonce) + payload + """t = (hash,payload,embeddedTime,'no') + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release()""" + + inventoryHash = calculateInventoryHash(payload) + objectType = 'pubkey' + shared.inventory[inventoryHash] = ( + objectType, streamNumber, payload, embeddedTime) + + shared.printLock.acquire() + print 'broadcasting inv with hash:', inventoryHash.encode('hex') + shared.printLock.release() + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + shared.UISignalQueue.put(('updateStatusBar', '')) + shared.config.set( + myAddress, 'lastpubkeysendtime', str(int(time.time()))) + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + + def doPOWForMyV3Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW + myAddress = shared.myAddressesByHash[hash] + status, addressVersionNumber, streamNumber, hash = decodeAddress( + myAddress) + embeddedTime = int(time.time() + random.randrange( + -300, 300)) # the current time plus or minus five minutes + payload = pack('>I', (embeddedTime)) + payload += encodeVarint(addressVersionNumber) # Address version number + payload += encodeVarint(streamNumber) + payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). + + try: + privSigningKeyBase58 = shared.config.get( + myAddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + myAddress, 'privencryptionkey') + except Exception as err: + 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) + shared.printLock.release() + return + + privSigningKeyHex = shared.decodeWalletImportFormat( + privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = shared.decodeWalletImportFormat( + privEncryptionKeyBase58).encode('hex') + pubSigningKey = highlevelcrypto.privToPub( + privSigningKeyHex).decode('hex') + pubEncryptionKey = highlevelcrypto.privToPub( + privEncryptionKeyHex).decode('hex') + + payload += pubSigningKey[1:] + payload += pubEncryptionKey[1:] + + payload += encodeVarint(shared.config.getint( + myAddress, 'noncetrialsperbyte')) + payload += encodeVarint(shared.config.getint( + myAddress, 'payloadlengthextrabytes')) + signature = highlevelcrypto.sign(payload, privSigningKeyHex) + payload += encodeVarint(len(signature)) + payload += signature + + # Do the POW for this pubkey message + target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + print '(For pubkey message) Doing proof of work...' + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce + + payload = pack('>Q', nonce) + payload + """t = (hash,payload,embeddedTime,'no') + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release()""" + + inventoryHash = calculateInventoryHash(payload) + objectType = 'pubkey' + shared.inventory[inventoryHash] = ( + objectType, streamNumber, payload, embeddedTime) + + shared.printLock.acquire() + print 'broadcasting inv with hash:', inventoryHash.encode('hex') + shared.printLock.release() + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + shared.UISignalQueue.put(('updateStatusBar', '')) + shared.config.set( + myAddress, 'lastpubkeysendtime', str(int(time.time()))) + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + + def sendBroadcast(self): + shared.sqlLock.acquire() + t = ('broadcastqueued',) + shared.sqlSubmitQueue.put( + '''SELECT fromaddress, subject, message, ackdata FROM sent WHERE status=? and folder='sent' ''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + fromaddress, subject, body, ackdata = row + status, addressVersionNumber, streamNumber, ripe = decodeAddress( + fromaddress) + if addressVersionNumber == 2 and int(time.time()) < encryptedBroadcastSwitchoverTime: + # We need to convert our private keys to public keys in order + # to include them. + try: + privSigningKeyBase58 = shared.config.get( + fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + fromaddress, 'privencryptionkey') + except: + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + continue + + privSigningKeyHex = shared.decodeWalletImportFormat( + 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. + 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 += encodeVarint(1) # broadcast version + payload += encodeVarint(addressVersionNumber) + payload += encodeVarint(streamNumber) + payload += '\x00\x00\x00\x01' # behavior bitfield + payload += pubSigningKey[1:] + payload += pubEncryptionKey[1:] + payload += ripe + payload += '\x02' # message encoding type + payload += encodeVarint(len( + 'Subject:' + subject + '\n' + 'Body:' + body)) # Type 2 is simple UTF-8 message encoding. + payload += 'Subject:' + subject + '\n' + 'Body:' + body + + signature = highlevelcrypto.sign(payload, privSigningKeyHex) + payload += encodeVarint(len(signature)) + payload += signature + + target = 2 ** 64 / ((len( + payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + print '(For broadcast message) Doing proof of work...' + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send broadcast...")))) + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce + + payload = pack('>Q', nonce) + payload + + inventoryHash = calculateInventoryHash(payload) + objectType = 'broadcast' + shared.inventory[inventoryHash] = ( + objectType, streamNumber, payload, int(time.time())) + print 'Broadcasting inv for my broadcast (within sendBroadcast function):', inventoryHash.encode('hex') + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Broadcast sent on %1").arg(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 + shared.sqlLock.acquire() + t = ('broadcastsent', int( + 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) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + elif addressVersionNumber == 3 or int(time.time()) > encryptedBroadcastSwitchoverTime: + # We need to convert our private keys to public keys in order + # to include them. + try: + privSigningKeyBase58 = shared.config.get( + fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + fromaddress, 'privencryptionkey') + except: + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + continue + + privSigningKeyHex = shared.decodeWalletImportFormat( + 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. + 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 += encodeVarint(2) # broadcast version + payload += encodeVarint(streamNumber) + + dataToEncrypt = encodeVarint(2) # broadcast version + dataToEncrypt += encodeVarint(addressVersionNumber) + dataToEncrypt += encodeVarint(streamNumber) + dataToEncrypt += '\x00\x00\x00\x01' # behavior bitfield + dataToEncrypt += pubSigningKey[1:] + dataToEncrypt += pubEncryptionKey[1:] + if addressVersionNumber >= 3: + dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'noncetrialsperbyte')) + dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'payloadlengthextrabytes')) + dataToEncrypt += '\x02' # message encoding type + dataToEncrypt += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding per the documentation on the wiki. + dataToEncrypt += 'Subject:' + subject + '\n' + 'Body:' + body + signature = highlevelcrypto.sign( + dataToEncrypt, privSigningKeyHex) + dataToEncrypt += encodeVarint(len(signature)) + dataToEncrypt += signature + + # Encrypt the broadcast with the information contained in the broadcaster's address. Anyone who knows the address can generate + # the private encryption key to decrypt the broadcast. This provides virtually no privacy; its purpose is to keep questionable + # and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties. + privEncryptionKey = hashlib.sha512(encodeVarint( + addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32] + pubEncryptionKey = pointMult(privEncryptionKey) + payload += highlevelcrypto.encrypt( + dataToEncrypt, pubEncryptionKey.encode('hex')) + + target = 2 ** 64 / ((len( + payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + print '(For broadcast message) Doing proof of work...' + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send broadcast...")))) + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce + + payload = pack('>Q', nonce) + payload + + inventoryHash = calculateInventoryHash(payload) + objectType = 'broadcast' + shared.inventory[inventoryHash] = ( + objectType, streamNumber, payload, int(time.time())) + print 'sending inv (within sendBroadcast function)' + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Broadcast sent on %1").arg(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 + shared.sqlLock.acquire() + t = ('broadcastsent', int( + 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) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + else: + shared.printLock.acquire() + sys.stderr.write( + 'Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n') + shared.printLock.release() + + def sendMsg(self): + # Check to see if there are any messages queued to be sent + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT DISTINCT toaddress FROM sent WHERE (status='msgqueued' AND folder='sent')''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: # For each address to which we need to send a message, check to see if we have its pubkey already. + toaddress, = row + toripe = decodeAddress(toaddress)[3] + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT hash FROM pubkeys WHERE hash=? ''') + shared.sqlSubmitQueue.put((toripe,)) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn != []: # If we have the needed pubkey, set the status to doingmsgpow (we'll do it further down) + t = (toaddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + else: # We don't have the needed pubkey. Set the status to 'awaitingpubkey' and request it if we haven't already + if toripe in neededPubkeys: + # We already sent a request for the pubkey + t = (toaddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='msgqueued' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByHash', ( + toripe, bitmessagemain.translateText("MainWindow",'Encryption key was requested earlier.')))) + else: + # We have not yet sent a request for the pubkey + t = (toaddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='doingpubkeypow' WHERE toaddress=? AND status='msgqueued' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByHash', ( + toripe, bitmessagemain.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + self.requestPubKey(toaddress) + 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. + 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,)) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: # For each message we need to send.. + 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. + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT hash FROM pubkeys WHERE hash=? ''') + shared.sqlSubmitQueue.put((toripe,)) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn == [] and toripe not in neededPubkeys: + # We no longer have the needed pubkey and we haven't requested + # it. + 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')) + shared.printLock.release() + t = (toaddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='msgqueued' WHERE toaddress=? AND status='doingmsgpow' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByHash', ( + toripe, bitmessagemain.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + self.requestPubKey(toaddress) + continue + bitmessagemain.ackdataForWhichImWatching[ackdata] = 0 + toStatus, toAddressVersionNumber, toStreamNumber, toHash = decodeAddress( + toaddress) + fromStatus, fromAddressVersionNumber, fromStreamNumber, fromHash = decodeAddress( + fromaddress) + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Looking up the receiver\'s public key")))) + shared.printLock.acquire() + print 'Found a message in our database that needs to be sent with this pubkey.' + print 'First 150 characters of message:', repr(message[:150]) + shared.printLock.release() + + # mark the pubkey as 'usedpersonally' so that we don't ever delete + # it. + shared.sqlLock.acquire() + t = (toripe,) + shared.sqlSubmitQueue.put( + '''UPDATE pubkeys SET usedpersonally='yes' WHERE hash=?''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + 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. + shared.sqlSubmitQueue.put( + 'SELECT transmitdata FROM pubkeys WHERE hash=?') + shared.sqlSubmitQueue.put((toripe,)) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn == []: + shared.printLock.acquire() + sys.stderr.write( + '(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n') + shared.printLock.release() + return + for row in queryreturn: + 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. + readPosition = 8 # to bypass the nonce + pubkeyEmbeddedTime, = unpack( + '>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: + pubkeyEmbeddedTime, = unpack( + '>Q', pubkeyPayload[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + readPosition += 1 # to bypass the address version whose length is definitely 1 + streamNumber, streamNumberLength = decodeVarint( + pubkeyPayload[readPosition:readPosition + 10]) + readPosition += streamNumberLength + behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4] + readPosition += 4 # to bypass the bitfield of behaviors + # pubSigningKeyBase256 = + # pubkeyPayload[readPosition:readPosition+64] #We don't use this + # key for anything here. + readPosition += 64 + pubEncryptionKeyBase256 = pubkeyPayload[ + readPosition:readPosition + 64] + readPosition += 64 + if toAddressVersionNumber == 2: + requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte + requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) + elif toAddressVersionNumber == 3: + requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( + pubkeyPayload[readPosition:readPosition + 10]) + readPosition += varintLength + requiredPayloadLengthExtraBytes, varintLength = decodeVarint( + pubkeyPayload[readPosition:readPosition + 10]) + 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. + requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte + if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: + requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( + requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes))))) + 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): + # The demanded difficulty is more than we are willing + # to do. + shared.sqlLock.acquire() + t = (ackdata,) + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( + requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes)).arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) + continue + + 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. + if fromAddressVersionNumber == 2: + payload = '\x01' # Message version. + payload += encodeVarint(fromAddressVersionNumber) + 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 ) + + # We need to convert our private keys to public keys in order + # to include them. + try: + privSigningKeyBase58 = shared.config.get( + fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + fromaddress, 'privencryptionkey') + except: + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + continue + + privSigningKeyHex = shared.decodeWalletImportFormat( + privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = shared.decodeWalletImportFormat( + privEncryptionKeyBase58).encode('hex') + + pubSigningKey = highlevelcrypto.privToPub( + 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 += 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 += '\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 + payload += encodeVarint(len(messageToTransmit)) + payload += messageToTransmit + fullAckPayload = self.generateFullAckMessage( + ackdata, toStreamNumber, embeddedTime) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out. + payload += encodeVarint(len(fullAckPayload)) + payload += fullAckPayload + signature = highlevelcrypto.sign(payload, privSigningKeyHex) + payload += encodeVarint(len(signature)) + payload += signature + + if fromAddressVersionNumber == 3: + payload = '\x01' # Message version. + payload += encodeVarint(fromAddressVersionNumber) + 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 ) + + # We need to convert our private keys to public keys in order + # to include them. + try: + privSigningKeyBase58 = shared.config.get( + fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = shared.config.get( + fromaddress, 'privencryptionkey') + except: + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( + ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + continue + + privSigningKeyHex = shared.decodeWalletImportFormat( + privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = shared.decodeWalletImportFormat( + privEncryptionKeyBase58).encode('hex') + + pubSigningKey = highlevelcrypto.privToPub( + 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 += 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 shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(toaddress): + payload += encodeVarint( + shared.networkDefaultProofOfWorkNonceTrialsPerByte) + payload += encodeVarint( + shared.networkDefaultPayloadLengthExtraBytes) + else: + payload += encodeVarint(shared.config.getint( + 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 += '\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 + payload += encodeVarint(len(messageToTransmit)) + payload += messageToTransmit + fullAckPayload = self.generateFullAckMessage( + ackdata, toStreamNumber, embeddedTime) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out. + payload += encodeVarint(len(fullAckPayload)) + payload += fullAckPayload + signature = highlevelcrypto.sign(payload, privSigningKeyHex) + payload += encodeVarint(len(signature)) + payload += signature + + + # We have assembled the data that will be encrypted. + try: + encrypted = highlevelcrypto.encrypt(payload,"04"+pubEncryptionKeyBase256.encode('hex')) + except: + shared.sqlLock.acquire() + t = (ackdata,) + shared.sqlSubmitQueue.put('''UPDATE sent SET status='badkey' WHERE ackdata=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,bitmessagemain.translateText("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) + continue + encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted + target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) + 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 + shared.printLock.release() + powStartTime = time.time() + initialHash = hashlib.sha512(encryptedPayload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + shared.printLock.acquire() + print '(For msg message) Found proof of work', trialValue, 'Nonce:', nonce + try: + print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' + except: + pass + shared.printLock.release() + encryptedPayload = pack('>Q', nonce) + encryptedPayload + + inventoryHash = calculateInventoryHash(encryptedPayload) + objectType = 'msg' + shared.inventory[inventoryHash] = ( + objectType, toStreamNumber, encryptedPayload, int(time.time())) + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(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') + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + + # Update the status of the message in the 'sent' table to have a + # 'msgsent' status + shared.sqlLock.acquire() + t = (ackdata,) + shared.sqlSubmitQueue.put('''UPDATE sent SET status='msgsent' WHERE ackdata=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + + def requestPubKey(self, toAddress): + toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress( + toAddress) + if toStatus != 'success': + shared.printLock.acquire() + sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr( + toAddress) + '. Please report this error to Atheros.') + shared.printLock.release() + return + neededPubkeys[ripe] = 0 + payload = pack('>Q', (int(time.time()) + random.randrange( + -300, 300))) # the current time plus or minus five minutes. + payload += encodeVarint(addressVersionNumber) + payload += encodeVarint(streamNumber) + payload += ripe + shared.printLock.acquire() + print 'making request for pubkey with ripe:', ripe.encode('hex') + shared.printLock.release() + # print 'trial value', trialValue + statusbar = 'Doing the computations necessary to request the recipient\'s public key.' + shared.UISignalQueue.put(('updateStatusBar', statusbar)) + shared.UISignalQueue.put(('updateSentItemStatusByHash', ( + ripe, bitmessagemain.translateText("MainWindow",'Doing work necessary to request encryption key.')))) + target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + shared.printLock.acquire() + print 'Found proof of work', trialValue, 'Nonce:', nonce + shared.printLock.release() + + payload = pack('>Q', nonce) + payload + inventoryHash = calculateInventoryHash(payload) + objectType = 'getpubkey' + shared.inventory[inventoryHash] = ( + objectType, streamNumber, payload, int(time.time())) + print 'sending inv (for the getpubkey message)' + shared.broadcastToSendDataQueues(( + streamNumber, 'sendinv', inventoryHash)) + + t = (toAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='doingpubkeypow' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + + shared.UISignalQueue.put(( + 'updateStatusBar', bitmessagemain.translateText("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) + shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, bitmessagemain.translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( + strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) + + def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime): + payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata + target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) + shared.printLock.acquire() + print '(For ack message) Doing proof of work...' + shared.printLock.release() + powStartTime = time.time() + initialHash = hashlib.sha512(payload).digest() + trialValue, nonce = proofofwork.run(target, initialHash) + shared.printLock.acquire() + print '(For ack message) Found proof of work', trialValue, 'Nonce:', nonce + try: + print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' + except: + pass + shared.printLock.release() + payload = pack('>Q', nonce) + payload + headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. + headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' + headerData += pack('>L', len(payload)) + headerData += hashlib.sha512(payload).digest()[:4] + return headerData + payload From 27a8662f2272da797192965a1b89951857a7b886 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Fri, 21 Jun 2013 23:29:04 +0100 Subject: [PATCH 29/93] Seperating class_singleListener, class_receiveDataThread, class_sendDataThread --- src/bitmessagemain.py | 2190 +------------------------------- src/class_receiveDataThread.py | 2028 +++++++++++++++++++++++++++++ src/class_sendDataThread.py | 165 +++ src/class_singleListener.py | 3 + 4 files changed, 2198 insertions(+), 2188 deletions(-) create mode 100644 src/class_receiveDataThread.py create mode 100644 src/class_sendDataThread.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index d22db71d..d25efbc7 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -54,6 +54,8 @@ from class_sqlThread import * from class_singleCleaner import * from class_singleWorker import * from class_addressGenerator import * +from class_sendDataThread import * +from class_receiveDataThread import * # Helper Functions import helper_startup @@ -224,2194 +226,6 @@ class outgoingSynSender(threading.Thread): time.sleep(0.1) -# This thread is created either by the synSenderThread(for outgoing -# connections) or the singleListenerThread(for incoming connectiosn). - - -class receiveDataThread(threading.Thread): - - def __init__(self): - threading.Thread.__init__(self) - self.data = '' - self.verackSent = False - self.verackReceived = False - - def setup( - self, - sock, - HOST, - port, - streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware): - self.sock = sock - self.HOST = HOST - self.PORT = port - self.streamNumber = streamNumber - self.payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header - 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. - 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. - self.initiatedConnection = False - else: - self.initiatedConnection = True - 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.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware - - def run(self): - shared.printLock.acquire() - print 'ID of the receiveDataThread is', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) - shared.printLock.release() - while True: - try: - self.data += self.sock.recv(4096) - except socket.timeout: - shared.printLock.acquire() - print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' - shared.printLock.release() - break - except Exception as err: - shared.printLock.acquire() - print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err - shared.printLock.release() - break - # print 'Received', repr(self.data) - if self.data == "": - shared.printLock.acquire() - print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' - shared.printLock.release() - break - else: - self.processData() - - try: - del selfInitiatedConnections[self.streamNumber][self] - shared.printLock.acquire() - print 'removed self (a receiveDataThread) from selfInitiatedConnections' - shared.printLock.release() - except: - pass - shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - try: - del shared.connectedHostsList[self.HOST] - except Exception as err: - shared.printLock.acquire() - print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err - shared.printLock.release() - try: - del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ - self.HOST] - except: - pass - shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) - shared.printLock.acquire() - print 'The size of the connectedHostsList is now:', len(shared.connectedHostsList) - shared.printLock.release() - - def processData(self): - global verbose - # if verbose >= 3: - # shared.printLock.acquire() - # print 'self.data is currently ', repr(self.data) - # shared.printLock.release() - if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length - return - if self.data[0:4] != '\xe9\xbe\xb4\xd9': - if verbose >= 1: - shared.printLock.acquire() - print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) - shared.printLock.release() - self.data = "" - return - self.payloadLength, = unpack('>L', self.data[16:20]) - if len(self.data) < self.payloadLength + 24: # check if the whole message has arrived yet. - return - if self.data[20:24] != hashlib.sha512(self.data[24:self.payloadLength + 24]).digest()[0:4]: # test the checksum in the message. If it is correct... - print 'Checksum incorrect. Clearing this message.' - self.data = self.data[self.payloadLength + 24:] - self.processData() - 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. - 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.knownNodes[self.streamNumber][ - self.HOST] = (self.PORT, int(time.time())) - shared.knownNodesLock.release() - if self.payloadLength <= 180000000: # If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.) - remoteCommand = self.data[4:16] - shared.printLock.acquire() - print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.HOST - shared.printLock.release() - if remoteCommand == 'version\x00\x00\x00\x00\x00': - self.recversion(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'verack\x00\x00\x00\x00\x00\x00': - self.recverack() - elif remoteCommand == 'addr\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recaddr(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'getpubkey\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recgetpubkey(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'pubkey\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recpubkey(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recinv(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'getdata\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recgetdata(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recmsg(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'broadcast\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.recbroadcast(self.data[24:self.payloadLength + 24]) - elif remoteCommand == 'ping\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - self.sendpong() - elif remoteCommand == 'pong\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - pass - elif remoteCommand == 'alert\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: - pass - - self.data = self.data[ - self.payloadLength + 24:] # take this message out and then process the next message - if self.data == '': - while len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: - random.seed() - objectHash, = random.sample( - self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1) - if objectHash in shared.inventory: - shared.printLock.acquire() - print 'Inventory (in memory) already has object listed in inv message.' - shared.printLock.release() - del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ - objectHash] - elif isInSqlInventory(objectHash): - if verbose >= 3: - shared.printLock.acquire() - print 'Inventory (SQL on disk) already has object listed in inv message.' - shared.printLock.release() - del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ - objectHash] - else: - self.sendgetdata(objectHash) - del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ - objectHash] # It is possible that the remote node doesn't respond with the object. In that case, we'll very likely get it from someone else anyway. - if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - shared.printLock.release() - 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. - except: - pass - break - if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - shared.printLock.release() - 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. - except: - pass - if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - 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. - if len(self.ackDataThatWeHaveYetToSend) > 0: - self.data = self.ackDataThatWeHaveYetToSend.pop() - self.processData() - - def isProofOfWorkSufficient( - self, - data, - nonceTrialsPerByte=0, - payloadLengthExtraBytes=0): - if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: - nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte - if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: - payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[ - :8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8]) - # print 'POW:', POW - return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte)) - - def sendpong(self): - print 'Sending pong' - 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') - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - def recverack(self): - print 'verack received' - self.verackReceived = True - if self.verackSent: - # We have thus both sent and received a verack. - self.connectionFullyEstablished() - - def connectionFullyEstablished(self): - self.connectionIsOrWasFullyEstablished = True - if not self.initiatedConnection: - 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. - shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) - remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[ - self.streamNumber][self.HOST] - shared.printLock.acquire() - print 'Connection fully established with', self.HOST, remoteNodeIncomingPort - 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.' - shared.printLock.release() - self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.HOST, - remoteNodeIncomingPort)]) # This lets all of our peers know about this new node. - self.sendaddr() # This is one large addr message to this one peer. - if not self.initiatedConnection and len(shared.connectedHostsList) > 200: - shared.printLock.acquire() - print 'We are connected to too many people. Closing connection.' - shared.printLock.release() - shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - return - self.sendBigInv() - - def sendBigInv(self): - shared.sqlLock.acquire() - # Select all hashes which are younger than two days old and in this - # stream. - t = (int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers, int( - time.time()) - lengthOfTimeToHoldOnToAllPubkeys, self.streamNumber) - shared.sqlSubmitQueue.put( - '''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - bigInvList = {} - for row in queryreturn: - hash, = row - if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: - bigInvList[hash] = 0 - # 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.objectsOfWhichThisRemoteNodeIsAlreadyAware: - objectType, streamNumber, payload, receivedTime = storedValue - if streamNumber == self.streamNumber and receivedTime > int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers: - bigInvList[hash] = 0 - numberOfObjectsInInvMessage = 0 - payload = '' - # Now let us start appending all of these hashes together. They will be - # sent out in a big inv message to our new peer. - for hash, storedValue in bigInvList.items(): - payload += hash - 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. - self.sendinvMessageToJustThisOnePeer( - numberOfObjectsInInvMessage, payload) - payload = '' - numberOfObjectsInInvMessage = 0 - if numberOfObjectsInInvMessage > 0: - self.sendinvMessageToJustThisOnePeer( - numberOfObjectsInInvMessage, payload) - - # Self explanatory. Notice that there is also a broadcastinv function for - # broadcasting invs to everyone in our stream. - def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): - payload = encodeVarint(numberOfObjects) + payload - 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] - shared.printLock.acquire() - print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' - shared.printLock.release() - try: - self.sock.sendall(headerData + payload) - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - # We have received a broadcast message - def recbroadcast(self, data): - self.messageProcessingStartTime = time.time() - # First we must check to make sure the proof of work is sufficient. - if not self.isProofOfWorkSufficient(data): - print 'Proof of work in broadcast message insufficient.' - return - readPosition = 8 # bypass the nonce - embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) - - # This section is used for the transition from 32 bit time to 64 bit - # time in the protocol. - if embeddedTime == 0: - embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - - if embeddedTime > (int(time.time()) + 10800): # prevent funny business - print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.' - return - if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): - print 'The embedded time in this broadcast message is too old. Ignoring message.' - return - if len(data) < 180: - print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.' - return - # Let us check to make sure the stream number is correct (thus - # preventing an individual from sending broadcasts out on the wrong - # streams or all streams). - broadcastVersion, broadcastVersionLength = decodeVarint( - data[readPosition:readPosition + 10]) - if broadcastVersion >= 2: - streamNumber, streamNumberLength = decodeVarint(data[ - readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10]) - if streamNumber != self.streamNumber: - print 'The stream number encoded in this broadcast message (' + str(streamNumber) + ') does not match the stream number on which it was received. Ignoring it.' - return - - shared.inventoryLock.acquire() - self.inventoryHash = calculateInventoryHash(data) - if self.inventoryHash in shared.inventory: - print 'We have already received this broadcast object. Ignoring.' - shared.inventoryLock.release() - return - elif isInSqlInventory(self.inventoryHash): - print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.' - shared.inventoryLock.release() - return - # It is valid so far. Let's let our peers know about it. - objectType = 'broadcast' - shared.inventory[self.inventoryHash] = ( - objectType, self.streamNumber, data, embeddedTime) - shared.inventoryLock.release() - self.broadcastinv(self.inventoryHash) - 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. - - # 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. - if len(data) > 100000000: # Size is greater than 100 megabytes - lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. - elif len(data) > 10000000: # Between 100 and 10 megabytes - lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds. - elif len(data) > 1000000: # Between 10 and 1 megabyte - lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds. - else: # Less than 1 megabyte - lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. - - sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ - (time.time() - self.messageProcessingStartTime) - if sleepTime > 0: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() - time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() - - # A broadcast message has a valid time and POW and requires processing. - # The recbroadcast function calls this one. - def processbroadcast(self, readPosition, data): - broadcastVersion, broadcastVersionLength = decodeVarint( - data[readPosition:readPosition + 9]) - readPosition += broadcastVersionLength - if broadcastVersion < 1 or broadcastVersion > 2: - 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 - if broadcastVersion == 1: - beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table - sendersAddressVersion, sendersAddressVersionLength = decodeVarint( - data[readPosition:readPosition + 9]) - if sendersAddressVersion <= 1 or sendersAddressVersion >= 3: - # Cannot decode senderAddressVersion higher than 2. Assuming - # the sender isn\'t being silly, you should upgrade Bitmessage - # because this message shall be ignored. - return - readPosition += sendersAddressVersionLength - if sendersAddressVersion == 2: - sendersStream, sendersStreamLength = decodeVarint( - data[readPosition:readPosition + 9]) - readPosition += sendersStreamLength - behaviorBitfield = data[readPosition:readPosition + 4] - readPosition += 4 - sendersPubSigningKey = '\x04' + \ - data[readPosition:readPosition + 64] - readPosition += 64 - sendersPubEncryptionKey = '\x04' + \ - data[readPosition:readPosition + 64] - readPosition += 64 - endOfPubkeyPosition = readPosition - sendersHash = data[readPosition:readPosition + 20] - if sendersHash not in shared.broadcastSendersForWhichImWatching: - # Display timing data - shared.printLock.acquire() - print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() - return - # At this point, this message claims to be from sendersHash and - # we are interested in it. We still have to hash the public key - # to make sure it is truly the key that matches the hash, and - # also check the signiture. - readPosition += 20 - - sha = hashlib.new('sha512') - sha.update(sendersPubSigningKey + sendersPubEncryptionKey) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) - if ripe.digest() != sendersHash: - # The sender of this message lied. - return - messageEncodingType, messageEncodingTypeLength = decodeVarint( - data[readPosition:readPosition + 9]) - if messageEncodingType == 0: - return - readPosition += messageEncodingTypeLength - messageLength, messageLengthLength = decodeVarint( - data[readPosition:readPosition + 9]) - readPosition += messageLengthLength - message = data[readPosition:readPosition + messageLength] - readPosition += messageLength - readPositionAtBottomOfMessage = readPosition - signatureLength, signatureLengthLength = decodeVarint( - data[readPosition:readPosition + 9]) - readPosition += signatureLengthLength - signature = data[readPosition:readPosition + signatureLength] - try: - if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')): - print 'ECDSA verify failed' - return - print 'ECDSA verify passed' - except Exception as err: - print 'ECDSA verify failed', err - return - # verify passed - - # Let's store the public key in case we want to reply to this person. - # We don't have the correct nonce or time (which would let us - # send out a pubkey message) so we'll just fill it with 1's. We - # won't be able to send this pubkey to others (without doing - # the proof of work ourselves, which this program is programmed - # to not do.) - t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[ - beginningOfPubkeyPosition:endOfPubkeyPosition], int(time.time()), 'yes') - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - # shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest()))) - # This will check to see whether we happen to be awaiting this - # pubkey in order to send a message. If we are, it will do the - # POW and send it. - self.possibleNewPubkey(ripe.digest()) - - fromAddress = encodeAddress( - sendersAddressVersion, sendersStream, ripe.digest()) - shared.printLock.acquire() - print 'fromAddress:', fromAddress - shared.printLock.release() - if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message - elif messageEncodingType == 1: - body = message - subject = '' - elif messageEncodingType == 0: - print 'messageEncodingType == 0. Doing nothing with the message.' - else: - body = 'Unknown encoding type.\n\n' + repr(message) - subject = '' - - toAddress = '[Broadcast subscribers]' - if messageEncodingType != 0: - - t = (self.inventoryHash, toAddress, fromAddress, subject, int( - time.time()), body, 'inbox', messageEncodingType, 0) - helper_inbox.insert(t) - - shared.UISignalQueue.put(('displayNewInboxMessage', ( - self.inventoryHash, toAddress, fromAddress, subject, body))) - - # If we are behaving as an API then we might need to run an - # outside command to let some program know that a new - # message has arrived. - if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): - try: - apiNotifyPath = shared.config.get( - 'bitmessagesettings', 'apinotifypath') - except: - apiNotifyPath = '' - if apiNotifyPath != '': - call([apiNotifyPath, "newBroadcast"]) - - # Display timing data - shared.printLock.acquire() - print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() - if broadcastVersion == 2: - cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += cleartextStreamNumberLength - initialDecryptionSuccessful = False - for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items(): - try: - decryptedData = cryptorObject.decrypt(data[readPosition:]) - toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key. - initialDecryptionSuccessful = True - print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') - break - except Exception as err: - pass - # print 'cryptorObject.decrypt Exception:', err - if not initialDecryptionSuccessful: - # This is not a broadcast I am interested in. - shared.printLock.acquire() - print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() - return - # At this point this is a broadcast I have decrypted and thus am - # interested in. - signedBroadcastVersion, readPosition = decodeVarint( - decryptedData[:10]) - beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table - sendersAddressVersion, sendersAddressVersionLength = decodeVarint( - decryptedData[readPosition:readPosition + 9]) - if sendersAddressVersion < 2 or sendersAddressVersion > 3: - print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.' - return - readPosition += sendersAddressVersionLength - sendersStream, sendersStreamLength = decodeVarint( - decryptedData[readPosition:readPosition + 9]) - if sendersStream != cleartextStreamNumber: - print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.' - return - readPosition += sendersStreamLength - behaviorBitfield = decryptedData[readPosition:readPosition + 4] - readPosition += 4 - sendersPubSigningKey = '\x04' + \ - decryptedData[readPosition:readPosition + 64] - readPosition += 64 - sendersPubEncryptionKey = '\x04' + \ - decryptedData[readPosition:readPosition + 64] - readPosition += 64 - if sendersAddressVersion >= 3: - requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += varintLength - print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte - requiredPayloadLengthExtraBytes, varintLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += varintLength - print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes - endOfPubkeyPosition = readPosition - - sha = hashlib.new('sha512') - sha.update(sendersPubSigningKey + sendersPubEncryptionKey) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) - - if toRipe != ripe.digest(): - print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.' - return - messageEncodingType, messageEncodingTypeLength = decodeVarint( - decryptedData[readPosition:readPosition + 9]) - if messageEncodingType == 0: - return - readPosition += messageEncodingTypeLength - messageLength, messageLengthLength = decodeVarint( - decryptedData[readPosition:readPosition + 9]) - readPosition += messageLengthLength - message = decryptedData[readPosition:readPosition + messageLength] - readPosition += messageLength - readPositionAtBottomOfMessage = readPosition - signatureLength, signatureLengthLength = decodeVarint( - decryptedData[readPosition:readPosition + 9]) - readPosition += signatureLengthLength - signature = decryptedData[ - readPosition:readPosition + signatureLength] - try: - if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')): - print 'ECDSA verify failed' - return - print 'ECDSA verify passed' - except Exception as err: - print 'ECDSA verify failed', err - return - # verify passed - - # Let's store the public key in case we want to reply to this - # person. - 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.sqlSubmitQueue.put( - '''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - # shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest()))) - # This will check to see whether we happen to be awaiting this - # pubkey in order to send a message. If we are, it will do the POW - # and send it. - self.possibleNewPubkey(ripe.digest()) - - fromAddress = encodeAddress( - sendersAddressVersion, sendersStream, ripe.digest()) - shared.printLock.acquire() - print 'fromAddress:', fromAddress - shared.printLock.release() - if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message - elif messageEncodingType == 1: - body = message - subject = '' - elif messageEncodingType == 0: - print 'messageEncodingType == 0. Doing nothing with the message.' - else: - body = 'Unknown encoding type.\n\n' + repr(message) - subject = '' - - toAddress = '[Broadcast subscribers]' - if messageEncodingType != 0: - - t = (self.inventoryHash, toAddress, fromAddress, subject, int( - time.time()), body, 'inbox', messageEncodingType, 0) - helper_inbox.insert(t) - - shared.UISignalQueue.put(('displayNewInboxMessage', ( - self.inventoryHash, toAddress, fromAddress, subject, body))) - - # If we are behaving as an API then we might need to run an - # outside command to let some program know that a new message - # has arrived. - if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): - try: - apiNotifyPath = shared.config.get( - 'bitmessagesettings', 'apinotifypath') - except: - apiNotifyPath = '' - if apiNotifyPath != '': - call([apiNotifyPath, "newBroadcast"]) - - # Display timing data - shared.printLock.acquire() - print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() - - # We have received a msg message. - def recmsg(self, data): - self.messageProcessingStartTime = time.time() - # First we must check to make sure the proof of work is sufficient. - if not self.isProofOfWorkSufficient(data): - print 'Proof of work in msg message insufficient.' - return - - readPosition = 8 - embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) - - # This section is used for the transition from 32 bit time to 64 bit - # time in the protocol. - if embeddedTime == 0: - embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - - if embeddedTime > int(time.time()) + 10800: - print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime - return - if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: - print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime - return - streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint( - data[readPosition:readPosition + 9]) - if streamNumberAsClaimedByMsg != self.streamNumber: - print 'The stream number encoded in this msg (' + str(streamNumberAsClaimedByMsg) + ') message does not match the stream number on which it was received. Ignoring it.' - return - readPosition += streamNumberAsClaimedByMsgLength - self.inventoryHash = calculateInventoryHash(data) - shared.inventoryLock.acquire() - if self.inventoryHash in shared.inventory: - print 'We have already received this msg message. Ignoring.' - shared.inventoryLock.release() - return - elif isInSqlInventory(self.inventoryHash): - print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.' - shared.inventoryLock.release() - return - # This msg message is valid. Let's let our peers know about it. - objectType = 'msg' - shared.inventory[self.inventoryHash] = ( - objectType, self.streamNumber, data, embeddedTime) - shared.inventoryLock.release() - self.broadcastinv(self.inventoryHash) - 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. - - # 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. - if len(data) > 100000000: # Size is greater than 100 megabytes - lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds. - elif len(data) > 10000000: # Between 100 and 10 megabytes - lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 10 MB message: 0.53 seconds. Actual length of time it takes in practice when processing a real message: 1.44 seconds. - elif len(data) > 1000000: # Between 10 and 1 megabyte - lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 1 MB message: 0.18 seconds. Actual length of time it takes in practice when processing a real message: 0.30 seconds. - 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. - - sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ - (time.time() - self.messageProcessingStartTime) - if sleepTime > 0: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() - time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() - - # A msg message has a valid time and POW and requires processing. The - # recmsg function calls this one. - def processmsg(self, readPosition, encryptedData): - initialDecryptionSuccessful = False - # Let's check whether this is a message acknowledgement bound for us. - if encryptedData[readPosition:] in ackdataForWhichImWatching: - shared.printLock.acquire() - print 'This msg IS an acknowledgement bound for me.' - shared.printLock.release() - del ackdataForWhichImWatching[encryptedData[readPosition:]] - t = ('ackreceived', encryptedData[readPosition:]) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - 'UPDATE sent SET status=? WHERE ackdata=?') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( - strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) - return - else: - shared.printLock.acquire() - print 'This was NOT an acknowledgement bound for me.' - # print 'ackdataForWhichImWatching', ackdataForWhichImWatching - shared.printLock.release() - - # This is not an acknowledgement bound for me. See if it is a message - # bound for me by trying to decrypt it with my private keys. - for key, cryptorObject in shared.myECCryptorObjects.items(): - try: - decryptedData = cryptorObject.decrypt( - encryptedData[readPosition:]) - toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data. - initialDecryptionSuccessful = True - print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') - break - except Exception as err: - pass - # print 'cryptorObject.decrypt Exception:', err - if not initialDecryptionSuccessful: - # This is not a message bound for me. - shared.printLock.acquire() - print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() - else: - # This is a message bound for me. - toAddress = shared.myAddressesByHash[ - toRipe] # Look up my address based on the RIPE hash. - readPosition = 0 - messageVersion, messageVersionLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += messageVersionLength - if messageVersion != 1: - print 'Cannot understand message versions other than one. Ignoring message.' - return - sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += sendersAddressVersionNumberLength - if sendersAddressVersionNumber == 0: - print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.' - return - if sendersAddressVersionNumber >= 4: - print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.' - return - if len(decryptedData) < 170: - print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.' - return - sendersStreamNumber, sendersStreamNumberLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - if sendersStreamNumber == 0: - print 'sender\'s stream number is 0. Ignoring message.' - return - readPosition += sendersStreamNumberLength - behaviorBitfield = decryptedData[readPosition:readPosition + 4] - readPosition += 4 - pubSigningKey = '\x04' + decryptedData[ - readPosition:readPosition + 64] - readPosition += 64 - pubEncryptionKey = '\x04' + decryptedData[ - readPosition:readPosition + 64] - readPosition += 64 - if sendersAddressVersionNumber >= 3: - requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += varintLength - print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte - requiredPayloadLengthExtraBytes, varintLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += varintLength - print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes - endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use. - if toRipe != decryptedData[readPosition:readPosition + 20]: - shared.printLock.acquire() - print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.' - print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html' - print 'your toRipe:', toRipe.encode('hex') - print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex') - shared.printLock.release() - return - readPosition += 20 - messageEncodingType, messageEncodingTypeLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += messageEncodingTypeLength - messageLength, messageLengthLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += messageLengthLength - message = decryptedData[readPosition:readPosition + messageLength] - # print 'First 150 characters of message:', repr(message[:150]) - readPosition += messageLength - ackLength, ackLengthLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += ackLengthLength - ackData = decryptedData[readPosition:readPosition + ackLength] - readPosition += ackLength - positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature - signatureLength, signatureLengthLength = decodeVarint( - decryptedData[readPosition:readPosition + 10]) - readPosition += signatureLengthLength - signature = decryptedData[ - readPosition:readPosition + signatureLength] - try: - if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')): - print 'ECDSA verify failed' - return - print 'ECDSA verify passed' - except Exception as err: - print 'ECDSA verify failed', err - return - shared.printLock.acquire() - print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' - shared.printLock.release() - # calculate the fromRipe. - sha = hashlib.new('sha512') - sha.update(pubSigningKey + pubEncryptionKey) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) - # Let's store the public key in case we want to reply to this - # person. - t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[ - messageVersionLength:endOfThePublicKeyPosition], int(time.time()), 'yes') - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - # shared.workerQueue.put(('newpubkey',(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()))) - # This will check to see whether we happen to be awaiting this - # pubkey in order to send a message. If we are, it will do the POW - # and send it. - self.possibleNewPubkey(ripe.digest()) - fromAddress = encodeAddress( - sendersAddressVersionNumber, sendersStreamNumber, ripe.digest()) - # If this message is bound for one of my version 3 addresses (or - # higher), then we must check to make sure it meets our demanded - # proof of work requirement. - if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher: - if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person: - requiredNonceTrialsPerByte = shared.config.getint( - toAddress, 'noncetrialsperbyte') - requiredPayloadLengthExtraBytes = shared.config.getint( - toAddress, 'payloadlengthextrabytes') - if not self.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes): - print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.' - return - blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists. - if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist - t = (fromAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT label FROM blacklist where address=? and enabled='1' ''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn != []: - shared.printLock.acquire() - print 'Message ignored because address is in blacklist.' - shared.printLock.release() - blockMessage = True - else: # We're using a whitelist - t = (fromAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT label FROM whitelist where address=? and enabled='1' ''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn == []: - print 'Message ignored because address not in whitelist.' - blockMessage = True - if not blockMessage: - print 'fromAddress:', fromAddress - print 'First 150 characters of message:', repr(message[:150]) - - toLabel = shared.config.get(toAddress, 'label') - if toLabel == '': - toLabel = toAddress - - if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - subject = subject[ - :500] # Only save and show the first 500 characters of the subject. Any more is probably an attak. - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message - elif messageEncodingType == 1: - body = message - subject = '' - elif messageEncodingType == 0: - print 'messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.' - else: - body = 'Unknown encoding type.\n\n' + repr(message) - subject = '' - if messageEncodingType != 0: - t = (self.inventoryHash, toAddress, fromAddress, subject, int( - time.time()), body, 'inbox', messageEncodingType, 0) - helper_inbox.insert(t) - - shared.UISignalQueue.put(('displayNewInboxMessage', ( - self.inventoryHash, toAddress, fromAddress, subject, body))) - - # If we are behaving as an API then we might need to run an - # outside command to let some program know that a new message - # has arrived. - if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): - try: - apiNotifyPath = shared.config.get( - 'bitmessagesettings', 'apinotifypath') - except: - apiNotifyPath = '' - if apiNotifyPath != '': - call([apiNotifyPath, "newMessage"]) - - # Let us now check and see whether our receiving address is - # behaving as a mailing list - if shared.safeConfigGetBoolean(toAddress, 'mailinglist'): - try: - mailingListName = shared.config.get( - toAddress, 'mailinglistname') - except: - mailingListName = '' - # Let us send out this message as a broadcast - subject = self.addMailingListNameToSubject( - subject, mailingListName) - # Let us now send this message out as a broadcast - message = 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. - ackdata = OpenSSL.rand( - 32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating. - toAddress = '[Broadcast subscribers]' - ripe = '' - - t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int( - time.time()), 'broadcastqueued', 1, 1, 'sent', 2) - helper_sent.insert(t) - - shared.UISignalQueue.put(('displayNewSentMessage', ( - toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata))) - shared.workerQueue.put(('sendbroadcast', '')) - - if self.isAckDataValid(ackData): - print 'ackData is valid. Will process it.' - self.ackDataThatWeHaveYetToSend.append( - ackData) # When we have processed all data, the processData function will pop the ackData out and process it as if it is a message received from our peer. - # Display timing data - timeRequiredToAttemptToDecryptMessage = time.time( - ) - self.messageProcessingStartTime - successfullyDecryptMessageTimings.append( - timeRequiredToAttemptToDecryptMessage) - sum = 0 - for item in successfullyDecryptMessageTimings: - sum += item - shared.printLock.acquire() - print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage - print 'Average time for all message decryption successes since startup:', sum / len(successfullyDecryptMessageTimings) - shared.printLock.release() - - def isAckDataValid(self, ackData): - if len(ackData) < 24: - print 'The length of ackData is unreasonably short. Not sending ackData.' - return False - if ackData[0:4] != '\xe9\xbe\xb4\xd9': - print 'Ackdata magic bytes were wrong. Not sending ackData.' - return False - ackDataPayloadLength, = unpack('>L', ackData[16:20]) - if len(ackData) - 24 != ackDataPayloadLength: - print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.' - return False - if ackData[4:16] != 'getpubkey\x00\x00\x00' and ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'broadcast\x00\x00\x00': - return False - return True - - def addMailingListNameToSubject(self, subject, mailingListName): - subject = subject.strip() - if subject[:3] == 'Re:' or subject[:3] == 'RE:': - subject = subject[3:].strip() - if '[' + mailingListName + ']' in subject: - return subject - else: - return '[' + mailingListName + '] ' + subject - - def possibleNewPubkey(self, toRipe): - if toRipe in neededPubkeys: - print 'We have been awaiting the arrival of this pubkey.' - del neededPubkeys[toRipe] - t = (toRipe,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - shared.workerQueue.put(('sendmessage', '')) - else: - shared.printLock.acquire() - print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') - shared.printLock.release() - - # We have received a pubkey - def recpubkey(self, data): - self.pubkeyProcessingStartTime = time.time() - if len(data) < 146 or len(data) > 600: # sanity check - return - # We must check to make sure the proof of work is sufficient. - if not self.isProofOfWorkSufficient(data): - print 'Proof of work in pubkey message insufficient.' - return - - readPosition = 8 # for the nonce - embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) - - # This section is used for the transition from 32 bit time to 64 bit - # time in the protocol. - if embeddedTime == 0: - embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - - if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys: - shared.printLock.acquire() - print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime - shared.printLock.release() - return - if embeddedTime > int(time.time()) + 10800: - shared.printLock.acquire() - print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.' - shared.printLock.release() - return - addressVersion, varintLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += varintLength - streamNumber, varintLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += varintLength - if self.streamNumber != streamNumber: - print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.' - return - - inventoryHash = calculateInventoryHash(data) - shared.inventoryLock.acquire() - if inventoryHash in shared.inventory: - print 'We have already received this pubkey. Ignoring it.' - shared.inventoryLock.release() - return - elif isInSqlInventory(inventoryHash): - print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.' - shared.inventoryLock.release() - return - objectType = 'pubkey' - shared.inventory[inventoryHash] = ( - objectType, self.streamNumber, data, embeddedTime) - shared.inventoryLock.release() - self.broadcastinv(inventoryHash) - shared.UISignalQueue.put(( - 'incrementNumberOfPubkeysProcessed', 'no data')) - - self.processpubkey(data) - - lengthOfTimeWeShouldUseToProcessThisMessage = .2 - sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ - (time.time() - self.pubkeyProcessingStartTime) - if sleepTime > 0: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() - time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.' - shared.printLock.release() - - def processpubkey(self, data): - readPosition = 8 # for the nonce - embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) - - # This section is used for the transition from 32 bit time to 64 bit - # time in the protocol. - if embeddedTime == 0: - embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - - addressVersion, varintLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += varintLength - streamNumber, varintLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += varintLength - if addressVersion == 0: - print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.' - return - if addressVersion >= 4 or addressVersion == 1: - shared.printLock.acquire() - print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.' - shared.printLock.release() - return - if addressVersion == 2: - if len(data) < 146: # sanity check. This is the minimum possible length. - print '(within processpubkey) payloadLength less than 146. Sanity check failed.' - return - bitfieldBehaviors = data[readPosition:readPosition + 4] - readPosition += 4 - publicSigningKey = data[readPosition:readPosition + 64] - # Is it possible for a public key to be invalid such that trying to - # encrypt or sign with it will cause an error? If it is, we should - # probably test these keys here. - readPosition += 64 - publicEncryptionKey = data[readPosition:readPosition + 64] - if len(publicEncryptionKey) < 64: - print 'publicEncryptionKey length less than 64. Sanity check failed.' - return - sha = hashlib.new('sha512') - sha.update( - '\x04' + publicSigningKey + '\x04' + publicEncryptionKey) - ripeHasher = hashlib.new('ripemd160') - ripeHasher.update(sha.digest()) - ripe = ripeHasher.digest() - - shared.printLock.acquire() - print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber - print 'ripe', ripe.encode('hex') - print 'publicSigningKey in hex:', publicSigningKey.encode('hex') - print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') - shared.printLock.release() - - t = (ripe,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn != []: # if this pubkey is already in our database and if we have used it personally: - print 'We HAVE used this pubkey personally. Updating time.' - t = (ripe, data, embeddedTime, 'yes') - else: - print 'We have NOT used this pubkey personally. Inserting in database.' - t = (ripe, data, embeddedTime, 'no') - # This will also update the embeddedTime. - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - # shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) - self.possibleNewPubkey(ripe) - if addressVersion == 3: - if len(data) < 170: # sanity check. - print '(within processpubkey) payloadLength less than 170. Sanity check failed.' - return - bitfieldBehaviors = data[readPosition:readPosition + 4] - readPosition += 4 - publicSigningKey = '\x04' + data[readPosition:readPosition + 64] - # Is it possible for a public key to be invalid such that trying to - # encrypt or sign with it will cause an error? If it is, we should - # probably test these keys here. - readPosition += 64 - publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64] - readPosition += 64 - specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += specifiedNonceTrialsPerByteLength - specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += specifiedPayloadLengthExtraBytesLength - endOfSignedDataPosition = readPosition - signatureLength, signatureLengthLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += signatureLengthLength - signature = data[readPosition:readPosition + signatureLength] - try: - if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')): - print 'ECDSA verify failed (within processpubkey)' - return - print 'ECDSA verify passed (within processpubkey)' - except Exception as err: - print 'ECDSA verify failed (within processpubkey)', err - return - - sha = hashlib.new('sha512') - sha.update(publicSigningKey + publicEncryptionKey) - ripeHasher = hashlib.new('ripemd160') - ripeHasher.update(sha.digest()) - ripe = ripeHasher.digest() - - shared.printLock.acquire() - print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber - print 'ripe', ripe.encode('hex') - print 'publicSigningKey in hex:', publicSigningKey.encode('hex') - print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') - shared.printLock.release() - - t = (ripe,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn != []: # if this pubkey is already in our database and if we have used it personally: - print 'We HAVE used this pubkey personally. Updating time.' - t = (ripe, data, embeddedTime, 'yes') - else: - print 'We have NOT used this pubkey personally. Inserting in database.' - t = (ripe, data, embeddedTime, 'no') - # This will also update the embeddedTime. - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''INSERT INTO pubkeys VALUES (?,?,?,?)''') - shared.sqlSubmitQueue.put(t) - shared.sqlReturnQueue.get() - shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - # shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) - self.possibleNewPubkey(ripe) - - # We have received a getpubkey message - def recgetpubkey(self, data): - if not self.isProofOfWorkSufficient(data): - print 'Proof of work in getpubkey message insufficient.' - return - if len(data) < 34: - print 'getpubkey message doesn\'t contain enough data. Ignoring.' - return - readPosition = 8 # bypass the nonce - embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) - - # This section is used for the transition from 32 bit time to 64 bit - # time in the protocol. - if embeddedTime == 0: - embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) - readPosition += 8 - else: - readPosition += 4 - - if embeddedTime > int(time.time()) + 10800: - print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime - return - if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: - print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime - return - requestedAddressVersionNumber, addressVersionLength = decodeVarint( - data[readPosition:readPosition + 10]) - readPosition += addressVersionLength - streamNumber, streamNumberLength = decodeVarint( - data[readPosition:readPosition + 10]) - if streamNumber != self.streamNumber: - print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber - return - readPosition += streamNumberLength - - inventoryHash = calculateInventoryHash(data) - shared.inventoryLock.acquire() - if inventoryHash in shared.inventory: - print 'We have already received this getpubkey request. Ignoring it.' - shared.inventoryLock.release() - return - elif isInSqlInventory(inventoryHash): - print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.' - shared.inventoryLock.release() - return - - objectType = 'getpubkey' - shared.inventory[inventoryHash] = ( - objectType, self.streamNumber, data, embeddedTime) - shared.inventoryLock.release() - # This getpubkey request is valid so far. Forward to peers. - self.broadcastinv(inventoryHash) - - if requestedAddressVersionNumber == 0: - print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.' - return - elif requestedAddressVersionNumber == 1: - print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.' - return - elif requestedAddressVersionNumber > 3: - print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.' - return - - requestedHash = data[readPosition:readPosition + 20] - if len(requestedHash) != 20: - print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.' - return - print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex') - - if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine - if decodeAddress(shared.myAddressesByHash[requestedHash])[1] != requestedAddressVersionNumber: - 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') - shared.printLock.release() - return - try: - lastPubkeySendTime = int(shared.config.get( - shared.myAddressesByHash[requestedHash], 'lastpubkeysendtime')) - except: - lastPubkeySendTime = 0 - if lastPubkeySendTime < time.time() - lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago - shared.printLock.acquire() - 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() - if requestedAddressVersionNumber == 2: - shared.workerQueue.put(( - 'doPOWForMyV2Pubkey', requestedHash)) - elif requestedAddressVersionNumber == 3: - shared.workerQueue.put(( - 'doPOWForMyV3Pubkey', requestedHash)) - else: - 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 - shared.printLock.release() - else: - shared.printLock.acquire() - print 'This getpubkey request is not for any of my keys.' - shared.printLock.release() - - # We have received an inv message - def recinv(self, data): - totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = 0 # ..from all peers, counting duplicates seperately (because they take up memory) - if len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) > 0: - for key, value in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer.items(): - totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave += value - shared.printLock.acquire() - print 'number of keys(hosts) in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) - print 'totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = ', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave - shared.printLock.release() - numberOfItemsInInv, lengthOfVarint = decodeVarint(data[:10]) - if numberOfItemsInInv > 50000: - sys.stderr.write('Too many items in inv message!') - return - if len(data) < lengthOfVarint + (numberOfItemsInInv * 32): - print 'inv message doesn\'t contain enough data. Ignoring.' - return - if numberOfItemsInInv == 1: # we'll just request this data from the person who advertised the object. - if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation - shared.printLock.acquire() - 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() - return - self.objectsOfWhichThisRemoteNodeIsAlreadyAware[ - data[lengthOfVarint:32 + lengthOfVarint]] = 0 - if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: - shared.printLock.acquire() - print 'Inventory (in memory) has inventory item already.' - shared.printLock.release() - elif isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): - print 'Inventory (SQL on disk) has inventory item already.' - else: - self.sendgetdata(data[lengthOfVarint:32 + lengthOfVarint]) - else: - print 'inv message lists', numberOfItemsInInv, 'objects.' - for i in range(numberOfItemsInInv): # upon finishing dealing with an incoming message, the receiveDataThread will request a random object from the peer. This way if we get multiple inv messages from multiple peers which list mostly the same objects, we will make getdata requests for different random objects from the various peers. - if len(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) == 32: # The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously. - if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation - shared.printLock.acquire() - 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() - break - self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[ - lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0 - 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 - # hash - def sendgetdata(self, hash): - shared.printLock.acquire() - print 'sending getdata to retrieve object with hash:', hash.encode('hex') - shared.printLock.release() - payload = '\x01' + hash - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - 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 += hashlib.sha512(payload).digest()[:4] - try: - self.sock.sendall(headerData + payload) - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - # We have received a getdata request from our peer - def recgetdata(self, data): - numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint( - data[:10]) - if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems): - print 'getdata message does not contain enough data. Ignoring.' - return - for i in xrange(numberOfRequestedInventoryItems): - hash = data[lengthOfVarint + ( - i * 32):32 + lengthOfVarint + (i * 32)] - shared.printLock.acquire() - print 'received getdata request for item:', hash.encode('hex') - shared.printLock.release() - # print 'inventory is', shared.inventory - if hash in shared.inventory: - objectType, streamNumber, payload, receivedTime = shared.inventory[ - hash] - self.sendData(objectType, payload) - else: - t = (hash,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''select objecttype, payload from inventory where hash=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn != []: - for row in queryreturn: - objectType, payload = row - self.sendData(objectType, payload) - else: - print 'Someone asked for an object with a getdata which is not in either our memory inventory or our SQL inventory. That shouldn\'t have happened.' - - # Our peer has requested (in a getdata message) that we send an object. - def sendData(self, objectType, payload): - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - if objectType == 'pubkey': - shared.printLock.acquire() - print 'sending pubkey' - shared.printLock.release() - headerData += 'pubkey\x00\x00\x00\x00\x00\x00' - elif objectType == 'getpubkey' or objectType == 'pubkeyrequest': - shared.printLock.acquire() - print 'sending getpubkey' - shared.printLock.release() - headerData += 'getpubkey\x00\x00\x00' - elif objectType == 'msg': - shared.printLock.acquire() - print 'sending msg' - shared.printLock.release() - headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' - elif objectType == 'broadcast': - shared.printLock.acquire() - print 'sending broadcast' - shared.printLock.release() - headerData += 'broadcast\x00\x00\x00' - else: - sys.stderr.write( - 'Error: sendData has been asked to send a strange objectType: %s\n' % str(objectType)) - return - headerData += pack('>L', len(payload)) # payload length. - headerData += hashlib.sha512(payload).digest()[:4] - try: - self.sock.sendall(headerData + payload) - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - # Send an inv message with just one hash to all of our peers - def broadcastinv(self, hash): - shared.printLock.acquire() - print 'broadcasting inv with hash:', hash.encode('hex') - shared.printLock.release() - shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash)) - - # We have received an addr message. - def recaddr(self, data): - listOfAddressDetailsToBroadcastToPeers = [] - numberOfAddressesIncluded = 0 - numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint( - data[:10]) - - if verbose >= 1: - shared.printLock.acquire() - print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' - shared.printLock.release() - - 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': - shared.printLock.acquire() - print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) - shared.printLock.release() - continue - except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) - shared.printLock.release() - 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() - 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. - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( - recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) - shared.knownNodesLock.release() - needToWriteKnownNodesToDisk = True - hostDetails = ( - timeSomeoneElseReceivedMessageFromThisNode, - recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) - listOfAddressDetailsToBroadcastToPeers.append( - hostDetails) - 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. - if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( - PORT, timeSomeoneElseReceivedMessageFromThisNode) - shared.knownNodesLock.release() - 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.' - 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') - pickle.dump(shared.knownNodes, output) - output.close() - shared.knownNodesLock.release() - self.broadcastaddr( - listOfAddressDetailsToBroadcastToPeers) # no longer broadcast - shared.printLock.acquire() - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' - shared.printLock.release() - 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': - shared.printLock.acquire() - print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) - shared.printLock.release() - continue - except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) - shared.printLock.release() - 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) - shared.printLock.release() - 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() - shared.knownNodes[recaddrStream] = {} - shared.knownNodesLock.release() - 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. - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( - recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) - shared.knownNodesLock.release() - shared.printLock.acquire() - print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream - shared.printLock.release() - needToWriteKnownNodesToDisk = True - hostDetails = ( - timeSomeoneElseReceivedMessageFromThisNode, - recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) - listOfAddressDetailsToBroadcastToPeers.append( - hostDetails) - 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. - if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( - PORT, timeSomeoneElseReceivedMessageFromThisNode) - shared.knownNodesLock.release() - 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.' - 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') - pickle.dump(shared.knownNodes, output) - output.close() - shared.knownNodesLock.release() - self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) - shared.printLock.acquire() - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' - shared.printLock.release() - - # Function runs when we want to broadcast an addr message to all of our - # peers. Runs when we learn of nodes that we didn't previously know about - # and want to share them with our peers. - def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers): - numberOfAddressesInAddrMessage = len( - listOfAddressDetailsToBroadcastToPeers) - payload = '' - for hostDetails in listOfAddressDetailsToBroadcastToPeers: - timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails - payload += pack( - '>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time - payload += pack('>I', streamNumber) - payload += pack( - '>q', services) # service bit flags offered by this node - payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ - socket.inet_aton(host) - payload += pack('>H', port) # remote port - - payload = encodeVarint(numberOfAddressesInAddrMessage) + payload - datatosend = '\xE9\xBE\xB4\xD9addr\x00\x00\x00\x00\x00\x00\x00\x00' - datatosend = datatosend + pack('>L', len(payload)) # payload length - datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] - datatosend = datatosend + payload - - if verbose >= 1: - shared.printLock.acquire() - print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' - shared.printLock.release() - shared.broadcastToSendDataQueues(( - self.streamNumber, 'sendaddr', datatosend)) - - # Send a big addr message to our peer - def sendaddr(self): - addrsInMyStream = {} - addrsInChildStreamLeft = {} - addrsInChildStreamRight = {} - # 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. - shared.knownNodesLock.acquire() - if len(shared.knownNodes[self.streamNumber]) > 0: - for i in range(500): - random.seed() - HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) - if helper_generic.isHostInPrivateIPRange(HOST): - continue - addrsInMyStream[HOST] = shared.knownNodes[ - self.streamNumber][HOST] - if len(shared.knownNodes[self.streamNumber * 2]) > 0: - for i in range(250): - random.seed() - HOST, = random.sample(shared.knownNodes[ - self.streamNumber * 2], 1) - if helper_generic.isHostInPrivateIPRange(HOST): - continue - addrsInChildStreamLeft[HOST] = shared.knownNodes[ - self.streamNumber * 2][HOST] - if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0: - for i in range(250): - random.seed() - HOST, = random.sample(shared.knownNodes[ - (self.streamNumber * 2) + 1], 1) - if helper_generic.isHostInPrivateIPRange(HOST): - continue - addrsInChildStreamRight[HOST] = shared.knownNodes[ - (self.streamNumber * 2) + 1][HOST] - shared.knownNodesLock.release() - numberOfAddressesInAddrMessage = 0 - payload = '' - # print 'addrsInMyStream.items()', addrsInMyStream.items() - for HOST, value in addrsInMyStream.items(): - PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. - numberOfAddressesInAddrMessage += 1 - payload += pack( - '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time - payload += pack('>I', self.streamNumber) - payload += pack( - '>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 - for HOST, value in addrsInChildStreamLeft.items(): - PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. - numberOfAddressesInAddrMessage += 1 - payload += pack( - '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time - payload += pack('>I', self.streamNumber * 2) - payload += pack( - '>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 - for HOST, value in addrsInChildStreamRight.items(): - PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. - numberOfAddressesInAddrMessage += 1 - payload += pack( - '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time - payload += pack('>I', (self.streamNumber * 2) + 1) - payload += pack( - '>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 = 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: - self.sock.sendall(datatosend) - if verbose >= 1: - shared.printLock.acquire() - print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' - shared.printLock.release() - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - # We have received a version message - def recversion(self, data): - if len(data) < 83: - # This version message is unreasonably short. Forget it. - return - elif not self.verackSent: - self.remoteProtocolVersion, = unpack('>L', data[:4]) - if self.remoteProtocolVersion <= 1: - shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closing connection to old protocol version 1 node: ', self.HOST - shared.printLock.release() - return - # print 'remoteProtocolVersion', self.remoteProtocolVersion - self.myExternalIP = socket.inet_ntoa(data[40:44]) - # print 'myExternalIP', self.myExternalIP - self.remoteNodeIncomingPort, = unpack('>H', data[70:72]) - # print 'remoteNodeIncomingPort', self.remoteNodeIncomingPort - useragentLength, lengthOfUseragentVarint = decodeVarint( - data[80:84]) - readPosition = 80 + lengthOfUseragentVarint - useragent = data[readPosition:readPosition + useragentLength] - readPosition += useragentLength - numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint( - data[readPosition:]) - readPosition += lengthOfNumberOfStreamsInVersionMessage - self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint( - data[readPosition:]) - shared.printLock.acquire() - print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber - shared.printLock.release() - if self.streamNumber != 1: - shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.' - shared.printLock.release() - 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. - # If this was an incoming connection, then the sendData thread - # doesn't know the stream. We have to set it. - if not self.initiatedConnection: - shared.broadcastToSendDataQueues(( - 0, 'setStreamNumber', (self.HOST, self.streamNumber))) - if data[72:80] == eightBytesOfRandomDataUsedToDetectConnectionsToSelf: - shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closing connection to myself: ', self.HOST - shared.printLock.release() - return - shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', ( - self.HOST, self.remoteProtocolVersion))) - - shared.knownNodesLock.acquire() - shared.knownNodes[self.streamNumber][self.HOST] = ( - self.remoteNodeIncomingPort, int(time.time())) - output = open(shared.appdata + 'knownnodes.dat', 'wb') - pickle.dump(shared.knownNodes, output) - output.close() - shared.knownNodesLock.release() - - self.sendverack() - if self.initiatedConnection == False: - self.sendversion() - - # Sends a version message - def sendversion(self): - shared.printLock.acquire() - print 'Sending version message' - shared.printLock.release() - try: - self.sock.sendall(assembleVersionMessage( - self.HOST, self.PORT, self.streamNumber)) - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - - # Sends a verack message - def sendverack(self): - shared.printLock.acquire() - print 'Sending verack' - shared.printLock.release() - 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') - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - # cf - # 83 - # e1 - # 35 - self.verackSent = True - if self.verackReceived: - self.connectionFullyEstablished() - - -# Every connection to a peer has a sendDataThread (and also a -# receiveDataThread). -class sendDataThread(threading.Thread): - - def __init__(self): - threading.Thread.__init__(self) - self.mailbox = Queue.Queue() - shared.sendDataQueues.append(self.mailbox) - shared.printLock.acquire() - print 'The length of sendDataQueues at sendDataThread init is:', len(shared.sendDataQueues) - shared.printLock.release() - self.data = '' - - def setup( - self, - sock, - HOST, - PORT, - streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware): - self.sock = sock - self.HOST = HOST - self.PORT = PORT - self.streamNumber = streamNumber - self.remoteProtocolVersion = - \ - 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 - shared.printLock.acquire() - print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber - shared.printLock.release() - - def sendVersionMessage(self): - datatosend = assembleVersionMessage( - self.HOST, self.PORT, self.streamNumber) # the IP and port of the remote host, and my streamNumber. - - shared.printLock.acquire() - print 'Sending version packet: ', repr(datatosend) - shared.printLock.release() - try: - self.sock.sendall(datatosend) - except Exception as err: - # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() - self.versionSent = 1 - - def run(self): - while True: - deststream, command, data = self.mailbox.get() - # shared.printLock.acquire() - # print 'sendDataThread, destream:', deststream, ', Command:', command, ', ID:',id(self), ', HOST:', self.HOST - # shared.printLock.release() - - if deststream == self.streamNumber or deststream == 0: - if command == 'shutdown': - if data == self.HOST or data == 'all': - shared.printLock.acquire() - print 'sendDataThread (associated with', self.HOST, ') ID:', id(self), 'shutting down now.' - shared.printLock.release() - try: - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - except: - pass - shared.sendDataQueues.remove(self.mailbox) - shared.printLock.acquire() - print 'len of sendDataQueues', len(shared.sendDataQueues) - shared.printLock.release() - 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: - elif command == 'setStreamNumber': - hostInMessage, specifiedStreamNumber = data - if hostInMessage == self.HOST: - shared.printLock.acquire() - print 'setting the stream number in the sendData thread (ID:', id(self), ') to', specifiedStreamNumber - shared.printLock.release() - self.streamNumber = specifiedStreamNumber - elif command == 'setRemoteProtocolVersion': - hostInMessage, specifiedRemoteProtocolVersion = data - if hostInMessage == self.HOST: - shared.printLock.acquire() - print 'setting the remote node\'s protocol version in the sendData thread (ID:', id(self), ') to', specifiedRemoteProtocolVersion - shared.printLock.release() - self.remoteProtocolVersion = specifiedRemoteProtocolVersion - elif command == 'sendaddr': - 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. - random.seed() - time.sleep(random.randrange(0, 10)) - self.sock.sendall(data) - self.lastTimeISentData = int(time.time()) - except: - print 'self.sock.sendall failed' - try: - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - except: - pass - shared.sendDataQueues.remove(self.mailbox) - print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST - break - elif command == 'sendinv': - if data not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: - payload = '\x01' + data - 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()) - except: - print 'self.sock.sendall failed' - try: - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - except: - pass - shared.sendDataQueues.remove(self.mailbox) - print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST - break - elif command == 'pong': - if self.lastTimeISentData < (int(time.time()) - 298): - # Send out a pong message to keep the connection alive. - shared.printLock.acquire() - print 'Sending pong to', self.HOST, 'to keep connection alive.' - shared.printLock.release() - 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.lastTimeISentData = int(time.time()) - except: - print 'send pong failed' - try: - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - except: - pass - shared.sendDataQueues.remove(self.mailbox) - print 'sendDataThread thread', self, 'ending now. Was connected to', self.HOST - break - else: - shared.printLock.acquire() - print 'sendDataThread ID:', id(self), 'ignoring command', command, 'because the thread is not in stream', deststream - shared.printLock.release() - - def isInSqlInventory(hash): t = (hash,) shared.sqlLock.acquire() diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py new file mode 100644 index 00000000..2b7b0288 --- /dev/null +++ b/src/class_receiveDataThread.py @@ -0,0 +1,2028 @@ +import time +import threading +import shared + +# This thread is created either by the synSenderThread(for outgoing +# connections) or the singleListenerThread(for incoming connectiosn). + + +class receiveDataThread(threading.Thread): + + def __init__(self): + threading.Thread.__init__(self) + self.data = '' + self.verackSent = False + self.verackReceived = False + + def setup( + self, + sock, + HOST, + port, + streamNumber, + objectsOfWhichThisRemoteNodeIsAlreadyAware): + self.sock = sock + self.HOST = HOST + self.PORT = port + self.streamNumber = streamNumber + self.payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header + 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. + 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. + self.initiatedConnection = False + else: + self.initiatedConnection = True + 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.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware + + def run(self): + shared.printLock.acquire() + print 'ID of the receiveDataThread is', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) + shared.printLock.release() + while True: + try: + self.data += self.sock.recv(4096) + except socket.timeout: + shared.printLock.acquire() + print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' + shared.printLock.release() + break + except Exception as err: + shared.printLock.acquire() + print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err + shared.printLock.release() + break + # print 'Received', repr(self.data) + if self.data == "": + shared.printLock.acquire() + print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' + shared.printLock.release() + break + else: + self.processData() + + try: + del selfInitiatedConnections[self.streamNumber][self] + shared.printLock.acquire() + print 'removed self (a receiveDataThread) from selfInitiatedConnections' + shared.printLock.release() + except: + pass + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) + try: + del shared.connectedHostsList[self.HOST] + except Exception as err: + shared.printLock.acquire() + print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err + shared.printLock.release() + try: + del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ + self.HOST] + except: + pass + shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) + shared.printLock.acquire() + print 'The size of the connectedHostsList is now:', len(shared.connectedHostsList) + shared.printLock.release() + + def processData(self): + global verbose + # if verbose >= 3: + # shared.printLock.acquire() + # print 'self.data is currently ', repr(self.data) + # shared.printLock.release() + if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length + return + if self.data[0:4] != '\xe9\xbe\xb4\xd9': + if verbose >= 1: + shared.printLock.acquire() + print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) + shared.printLock.release() + self.data = "" + return + self.payloadLength, = unpack('>L', self.data[16:20]) + if len(self.data) < self.payloadLength + 24: # check if the whole message has arrived yet. + return + if self.data[20:24] != hashlib.sha512(self.data[24:self.payloadLength + 24]).digest()[0:4]: # test the checksum in the message. If it is correct... + print 'Checksum incorrect. Clearing this message.' + self.data = self.data[self.payloadLength + 24:] + self.processData() + 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. + 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.knownNodes[self.streamNumber][ + self.HOST] = (self.PORT, int(time.time())) + shared.knownNodesLock.release() + if self.payloadLength <= 180000000: # If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.) + remoteCommand = self.data[4:16] + shared.printLock.acquire() + print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.HOST + shared.printLock.release() + if remoteCommand == 'version\x00\x00\x00\x00\x00': + self.recversion(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'verack\x00\x00\x00\x00\x00\x00': + self.recverack() + elif remoteCommand == 'addr\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recaddr(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'getpubkey\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recgetpubkey(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'pubkey\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recpubkey(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recinv(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'getdata\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recgetdata(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recmsg(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'broadcast\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.recbroadcast(self.data[24:self.payloadLength + 24]) + elif remoteCommand == 'ping\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + self.sendpong() + elif remoteCommand == 'pong\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + pass + elif remoteCommand == 'alert\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: + pass + + self.data = self.data[ + self.payloadLength + 24:] # take this message out and then process the next message + if self.data == '': + while len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: + random.seed() + objectHash, = random.sample( + self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1) + if objectHash in shared.inventory: + shared.printLock.acquire() + print 'Inventory (in memory) already has object listed in inv message.' + shared.printLock.release() + del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ + objectHash] + elif isInSqlInventory(objectHash): + if verbose >= 3: + shared.printLock.acquire() + print 'Inventory (SQL on disk) already has object listed in inv message.' + shared.printLock.release() + del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ + objectHash] + else: + self.sendgetdata(objectHash) + del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ + objectHash] # It is possible that the remote node doesn't respond with the object. In that case, we'll very likely get it from someone else anyway. + if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0: + shared.printLock.acquire() + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + shared.printLock.release() + 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. + except: + pass + break + if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0: + shared.printLock.acquire() + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + shared.printLock.release() + 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. + except: + pass + if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: + shared.printLock.acquire() + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + 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. + if len(self.ackDataThatWeHaveYetToSend) > 0: + self.data = self.ackDataThatWeHaveYetToSend.pop() + self.processData() + + def isProofOfWorkSufficient( + self, + data, + nonceTrialsPerByte=0, + payloadLengthExtraBytes=0): + if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: + nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte + if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: + payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes + POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[ + :8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8]) + # print 'POW:', POW + return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte)) + + def sendpong(self): + print 'Sending pong' + 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') + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + def recverack(self): + print 'verack received' + self.verackReceived = True + if self.verackSent: + # We have thus both sent and received a verack. + self.connectionFullyEstablished() + + def connectionFullyEstablished(self): + self.connectionIsOrWasFullyEstablished = True + if not self.initiatedConnection: + 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. + shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) + remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[ + self.streamNumber][self.HOST] + shared.printLock.acquire() + print 'Connection fully established with', self.HOST, remoteNodeIncomingPort + 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.' + shared.printLock.release() + self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.HOST, + remoteNodeIncomingPort)]) # This lets all of our peers know about this new node. + self.sendaddr() # This is one large addr message to this one peer. + if not self.initiatedConnection and len(shared.connectedHostsList) > 200: + shared.printLock.acquire() + print 'We are connected to too many people. Closing connection.' + shared.printLock.release() + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) + return + self.sendBigInv() + + def sendBigInv(self): + shared.sqlLock.acquire() + # Select all hashes which are younger than two days old and in this + # stream. + t = (int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers, int( + time.time()) - lengthOfTimeToHoldOnToAllPubkeys, self.streamNumber) + shared.sqlSubmitQueue.put( + '''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + bigInvList = {} + for row in queryreturn: + hash, = row + if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: + bigInvList[hash] = 0 + # 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.objectsOfWhichThisRemoteNodeIsAlreadyAware: + objectType, streamNumber, payload, receivedTime = storedValue + if streamNumber == self.streamNumber and receivedTime > int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers: + bigInvList[hash] = 0 + numberOfObjectsInInvMessage = 0 + payload = '' + # Now let us start appending all of these hashes together. They will be + # sent out in a big inv message to our new peer. + for hash, storedValue in bigInvList.items(): + payload += hash + 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. + self.sendinvMessageToJustThisOnePeer( + numberOfObjectsInInvMessage, payload) + payload = '' + numberOfObjectsInInvMessage = 0 + if numberOfObjectsInInvMessage > 0: + self.sendinvMessageToJustThisOnePeer( + numberOfObjectsInInvMessage, payload) + + # Self explanatory. Notice that there is also a broadcastinv function for + # broadcasting invs to everyone in our stream. + def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): + payload = encodeVarint(numberOfObjects) + payload + 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] + shared.printLock.acquire() + print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' + shared.printLock.release() + try: + self.sock.sendall(headerData + payload) + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + # We have received a broadcast message + def recbroadcast(self, data): + self.messageProcessingStartTime = time.time() + # First we must check to make sure the proof of work is sufficient. + if not self.isProofOfWorkSufficient(data): + print 'Proof of work in broadcast message insufficient.' + return + readPosition = 8 # bypass the nonce + embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) + + # This section is used for the transition from 32 bit time to 64 bit + # time in the protocol. + if embeddedTime == 0: + embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + + if embeddedTime > (int(time.time()) + 10800): # prevent funny business + print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.' + return + if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): + print 'The embedded time in this broadcast message is too old. Ignoring message.' + return + if len(data) < 180: + print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.' + return + # Let us check to make sure the stream number is correct (thus + # preventing an individual from sending broadcasts out on the wrong + # streams or all streams). + broadcastVersion, broadcastVersionLength = decodeVarint( + data[readPosition:readPosition + 10]) + if broadcastVersion >= 2: + streamNumber, streamNumberLength = decodeVarint(data[ + readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10]) + if streamNumber != self.streamNumber: + print 'The stream number encoded in this broadcast message (' + str(streamNumber) + ') does not match the stream number on which it was received. Ignoring it.' + return + + shared.inventoryLock.acquire() + self.inventoryHash = calculateInventoryHash(data) + if self.inventoryHash in shared.inventory: + print 'We have already received this broadcast object. Ignoring.' + shared.inventoryLock.release() + return + elif isInSqlInventory(self.inventoryHash): + print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.' + shared.inventoryLock.release() + return + # It is valid so far. Let's let our peers know about it. + objectType = 'broadcast' + shared.inventory[self.inventoryHash] = ( + objectType, self.streamNumber, data, embeddedTime) + shared.inventoryLock.release() + self.broadcastinv(self.inventoryHash) + 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. + + # 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. + if len(data) > 100000000: # Size is greater than 100 megabytes + lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. + elif len(data) > 10000000: # Between 100 and 10 megabytes + lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds. + elif len(data) > 1000000: # Between 10 and 1 megabyte + lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds. + else: # Less than 1 megabyte + lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. + + sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ + (time.time() - self.messageProcessingStartTime) + if sleepTime > 0: + shared.printLock.acquire() + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + shared.printLock.release() + time.sleep(sleepTime) + shared.printLock.acquire() + print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' + shared.printLock.release() + + # A broadcast message has a valid time and POW and requires processing. + # The recbroadcast function calls this one. + def processbroadcast(self, readPosition, data): + broadcastVersion, broadcastVersionLength = decodeVarint( + data[readPosition:readPosition + 9]) + readPosition += broadcastVersionLength + if broadcastVersion < 1 or broadcastVersion > 2: + 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 + if broadcastVersion == 1: + beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table + sendersAddressVersion, sendersAddressVersionLength = decodeVarint( + data[readPosition:readPosition + 9]) + if sendersAddressVersion <= 1 or sendersAddressVersion >= 3: + # Cannot decode senderAddressVersion higher than 2. Assuming + # the sender isn\'t being silly, you should upgrade Bitmessage + # because this message shall be ignored. + return + readPosition += sendersAddressVersionLength + if sendersAddressVersion == 2: + sendersStream, sendersStreamLength = decodeVarint( + data[readPosition:readPosition + 9]) + readPosition += sendersStreamLength + behaviorBitfield = data[readPosition:readPosition + 4] + readPosition += 4 + sendersPubSigningKey = '\x04' + \ + data[readPosition:readPosition + 64] + readPosition += 64 + sendersPubEncryptionKey = '\x04' + \ + data[readPosition:readPosition + 64] + readPosition += 64 + endOfPubkeyPosition = readPosition + sendersHash = data[readPosition:readPosition + 20] + if sendersHash not in shared.broadcastSendersForWhichImWatching: + # Display timing data + shared.printLock.acquire() + print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime + shared.printLock.release() + return + # At this point, this message claims to be from sendersHash and + # we are interested in it. We still have to hash the public key + # to make sure it is truly the key that matches the hash, and + # also check the signiture. + readPosition += 20 + + sha = hashlib.new('sha512') + sha.update(sendersPubSigningKey + sendersPubEncryptionKey) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) + if ripe.digest() != sendersHash: + # The sender of this message lied. + return + messageEncodingType, messageEncodingTypeLength = decodeVarint( + data[readPosition:readPosition + 9]) + if messageEncodingType == 0: + return + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint( + data[readPosition:readPosition + 9]) + readPosition += messageLengthLength + message = data[readPosition:readPosition + messageLength] + readPosition += messageLength + readPositionAtBottomOfMessage = readPosition + signatureLength, signatureLengthLength = decodeVarint( + data[readPosition:readPosition + 9]) + readPosition += signatureLengthLength + signature = data[readPosition:readPosition + signatureLength] + try: + if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')): + print 'ECDSA verify failed' + return + print 'ECDSA verify passed' + except Exception as err: + print 'ECDSA verify failed', err + return + # verify passed + + # Let's store the public key in case we want to reply to this person. + # We don't have the correct nonce or time (which would let us + # send out a pubkey message) so we'll just fill it with 1's. We + # won't be able to send this pubkey to others (without doing + # the proof of work ourselves, which this program is programmed + # to not do.) + t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[ + beginningOfPubkeyPosition:endOfPubkeyPosition], int(time.time()), 'yes') + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + # shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest()))) + # This will check to see whether we happen to be awaiting this + # pubkey in order to send a message. If we are, it will do the + # POW and send it. + self.possibleNewPubkey(ripe.digest()) + + fromAddress = encodeAddress( + sendersAddressVersion, sendersStream, ripe.digest()) + shared.printLock.acquire() + print 'fromAddress:', fromAddress + shared.printLock.release() + if messageEncodingType == 2: + bodyPositionIndex = string.find(message, '\nBody:') + if bodyPositionIndex > 1: + subject = message[8:bodyPositionIndex] + body = message[bodyPositionIndex + 6:] + else: + subject = '' + body = message + elif messageEncodingType == 1: + body = message + subject = '' + elif messageEncodingType == 0: + print 'messageEncodingType == 0. Doing nothing with the message.' + else: + body = 'Unknown encoding type.\n\n' + repr(message) + subject = '' + + toAddress = '[Broadcast subscribers]' + if messageEncodingType != 0: + + t = (self.inventoryHash, toAddress, fromAddress, subject, int( + time.time()), body, 'inbox', messageEncodingType, 0) + helper_inbox.insert(t) + + shared.UISignalQueue.put(('displayNewInboxMessage', ( + self.inventoryHash, toAddress, fromAddress, subject, body))) + + # If we are behaving as an API then we might need to run an + # outside command to let some program know that a new + # message has arrived. + if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): + try: + apiNotifyPath = shared.config.get( + 'bitmessagesettings', 'apinotifypath') + except: + apiNotifyPath = '' + if apiNotifyPath != '': + call([apiNotifyPath, "newBroadcast"]) + + # Display timing data + shared.printLock.acquire() + print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime + shared.printLock.release() + if broadcastVersion == 2: + cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += cleartextStreamNumberLength + initialDecryptionSuccessful = False + for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items(): + try: + decryptedData = cryptorObject.decrypt(data[readPosition:]) + toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key. + initialDecryptionSuccessful = True + print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') + break + except Exception as err: + pass + # print 'cryptorObject.decrypt Exception:', err + if not initialDecryptionSuccessful: + # This is not a broadcast I am interested in. + shared.printLock.acquire() + print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.' + shared.printLock.release() + return + # At this point this is a broadcast I have decrypted and thus am + # interested in. + signedBroadcastVersion, readPosition = decodeVarint( + decryptedData[:10]) + beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table + sendersAddressVersion, sendersAddressVersionLength = decodeVarint( + decryptedData[readPosition:readPosition + 9]) + if sendersAddressVersion < 2 or sendersAddressVersion > 3: + print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.' + return + readPosition += sendersAddressVersionLength + sendersStream, sendersStreamLength = decodeVarint( + decryptedData[readPosition:readPosition + 9]) + if sendersStream != cleartextStreamNumber: + print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.' + return + readPosition += sendersStreamLength + behaviorBitfield = decryptedData[readPosition:readPosition + 4] + readPosition += 4 + sendersPubSigningKey = '\x04' + \ + decryptedData[readPosition:readPosition + 64] + readPosition += 64 + sendersPubEncryptionKey = '\x04' + \ + decryptedData[readPosition:readPosition + 64] + readPosition += 64 + if sendersAddressVersion >= 3: + requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += varintLength + print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte + requiredPayloadLengthExtraBytes, varintLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += varintLength + print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes + endOfPubkeyPosition = readPosition + + sha = hashlib.new('sha512') + sha.update(sendersPubSigningKey + sendersPubEncryptionKey) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) + + if toRipe != ripe.digest(): + print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.' + return + messageEncodingType, messageEncodingTypeLength = decodeVarint( + decryptedData[readPosition:readPosition + 9]) + if messageEncodingType == 0: + return + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint( + decryptedData[readPosition:readPosition + 9]) + readPosition += messageLengthLength + message = decryptedData[readPosition:readPosition + messageLength] + readPosition += messageLength + readPositionAtBottomOfMessage = readPosition + signatureLength, signatureLengthLength = decodeVarint( + decryptedData[readPosition:readPosition + 9]) + readPosition += signatureLengthLength + signature = decryptedData[ + readPosition:readPosition + signatureLength] + try: + if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')): + print 'ECDSA verify failed' + return + print 'ECDSA verify passed' + except Exception as err: + print 'ECDSA verify failed', err + return + # verify passed + + # Let's store the public key in case we want to reply to this + # person. + 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.sqlSubmitQueue.put( + '''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + # shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest()))) + # This will check to see whether we happen to be awaiting this + # pubkey in order to send a message. If we are, it will do the POW + # and send it. + self.possibleNewPubkey(ripe.digest()) + + fromAddress = encodeAddress( + sendersAddressVersion, sendersStream, ripe.digest()) + shared.printLock.acquire() + print 'fromAddress:', fromAddress + shared.printLock.release() + if messageEncodingType == 2: + bodyPositionIndex = string.find(message, '\nBody:') + if bodyPositionIndex > 1: + subject = message[8:bodyPositionIndex] + body = message[bodyPositionIndex + 6:] + else: + subject = '' + body = message + elif messageEncodingType == 1: + body = message + subject = '' + elif messageEncodingType == 0: + print 'messageEncodingType == 0. Doing nothing with the message.' + else: + body = 'Unknown encoding type.\n\n' + repr(message) + subject = '' + + toAddress = '[Broadcast subscribers]' + if messageEncodingType != 0: + + t = (self.inventoryHash, toAddress, fromAddress, subject, int( + time.time()), body, 'inbox', messageEncodingType, 0) + helper_inbox.insert(t) + + shared.UISignalQueue.put(('displayNewInboxMessage', ( + self.inventoryHash, toAddress, fromAddress, subject, body))) + + # If we are behaving as an API then we might need to run an + # outside command to let some program know that a new message + # has arrived. + if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): + try: + apiNotifyPath = shared.config.get( + 'bitmessagesettings', 'apinotifypath') + except: + apiNotifyPath = '' + if apiNotifyPath != '': + call([apiNotifyPath, "newBroadcast"]) + + # Display timing data + shared.printLock.acquire() + print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime + shared.printLock.release() + + # We have received a msg message. + def recmsg(self, data): + self.messageProcessingStartTime = time.time() + # First we must check to make sure the proof of work is sufficient. + if not self.isProofOfWorkSufficient(data): + print 'Proof of work in msg message insufficient.' + return + + readPosition = 8 + embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) + + # This section is used for the transition from 32 bit time to 64 bit + # time in the protocol. + if embeddedTime == 0: + embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + + if embeddedTime > int(time.time()) + 10800: + print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime + return + if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: + print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime + return + streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint( + data[readPosition:readPosition + 9]) + if streamNumberAsClaimedByMsg != self.streamNumber: + print 'The stream number encoded in this msg (' + str(streamNumberAsClaimedByMsg) + ') message does not match the stream number on which it was received. Ignoring it.' + return + readPosition += streamNumberAsClaimedByMsgLength + self.inventoryHash = calculateInventoryHash(data) + shared.inventoryLock.acquire() + if self.inventoryHash in shared.inventory: + print 'We have already received this msg message. Ignoring.' + shared.inventoryLock.release() + return + elif isInSqlInventory(self.inventoryHash): + print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.' + shared.inventoryLock.release() + return + # This msg message is valid. Let's let our peers know about it. + objectType = 'msg' + shared.inventory[self.inventoryHash] = ( + objectType, self.streamNumber, data, embeddedTime) + shared.inventoryLock.release() + self.broadcastinv(self.inventoryHash) + 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. + + # 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. + if len(data) > 100000000: # Size is greater than 100 megabytes + lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds. + elif len(data) > 10000000: # Between 100 and 10 megabytes + lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 10 MB message: 0.53 seconds. Actual length of time it takes in practice when processing a real message: 1.44 seconds. + elif len(data) > 1000000: # Between 10 and 1 megabyte + lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 1 MB message: 0.18 seconds. Actual length of time it takes in practice when processing a real message: 0.30 seconds. + 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. + + sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ + (time.time() - self.messageProcessingStartTime) + if sleepTime > 0: + shared.printLock.acquire() + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + shared.printLock.release() + time.sleep(sleepTime) + shared.printLock.acquire() + print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' + shared.printLock.release() + + # A msg message has a valid time and POW and requires processing. The + # recmsg function calls this one. + def processmsg(self, readPosition, encryptedData): + initialDecryptionSuccessful = False + # Let's check whether this is a message acknowledgement bound for us. + if encryptedData[readPosition:] in ackdataForWhichImWatching: + shared.printLock.acquire() + print 'This msg IS an acknowledgement bound for me.' + shared.printLock.release() + del ackdataForWhichImWatching[encryptedData[readPosition:]] + t = ('ackreceived', encryptedData[readPosition:]) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + 'UPDATE sent SET status=? WHERE ackdata=?') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( + strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) + return + else: + shared.printLock.acquire() + print 'This was NOT an acknowledgement bound for me.' + # print 'ackdataForWhichImWatching', ackdataForWhichImWatching + shared.printLock.release() + + # This is not an acknowledgement bound for me. See if it is a message + # bound for me by trying to decrypt it with my private keys. + for key, cryptorObject in shared.myECCryptorObjects.items(): + try: + decryptedData = cryptorObject.decrypt( + encryptedData[readPosition:]) + toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data. + initialDecryptionSuccessful = True + print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') + break + except Exception as err: + pass + # print 'cryptorObject.decrypt Exception:', err + if not initialDecryptionSuccessful: + # This is not a message bound for me. + shared.printLock.acquire() + print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.' + shared.printLock.release() + else: + # This is a message bound for me. + toAddress = shared.myAddressesByHash[ + toRipe] # Look up my address based on the RIPE hash. + readPosition = 0 + messageVersion, messageVersionLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += messageVersionLength + if messageVersion != 1: + print 'Cannot understand message versions other than one. Ignoring message.' + return + sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += sendersAddressVersionNumberLength + if sendersAddressVersionNumber == 0: + print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.' + return + if sendersAddressVersionNumber >= 4: + print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.' + return + if len(decryptedData) < 170: + print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.' + return + sendersStreamNumber, sendersStreamNumberLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + if sendersStreamNumber == 0: + print 'sender\'s stream number is 0. Ignoring message.' + return + readPosition += sendersStreamNumberLength + behaviorBitfield = decryptedData[readPosition:readPosition + 4] + readPosition += 4 + pubSigningKey = '\x04' + decryptedData[ + readPosition:readPosition + 64] + readPosition += 64 + pubEncryptionKey = '\x04' + decryptedData[ + readPosition:readPosition + 64] + readPosition += 64 + if sendersAddressVersionNumber >= 3: + requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += varintLength + print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte + requiredPayloadLengthExtraBytes, varintLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += varintLength + print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes + endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use. + if toRipe != decryptedData[readPosition:readPosition + 20]: + shared.printLock.acquire() + print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.' + print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html' + print 'your toRipe:', toRipe.encode('hex') + print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex') + shared.printLock.release() + return + readPosition += 20 + messageEncodingType, messageEncodingTypeLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += messageLengthLength + message = decryptedData[readPosition:readPosition + messageLength] + # print 'First 150 characters of message:', repr(message[:150]) + readPosition += messageLength + ackLength, ackLengthLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += ackLengthLength + ackData = decryptedData[readPosition:readPosition + ackLength] + readPosition += ackLength + positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature + signatureLength, signatureLengthLength = decodeVarint( + decryptedData[readPosition:readPosition + 10]) + readPosition += signatureLengthLength + signature = decryptedData[ + readPosition:readPosition + signatureLength] + try: + if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')): + print 'ECDSA verify failed' + return + print 'ECDSA verify passed' + except Exception as err: + print 'ECDSA verify failed', err + return + shared.printLock.acquire() + print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' + shared.printLock.release() + # calculate the fromRipe. + sha = hashlib.new('sha512') + sha.update(pubSigningKey + pubEncryptionKey) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) + # Let's store the public key in case we want to reply to this + # person. + t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[ + messageVersionLength:endOfThePublicKeyPosition], int(time.time()), 'yes') + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + # shared.workerQueue.put(('newpubkey',(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()))) + # This will check to see whether we happen to be awaiting this + # pubkey in order to send a message. If we are, it will do the POW + # and send it. + self.possibleNewPubkey(ripe.digest()) + fromAddress = encodeAddress( + sendersAddressVersionNumber, sendersStreamNumber, ripe.digest()) + # If this message is bound for one of my version 3 addresses (or + # higher), then we must check to make sure it meets our demanded + # proof of work requirement. + if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher: + if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person: + requiredNonceTrialsPerByte = shared.config.getint( + toAddress, 'noncetrialsperbyte') + requiredPayloadLengthExtraBytes = shared.config.getint( + toAddress, 'payloadlengthextrabytes') + if not self.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes): + print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.' + return + blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists. + if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist + t = (fromAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT label FROM blacklist where address=? and enabled='1' ''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn != []: + shared.printLock.acquire() + print 'Message ignored because address is in blacklist.' + shared.printLock.release() + blockMessage = True + else: # We're using a whitelist + t = (fromAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT label FROM whitelist where address=? and enabled='1' ''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn == []: + print 'Message ignored because address not in whitelist.' + blockMessage = True + if not blockMessage: + print 'fromAddress:', fromAddress + print 'First 150 characters of message:', repr(message[:150]) + + toLabel = shared.config.get(toAddress, 'label') + if toLabel == '': + toLabel = toAddress + + if messageEncodingType == 2: + bodyPositionIndex = string.find(message, '\nBody:') + if bodyPositionIndex > 1: + subject = message[8:bodyPositionIndex] + subject = subject[ + :500] # Only save and show the first 500 characters of the subject. Any more is probably an attak. + body = message[bodyPositionIndex + 6:] + else: + subject = '' + body = message + elif messageEncodingType == 1: + body = message + subject = '' + elif messageEncodingType == 0: + print 'messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.' + else: + body = 'Unknown encoding type.\n\n' + repr(message) + subject = '' + if messageEncodingType != 0: + t = (self.inventoryHash, toAddress, fromAddress, subject, int( + time.time()), body, 'inbox', messageEncodingType, 0) + helper_inbox.insert(t) + + shared.UISignalQueue.put(('displayNewInboxMessage', ( + self.inventoryHash, toAddress, fromAddress, subject, body))) + + # If we are behaving as an API then we might need to run an + # outside command to let some program know that a new message + # has arrived. + if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): + try: + apiNotifyPath = shared.config.get( + 'bitmessagesettings', 'apinotifypath') + except: + apiNotifyPath = '' + if apiNotifyPath != '': + call([apiNotifyPath, "newMessage"]) + + # Let us now check and see whether our receiving address is + # behaving as a mailing list + if shared.safeConfigGetBoolean(toAddress, 'mailinglist'): + try: + mailingListName = shared.config.get( + toAddress, 'mailinglistname') + except: + mailingListName = '' + # Let us send out this message as a broadcast + subject = self.addMailingListNameToSubject( + subject, mailingListName) + # Let us now send this message out as a broadcast + message = 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. + ackdata = OpenSSL.rand( + 32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating. + toAddress = '[Broadcast subscribers]' + ripe = '' + + t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int( + time.time()), 'broadcastqueued', 1, 1, 'sent', 2) + helper_sent.insert(t) + + shared.UISignalQueue.put(('displayNewSentMessage', ( + toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata))) + shared.workerQueue.put(('sendbroadcast', '')) + + if self.isAckDataValid(ackData): + print 'ackData is valid. Will process it.' + self.ackDataThatWeHaveYetToSend.append( + ackData) # When we have processed all data, the processData function will pop the ackData out and process it as if it is a message received from our peer. + # Display timing data + timeRequiredToAttemptToDecryptMessage = time.time( + ) - self.messageProcessingStartTime + successfullyDecryptMessageTimings.append( + timeRequiredToAttemptToDecryptMessage) + sum = 0 + for item in successfullyDecryptMessageTimings: + sum += item + shared.printLock.acquire() + print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage + print 'Average time for all message decryption successes since startup:', sum / len(successfullyDecryptMessageTimings) + shared.printLock.release() + + def isAckDataValid(self, ackData): + if len(ackData) < 24: + print 'The length of ackData is unreasonably short. Not sending ackData.' + return False + if ackData[0:4] != '\xe9\xbe\xb4\xd9': + print 'Ackdata magic bytes were wrong. Not sending ackData.' + return False + ackDataPayloadLength, = unpack('>L', ackData[16:20]) + if len(ackData) - 24 != ackDataPayloadLength: + print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.' + return False + if ackData[4:16] != 'getpubkey\x00\x00\x00' and ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'broadcast\x00\x00\x00': + return False + return True + + def addMailingListNameToSubject(self, subject, mailingListName): + subject = subject.strip() + if subject[:3] == 'Re:' or subject[:3] == 'RE:': + subject = subject[3:].strip() + if '[' + mailingListName + ']' in subject: + return subject + else: + return '[' + mailingListName + '] ' + subject + + def possibleNewPubkey(self, toRipe): + if toRipe in neededPubkeys: + print 'We have been awaiting the arrival of this pubkey.' + del neededPubkeys[toRipe] + t = (toRipe,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + shared.workerQueue.put(('sendmessage', '')) + else: + shared.printLock.acquire() + print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') + shared.printLock.release() + + # We have received a pubkey + def recpubkey(self, data): + self.pubkeyProcessingStartTime = time.time() + if len(data) < 146 or len(data) > 600: # sanity check + return + # We must check to make sure the proof of work is sufficient. + if not self.isProofOfWorkSufficient(data): + print 'Proof of work in pubkey message insufficient.' + return + + readPosition = 8 # for the nonce + embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) + + # This section is used for the transition from 32 bit time to 64 bit + # time in the protocol. + if embeddedTime == 0: + embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + + if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys: + shared.printLock.acquire() + print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime + shared.printLock.release() + return + if embeddedTime > int(time.time()) + 10800: + shared.printLock.acquire() + print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.' + shared.printLock.release() + return + addressVersion, varintLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += varintLength + streamNumber, varintLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += varintLength + if self.streamNumber != streamNumber: + print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.' + return + + inventoryHash = calculateInventoryHash(data) + shared.inventoryLock.acquire() + if inventoryHash in shared.inventory: + print 'We have already received this pubkey. Ignoring it.' + shared.inventoryLock.release() + return + elif isInSqlInventory(inventoryHash): + print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.' + shared.inventoryLock.release() + return + objectType = 'pubkey' + shared.inventory[inventoryHash] = ( + objectType, self.streamNumber, data, embeddedTime) + shared.inventoryLock.release() + self.broadcastinv(inventoryHash) + shared.UISignalQueue.put(( + 'incrementNumberOfPubkeysProcessed', 'no data')) + + self.processpubkey(data) + + lengthOfTimeWeShouldUseToProcessThisMessage = .2 + sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ + (time.time() - self.pubkeyProcessingStartTime) + if sleepTime > 0: + shared.printLock.acquire() + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + shared.printLock.release() + time.sleep(sleepTime) + shared.printLock.acquire() + print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.' + shared.printLock.release() + + def processpubkey(self, data): + readPosition = 8 # for the nonce + embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) + + # This section is used for the transition from 32 bit time to 64 bit + # time in the protocol. + if embeddedTime == 0: + embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + + addressVersion, varintLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += varintLength + streamNumber, varintLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += varintLength + if addressVersion == 0: + print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.' + return + if addressVersion >= 4 or addressVersion == 1: + shared.printLock.acquire() + print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.' + shared.printLock.release() + return + if addressVersion == 2: + if len(data) < 146: # sanity check. This is the minimum possible length. + print '(within processpubkey) payloadLength less than 146. Sanity check failed.' + return + bitfieldBehaviors = data[readPosition:readPosition + 4] + readPosition += 4 + publicSigningKey = data[readPosition:readPosition + 64] + # Is it possible for a public key to be invalid such that trying to + # encrypt or sign with it will cause an error? If it is, we should + # probably test these keys here. + readPosition += 64 + publicEncryptionKey = data[readPosition:readPosition + 64] + if len(publicEncryptionKey) < 64: + print 'publicEncryptionKey length less than 64. Sanity check failed.' + return + sha = hashlib.new('sha512') + sha.update( + '\x04' + publicSigningKey + '\x04' + publicEncryptionKey) + ripeHasher = hashlib.new('ripemd160') + ripeHasher.update(sha.digest()) + ripe = ripeHasher.digest() + + shared.printLock.acquire() + print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber + print 'ripe', ripe.encode('hex') + print 'publicSigningKey in hex:', publicSigningKey.encode('hex') + print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') + shared.printLock.release() + + t = (ripe,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn != []: # if this pubkey is already in our database and if we have used it personally: + print 'We HAVE used this pubkey personally. Updating time.' + t = (ripe, data, embeddedTime, 'yes') + else: + print 'We have NOT used this pubkey personally. Inserting in database.' + t = (ripe, data, embeddedTime, 'no') + # This will also update the embeddedTime. + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + # shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) + self.possibleNewPubkey(ripe) + if addressVersion == 3: + if len(data) < 170: # sanity check. + print '(within processpubkey) payloadLength less than 170. Sanity check failed.' + return + bitfieldBehaviors = data[readPosition:readPosition + 4] + readPosition += 4 + publicSigningKey = '\x04' + data[readPosition:readPosition + 64] + # Is it possible for a public key to be invalid such that trying to + # encrypt or sign with it will cause an error? If it is, we should + # probably test these keys here. + readPosition += 64 + publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64] + readPosition += 64 + specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += specifiedNonceTrialsPerByteLength + specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += specifiedPayloadLengthExtraBytesLength + endOfSignedDataPosition = readPosition + signatureLength, signatureLengthLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += signatureLengthLength + signature = data[readPosition:readPosition + signatureLength] + try: + if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')): + print 'ECDSA verify failed (within processpubkey)' + return + print 'ECDSA verify passed (within processpubkey)' + except Exception as err: + print 'ECDSA verify failed (within processpubkey)', err + return + + sha = hashlib.new('sha512') + sha.update(publicSigningKey + publicEncryptionKey) + ripeHasher = hashlib.new('ripemd160') + ripeHasher.update(sha.digest()) + ripe = ripeHasher.digest() + + shared.printLock.acquire() + print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber + print 'ripe', ripe.encode('hex') + print 'publicSigningKey in hex:', publicSigningKey.encode('hex') + print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') + shared.printLock.release() + + t = (ripe,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn != []: # if this pubkey is already in our database and if we have used it personally: + print 'We HAVE used this pubkey personally. Updating time.' + t = (ripe, data, embeddedTime, 'yes') + else: + print 'We have NOT used this pubkey personally. Inserting in database.' + t = (ripe, data, embeddedTime, 'no') + # This will also update the embeddedTime. + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''INSERT INTO pubkeys VALUES (?,?,?,?)''') + shared.sqlSubmitQueue.put(t) + shared.sqlReturnQueue.get() + shared.sqlSubmitQueue.put('commit') + shared.sqlLock.release() + # shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) + self.possibleNewPubkey(ripe) + + # We have received a getpubkey message + def recgetpubkey(self, data): + if not self.isProofOfWorkSufficient(data): + print 'Proof of work in getpubkey message insufficient.' + return + if len(data) < 34: + print 'getpubkey message doesn\'t contain enough data. Ignoring.' + return + readPosition = 8 # bypass the nonce + embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) + + # This section is used for the transition from 32 bit time to 64 bit + # time in the protocol. + if embeddedTime == 0: + embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) + readPosition += 8 + else: + readPosition += 4 + + if embeddedTime > int(time.time()) + 10800: + print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime + return + if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: + print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime + return + requestedAddressVersionNumber, addressVersionLength = decodeVarint( + data[readPosition:readPosition + 10]) + readPosition += addressVersionLength + streamNumber, streamNumberLength = decodeVarint( + data[readPosition:readPosition + 10]) + if streamNumber != self.streamNumber: + print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber + return + readPosition += streamNumberLength + + inventoryHash = calculateInventoryHash(data) + shared.inventoryLock.acquire() + if inventoryHash in shared.inventory: + print 'We have already received this getpubkey request. Ignoring it.' + shared.inventoryLock.release() + return + elif isInSqlInventory(inventoryHash): + print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.' + shared.inventoryLock.release() + return + + objectType = 'getpubkey' + shared.inventory[inventoryHash] = ( + objectType, self.streamNumber, data, embeddedTime) + shared.inventoryLock.release() + # This getpubkey request is valid so far. Forward to peers. + self.broadcastinv(inventoryHash) + + if requestedAddressVersionNumber == 0: + print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.' + return + elif requestedAddressVersionNumber == 1: + print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.' + return + elif requestedAddressVersionNumber > 3: + print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.' + return + + requestedHash = data[readPosition:readPosition + 20] + if len(requestedHash) != 20: + print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.' + return + print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex') + + if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine + if decodeAddress(shared.myAddressesByHash[requestedHash])[1] != requestedAddressVersionNumber: + 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') + shared.printLock.release() + return + try: + lastPubkeySendTime = int(shared.config.get( + shared.myAddressesByHash[requestedHash], 'lastpubkeysendtime')) + except: + lastPubkeySendTime = 0 + if lastPubkeySendTime < time.time() - lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago + shared.printLock.acquire() + 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() + if requestedAddressVersionNumber == 2: + shared.workerQueue.put(( + 'doPOWForMyV2Pubkey', requestedHash)) + elif requestedAddressVersionNumber == 3: + shared.workerQueue.put(( + 'doPOWForMyV3Pubkey', requestedHash)) + else: + 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 + shared.printLock.release() + else: + shared.printLock.acquire() + print 'This getpubkey request is not for any of my keys.' + shared.printLock.release() + + # We have received an inv message + def recinv(self, data): + totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = 0 # ..from all peers, counting duplicates seperately (because they take up memory) + if len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) > 0: + for key, value in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer.items(): + totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave += value + shared.printLock.acquire() + print 'number of keys(hosts) in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) + print 'totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = ', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave + shared.printLock.release() + numberOfItemsInInv, lengthOfVarint = decodeVarint(data[:10]) + if numberOfItemsInInv > 50000: + sys.stderr.write('Too many items in inv message!') + return + if len(data) < lengthOfVarint + (numberOfItemsInInv * 32): + print 'inv message doesn\'t contain enough data. Ignoring.' + return + if numberOfItemsInInv == 1: # we'll just request this data from the person who advertised the object. + if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation + shared.printLock.acquire() + 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() + return + self.objectsOfWhichThisRemoteNodeIsAlreadyAware[ + data[lengthOfVarint:32 + lengthOfVarint]] = 0 + if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: + shared.printLock.acquire() + print 'Inventory (in memory) has inventory item already.' + shared.printLock.release() + elif isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): + print 'Inventory (SQL on disk) has inventory item already.' + else: + self.sendgetdata(data[lengthOfVarint:32 + lengthOfVarint]) + else: + print 'inv message lists', numberOfItemsInInv, 'objects.' + for i in range(numberOfItemsInInv): # upon finishing dealing with an incoming message, the receiveDataThread will request a random object from the peer. This way if we get multiple inv messages from multiple peers which list mostly the same objects, we will make getdata requests for different random objects from the various peers. + if len(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) == 32: # The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously. + if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation + shared.printLock.acquire() + 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() + break + self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[ + lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0 + 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 + # hash + def sendgetdata(self, hash): + shared.printLock.acquire() + print 'sending getdata to retrieve object with hash:', hash.encode('hex') + shared.printLock.release() + payload = '\x01' + hash + headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. + 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 += hashlib.sha512(payload).digest()[:4] + try: + self.sock.sendall(headerData + payload) + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + # We have received a getdata request from our peer + def recgetdata(self, data): + numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint( + data[:10]) + if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems): + print 'getdata message does not contain enough data. Ignoring.' + return + for i in xrange(numberOfRequestedInventoryItems): + hash = data[lengthOfVarint + ( + i * 32):32 + lengthOfVarint + (i * 32)] + shared.printLock.acquire() + print 'received getdata request for item:', hash.encode('hex') + shared.printLock.release() + # print 'inventory is', shared.inventory + if hash in shared.inventory: + objectType, streamNumber, payload, receivedTime = shared.inventory[ + hash] + self.sendData(objectType, payload) + else: + t = (hash,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''select objecttype, payload from inventory where hash=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn != []: + for row in queryreturn: + objectType, payload = row + self.sendData(objectType, payload) + else: + print 'Someone asked for an object with a getdata which is not in either our memory inventory or our SQL inventory. That shouldn\'t have happened.' + + # Our peer has requested (in a getdata message) that we send an object. + def sendData(self, objectType, payload): + headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. + if objectType == 'pubkey': + shared.printLock.acquire() + print 'sending pubkey' + shared.printLock.release() + headerData += 'pubkey\x00\x00\x00\x00\x00\x00' + elif objectType == 'getpubkey' or objectType == 'pubkeyrequest': + shared.printLock.acquire() + print 'sending getpubkey' + shared.printLock.release() + headerData += 'getpubkey\x00\x00\x00' + elif objectType == 'msg': + shared.printLock.acquire() + print 'sending msg' + shared.printLock.release() + headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' + elif objectType == 'broadcast': + shared.printLock.acquire() + print 'sending broadcast' + shared.printLock.release() + headerData += 'broadcast\x00\x00\x00' + else: + sys.stderr.write( + 'Error: sendData has been asked to send a strange objectType: %s\n' % str(objectType)) + return + headerData += pack('>L', len(payload)) # payload length. + headerData += hashlib.sha512(payload).digest()[:4] + try: + self.sock.sendall(headerData + payload) + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + # Send an inv message with just one hash to all of our peers + def broadcastinv(self, hash): + shared.printLock.acquire() + print 'broadcasting inv with hash:', hash.encode('hex') + shared.printLock.release() + shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash)) + + # We have received an addr message. + def recaddr(self, data): + listOfAddressDetailsToBroadcastToPeers = [] + numberOfAddressesIncluded = 0 + numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint( + data[:10]) + + if verbose >= 1: + shared.printLock.acquire() + print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' + shared.printLock.release() + + 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': + shared.printLock.acquire() + print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) + shared.printLock.release() + continue + except Exception as err: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) + shared.printLock.release() + 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() + 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. + shared.knownNodesLock.acquire() + shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( + recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) + shared.knownNodesLock.release() + needToWriteKnownNodesToDisk = True + hostDetails = ( + timeSomeoneElseReceivedMessageFromThisNode, + recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) + listOfAddressDetailsToBroadcastToPeers.append( + hostDetails) + 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. + if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): + shared.knownNodesLock.acquire() + shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( + PORT, timeSomeoneElseReceivedMessageFromThisNode) + shared.knownNodesLock.release() + 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.' + 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') + pickle.dump(shared.knownNodes, output) + output.close() + shared.knownNodesLock.release() + self.broadcastaddr( + listOfAddressDetailsToBroadcastToPeers) # no longer broadcast + shared.printLock.acquire() + print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' + shared.printLock.release() + 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': + shared.printLock.acquire() + print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) + shared.printLock.release() + continue + except Exception as err: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) + shared.printLock.release() + 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: + shared.printLock.acquire() + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) + shared.printLock.release() + 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() + shared.knownNodes[recaddrStream] = {} + shared.knownNodesLock.release() + 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. + shared.knownNodesLock.acquire() + shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( + recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) + shared.knownNodesLock.release() + shared.printLock.acquire() + print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream + shared.printLock.release() + needToWriteKnownNodesToDisk = True + hostDetails = ( + timeSomeoneElseReceivedMessageFromThisNode, + recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) + listOfAddressDetailsToBroadcastToPeers.append( + hostDetails) + 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. + if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): + shared.knownNodesLock.acquire() + shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( + PORT, timeSomeoneElseReceivedMessageFromThisNode) + shared.knownNodesLock.release() + 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.' + 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') + pickle.dump(shared.knownNodes, output) + output.close() + shared.knownNodesLock.release() + self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) + shared.printLock.acquire() + print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' + shared.printLock.release() + + # Function runs when we want to broadcast an addr message to all of our + # peers. Runs when we learn of nodes that we didn't previously know about + # and want to share them with our peers. + def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers): + numberOfAddressesInAddrMessage = len( + listOfAddressDetailsToBroadcastToPeers) + payload = '' + for hostDetails in listOfAddressDetailsToBroadcastToPeers: + timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails + payload += pack( + '>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time + payload += pack('>I', streamNumber) + payload += pack( + '>q', services) # service bit flags offered by this node + payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ + socket.inet_aton(host) + payload += pack('>H', port) # remote port + + payload = encodeVarint(numberOfAddressesInAddrMessage) + payload + datatosend = '\xE9\xBE\xB4\xD9addr\x00\x00\x00\x00\x00\x00\x00\x00' + datatosend = datatosend + pack('>L', len(payload)) # payload length + datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] + datatosend = datatosend + payload + + if verbose >= 1: + shared.printLock.acquire() + print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' + shared.printLock.release() + shared.broadcastToSendDataQueues(( + self.streamNumber, 'sendaddr', datatosend)) + + # Send a big addr message to our peer + def sendaddr(self): + addrsInMyStream = {} + addrsInChildStreamLeft = {} + addrsInChildStreamRight = {} + # 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. + shared.knownNodesLock.acquire() + if len(shared.knownNodes[self.streamNumber]) > 0: + for i in range(500): + random.seed() + HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) + if helper_generic.isHostInPrivateIPRange(HOST): + continue + addrsInMyStream[HOST] = shared.knownNodes[ + self.streamNumber][HOST] + if len(shared.knownNodes[self.streamNumber * 2]) > 0: + for i in range(250): + random.seed() + HOST, = random.sample(shared.knownNodes[ + self.streamNumber * 2], 1) + if helper_generic.isHostInPrivateIPRange(HOST): + continue + addrsInChildStreamLeft[HOST] = shared.knownNodes[ + self.streamNumber * 2][HOST] + if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0: + for i in range(250): + random.seed() + HOST, = random.sample(shared.knownNodes[ + (self.streamNumber * 2) + 1], 1) + if helper_generic.isHostInPrivateIPRange(HOST): + continue + addrsInChildStreamRight[HOST] = shared.knownNodes[ + (self.streamNumber * 2) + 1][HOST] + shared.knownNodesLock.release() + numberOfAddressesInAddrMessage = 0 + payload = '' + # print 'addrsInMyStream.items()', addrsInMyStream.items() + for HOST, value in addrsInMyStream.items(): + PORT, timeLastReceivedMessageFromThisNode = value + if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + numberOfAddressesInAddrMessage += 1 + payload += pack( + '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time + payload += pack('>I', self.streamNumber) + payload += pack( + '>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 + for HOST, value in addrsInChildStreamLeft.items(): + PORT, timeLastReceivedMessageFromThisNode = value + if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + numberOfAddressesInAddrMessage += 1 + payload += pack( + '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time + payload += pack('>I', self.streamNumber * 2) + payload += pack( + '>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 + for HOST, value in addrsInChildStreamRight.items(): + PORT, timeLastReceivedMessageFromThisNode = value + if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + numberOfAddressesInAddrMessage += 1 + payload += pack( + '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time + payload += pack('>I', (self.streamNumber * 2) + 1) + payload += pack( + '>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 = 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: + self.sock.sendall(datatosend) + if verbose >= 1: + shared.printLock.acquire() + print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' + shared.printLock.release() + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + # We have received a version message + def recversion(self, data): + if len(data) < 83: + # This version message is unreasonably short. Forget it. + return + elif not self.verackSent: + self.remoteProtocolVersion, = unpack('>L', data[:4]) + if self.remoteProtocolVersion <= 1: + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) + shared.printLock.acquire() + print 'Closing connection to old protocol version 1 node: ', self.HOST + shared.printLock.release() + return + # print 'remoteProtocolVersion', self.remoteProtocolVersion + self.myExternalIP = socket.inet_ntoa(data[40:44]) + # print 'myExternalIP', self.myExternalIP + self.remoteNodeIncomingPort, = unpack('>H', data[70:72]) + # print 'remoteNodeIncomingPort', self.remoteNodeIncomingPort + useragentLength, lengthOfUseragentVarint = decodeVarint( + data[80:84]) + readPosition = 80 + lengthOfUseragentVarint + useragent = data[readPosition:readPosition + useragentLength] + readPosition += useragentLength + numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint( + data[readPosition:]) + readPosition += lengthOfNumberOfStreamsInVersionMessage + self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint( + data[readPosition:]) + shared.printLock.acquire() + print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber + shared.printLock.release() + if self.streamNumber != 1: + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) + shared.printLock.acquire() + print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.' + shared.printLock.release() + 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. + # If this was an incoming connection, then the sendData thread + # doesn't know the stream. We have to set it. + if not self.initiatedConnection: + shared.broadcastToSendDataQueues(( + 0, 'setStreamNumber', (self.HOST, self.streamNumber))) + if data[72:80] == eightBytesOfRandomDataUsedToDetectConnectionsToSelf: + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) + shared.printLock.acquire() + print 'Closing connection to myself: ', self.HOST + shared.printLock.release() + return + shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', ( + self.HOST, self.remoteProtocolVersion))) + + shared.knownNodesLock.acquire() + shared.knownNodes[self.streamNumber][self.HOST] = ( + self.remoteNodeIncomingPort, int(time.time())) + output = open(shared.appdata + 'knownnodes.dat', 'wb') + pickle.dump(shared.knownNodes, output) + output.close() + shared.knownNodesLock.release() + + self.sendverack() + if self.initiatedConnection == False: + self.sendversion() + + # Sends a version message + def sendversion(self): + shared.printLock.acquire() + print 'Sending version message' + shared.printLock.release() + try: + self.sock.sendall(assembleVersionMessage( + self.HOST, self.PORT, self.streamNumber)) + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + + # Sends a verack message + def sendverack(self): + shared.printLock.acquire() + print 'Sending verack' + shared.printLock.release() + 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') + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + # cf + # 83 + # e1 + # 35 + self.verackSent = True + if self.verackReceived: + self.connectionFullyEstablished() diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py new file mode 100644 index 00000000..68791198 --- /dev/null +++ b/src/class_sendDataThread.py @@ -0,0 +1,165 @@ +import time +import threading +import shared + +# Every connection to a peer has a sendDataThread (and also a +# receiveDataThread). +class sendDataThread(threading.Thread): + + def __init__(self): + threading.Thread.__init__(self) + self.mailbox = Queue.Queue() + shared.sendDataQueues.append(self.mailbox) + shared.printLock.acquire() + print 'The length of sendDataQueues at sendDataThread init is:', len(shared.sendDataQueues) + shared.printLock.release() + self.data = '' + + def setup( + self, + sock, + HOST, + PORT, + streamNumber, + objectsOfWhichThisRemoteNodeIsAlreadyAware): + self.sock = sock + self.HOST = HOST + self.PORT = PORT + self.streamNumber = streamNumber + self.remoteProtocolVersion = - \ + 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 + shared.printLock.acquire() + print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber + shared.printLock.release() + + def sendVersionMessage(self): + datatosend = assembleVersionMessage( + self.HOST, self.PORT, self.streamNumber) # the IP and port of the remote host, and my streamNumber. + + shared.printLock.acquire() + print 'Sending version packet: ', repr(datatosend) + shared.printLock.release() + try: + self.sock.sendall(datatosend) + except Exception as err: + # if not 'Bad file descriptor' in err: + shared.printLock.acquire() + sys.stderr.write('sock.sendall error: %s\n' % err) + shared.printLock.release() + self.versionSent = 1 + + def run(self): + while True: + deststream, command, data = self.mailbox.get() + # shared.printLock.acquire() + # print 'sendDataThread, destream:', deststream, ', Command:', command, ', ID:',id(self), ', HOST:', self.HOST + # shared.printLock.release() + + if deststream == self.streamNumber or deststream == 0: + if command == 'shutdown': + if data == self.HOST or data == 'all': + shared.printLock.acquire() + print 'sendDataThread (associated with', self.HOST, ') ID:', id(self), 'shutting down now.' + shared.printLock.release() + try: + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + except: + pass + shared.sendDataQueues.remove(self.mailbox) + shared.printLock.acquire() + print 'len of sendDataQueues', len(shared.sendDataQueues) + shared.printLock.release() + 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: + elif command == 'setStreamNumber': + hostInMessage, specifiedStreamNumber = data + if hostInMessage == self.HOST: + shared.printLock.acquire() + print 'setting the stream number in the sendData thread (ID:', id(self), ') to', specifiedStreamNumber + shared.printLock.release() + self.streamNumber = specifiedStreamNumber + elif command == 'setRemoteProtocolVersion': + hostInMessage, specifiedRemoteProtocolVersion = data + if hostInMessage == self.HOST: + shared.printLock.acquire() + print 'setting the remote node\'s protocol version in the sendData thread (ID:', id(self), ') to', specifiedRemoteProtocolVersion + shared.printLock.release() + self.remoteProtocolVersion = specifiedRemoteProtocolVersion + elif command == 'sendaddr': + 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. + random.seed() + time.sleep(random.randrange(0, 10)) + self.sock.sendall(data) + self.lastTimeISentData = int(time.time()) + except: + print 'self.sock.sendall failed' + try: + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + except: + pass + shared.sendDataQueues.remove(self.mailbox) + print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST + break + elif command == 'sendinv': + if data not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: + payload = '\x01' + data + 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()) + except: + print 'self.sock.sendall failed' + try: + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + except: + pass + shared.sendDataQueues.remove(self.mailbox) + print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST + break + elif command == 'pong': + if self.lastTimeISentData < (int(time.time()) - 298): + # Send out a pong message to keep the connection alive. + shared.printLock.acquire() + print 'Sending pong to', self.HOST, 'to keep connection alive.' + shared.printLock.release() + 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.lastTimeISentData = int(time.time()) + except: + print 'send pong failed' + try: + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + except: + pass + shared.sendDataQueues.remove(self.mailbox) + print 'sendDataThread thread', self, 'ending now. Was connected to', self.HOST + break + else: + shared.printLock.acquire() + print 'sendDataThread ID:', id(self), 'ignoring command', command, 'because the thread is not in stream', deststream + shared.printLock.release() + diff --git a/src/class_singleListener.py b/src/class_singleListener.py index 9e982a24..c050907c 100644 --- a/src/class_singleListener.py +++ b/src/class_singleListener.py @@ -2,6 +2,9 @@ import threading import shared import socket +from class_sendDataThread import * +from class_receiveDataThread import * + # 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 From 37886916b8e5e08c0698ec575972cdf54db43397 Mon Sep 17 00:00:00 2001 From: Joshua Noble Date: Sat, 22 Jun 2013 02:21:24 -0400 Subject: [PATCH 30/93] Add getSentMessagesByAddress API command --- src/bitmessagemain.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 4279a259..c0b9c04e 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -4419,6 +4419,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data elif method == 'getInboxMessagesByAddress': + if len(params) == 0: + return 'API Error 0000: I need parameters!' toAddress = params[0] v = (toAddress,) shared.sqlLock.acquire() @@ -4454,6 +4456,26 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status,'ackData':ackdata.encode('hex')},indent=4, separators=(',', ': ')) data += ']}' return data + elif method == 'getSentMessagesByAddress': + if len(params) == 0: + return 'API Error 0000: I need parameters!' + fromAddress = params[0] + v = (fromAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime''') + shared.sqlSubmitQueue.put(v) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + data = '{"sentMessages":[' + for row in queryreturn: + msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + if len(data) > 25: + data += ',' + data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':encodingtype,'lastActionTime':lastactiontime,'status':status,'ackData':ackdata.encode('hex')},indent=4, separators=(',', ': ')) + data += ']}' + return data elif method == 'getSentMessageByAckData': if len(params) == 0: return 'API Error 0000: I need parameters!' From c2f493b59509477c97d151c5cf87e22811df782a Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Sat, 22 Jun 2013 10:55:15 -0400 Subject: [PATCH 31/93] Fix issue #246 --- src/bitmessagemain.py | 1 - src/helper_startup.py | 5 ++++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 52e89846..0806afc9 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -14,7 +14,6 @@ lengthOfTimeToLeaveObjectsInInventory = 237600 # Equals two days and 18 hours. lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time. maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 # Equals two days and 12 hours maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours -storeConfigFilesInSameDirectoryAsProgramByDefault = False # The user may de-select Portable Mode in the settings if they want the config files to stay in the application data folder. useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the normal network, you won't be able to send or sometimes receive messages. encryptedBroadcastSwitchoverTime = 1369735200 diff --git a/src/helper_startup.py b/src/helper_startup.py index b7e9e607..3cea3a30 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -1,6 +1,9 @@ import shared import ConfigParser -import time +import sys +import os + +storeConfigFilesInSameDirectoryAsProgramByDefault = False # The user may de-select Portable Mode in the settings if they want the config files to stay in the application data folder. def loadConfig(): # First try to load the config file (the keys.dat file) from the program From f1d2b042eacc004410504cb6976c7d1f4978c5f4 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Sun, 23 Jun 2013 02:38:21 -0400 Subject: [PATCH 32/93] add import sys to class_sqlThread.py --- src/class_sqlThread.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 210a78e3..f54d5a86 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -3,6 +3,7 @@ import shared import sqlite3 import time import shutil # used for moving the messages.dat file +import sys # 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 From e9dc2d5c5ea78f9945eb700514342ebfe54539b0 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Sun, 23 Jun 2013 19:31:47 +0100 Subject: [PATCH 33/93] Fixed missing hashlib import in class_sendDataThread --- src/class_sendDataThread.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index fd0ca786..6773a868 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -3,6 +3,7 @@ import threading import shared import Queue from struct import unpack, pack +import hashlib import bitmessagemain From 2eb6558cf100952fbd827cd059ff7866061f6fe3 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Sun, 23 Jun 2013 20:52:39 +0100 Subject: [PATCH 34/93] Added a number of missing imports fixing several issues (thank you PyDev) --- .gitignore | 2 ++ src/build_osx.py | 2 +- src/class_addressGenerator.py | 2 ++ src/class_outgoingSynSender.py | 2 +- src/class_receiveDataThread.py | 19 +++++++++++++------ src/class_sendDataThread.py | 3 +++ src/class_singleCleaner.py | 4 +++- src/class_singleWorker.py | 3 +++ src/class_sqlThread.py | 1 + src/defaultKnownNodes.py | 2 +- src/helper_generic.py | 1 + src/helper_startup.py | 1 - src/proofofwork.py | 5 +++-- src/shared.py | 2 ++ src/singleton.py | 4 ++-- 15 files changed, 38 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index acfa0ca1..e0055bc7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ **.DS_Store src/build src/dist +src/.project +src/.pydevprojecy diff --git a/src/build_osx.py b/src/build_osx.py index de08da4c..db004769 100644 --- a/src/build_osx.py +++ b/src/build_osx.py @@ -9,7 +9,7 @@ Usage (Windows): """ import sys, os, shutil, re -from setuptools import setup +from setuptools import setup # @UnresolvedImport name = "Bitmessage" diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index e22fdd51..c19a294b 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -2,9 +2,11 @@ import shared import threading import bitmessagemain import time +import sys from pyelliptic.openssl import OpenSSL import ctypes import hashlib +import highlevelcrypto from addresses import * from pyelliptic import arithmetic diff --git a/src/class_outgoingSynSender.py b/src/class_outgoingSynSender.py index ee8c5640..d3310698 100644 --- a/src/class_outgoingSynSender.py +++ b/src/class_outgoingSynSender.py @@ -141,7 +141,7 @@ class outgoingSynSender(threading.Thread): shared.printLock.release() except socks.Socks5AuthError as err: shared.UISignalQueue.put(( - 'updateStatusBar', translateText( + 'updateStatusBar', bitmessagemain.translateText( "MainWindow", "SOCKS5 Authentication problem: %1").arg(str(err)))) except socks.Socks5Error as err: pass diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index decd9618..c1148667 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -7,9 +7,16 @@ import pickle import random from struct import unpack, pack import sys +import string +from subprocess import call # used when the API must execute an outside program +from pyelliptic.openssl import OpenSSL +import highlevelcrypto from addresses import * import helper_generic +import helper_bitcoin +import helper_inbox +import helper_sent import bitmessagemain from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers, numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer, neededPubkeys @@ -814,8 +821,8 @@ class receiveDataThread(threading.Thread): shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( - strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], bitmessagemain.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( + time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8'))))) return else: shared.printLock.acquire() @@ -1046,7 +1053,7 @@ class receiveDataThread(threading.Thread): subject = self.addMailingListNameToSubject( subject, mailingListName) # Let us now send this message out as a broadcast - message = strftime("%a, %Y-%m-%d %H:%M:%S UTC", gmtime( + message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime( )) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing. ackdata = OpenSSL.rand( @@ -1069,14 +1076,14 @@ class receiveDataThread(threading.Thread): # Display timing data timeRequiredToAttemptToDecryptMessage = time.time( ) - self.messageProcessingStartTime - successfullyDecryptMessageTimings.append( + bitmessagemain.successfullyDecryptMessageTimings.append( timeRequiredToAttemptToDecryptMessage) sum = 0 - for item in successfullyDecryptMessageTimings: + for item in bitmessagemain.successfullyDecryptMessageTimings: sum += item shared.printLock.acquire() print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage - print 'Average time for all message decryption successes since startup:', sum / len(successfullyDecryptMessageTimings) + print 'Average time for all message decryption successes since startup:', sum / len(bitmessagemain.successfullyDecryptMessageTimings) shared.printLock.release() def isAckDataValid(self, ackData): diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index 6773a868..1e3528dd 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -4,6 +4,9 @@ import shared import Queue from struct import unpack, pack import hashlib +import random +import sys +import socket import bitmessagemain diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 999cda26..f04a5507 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -1,7 +1,9 @@ import threading import shared import time -from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers +from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers,\ + neededPubkeys +import sys '''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: diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 9e1582f9..e0d54c37 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -7,6 +7,9 @@ from addresses import * import bitmessagemain import highlevelcrypto import proofofwork +from bitmessagemain import neededPubkeys, encryptedBroadcastSwitchoverTime +import sys +from class_addressGenerator import pointMult # This thread, of which there is only one, does the heavy lifting: # calculating POWs. diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index f54d5a86..5848e868 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -4,6 +4,7 @@ import sqlite3 import time import shutil # used for moving the messages.dat file import sys +import os # 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 diff --git a/src/defaultKnownNodes.py b/src/defaultKnownNodes.py index 4f4e80ce..5c6d5b21 100644 --- a/src/defaultKnownNodes.py +++ b/src/defaultKnownNodes.py @@ -59,7 +59,7 @@ if __name__ == "__main__": APPNAME = "PyBitmessage" from os import path, environ if sys.platform == 'darwin': - from AppKit import NSSearchPathForDirectoriesInDomains + from AppKit import NSSearchPathForDirectoriesInDomains # @UnresolvedImport # http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains # NSApplicationSupportDirectory = 14 # NSUserDomainMask = 1 diff --git a/src/helper_generic.py b/src/helper_generic.py index 99c1c2d3..e79a5a43 100644 --- a/src/helper_generic.py +++ b/src/helper_generic.py @@ -1,4 +1,5 @@ import shared +import sys def convertIntToString(n): a = __builtins__.hex(n) diff --git a/src/helper_startup.py b/src/helper_startup.py index 3cea3a30..df27fd6e 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -8,7 +8,6 @@ storeConfigFilesInSameDirectoryAsProgramByDefault = False # The user may de-sel def loadConfig(): # First try to load the config file (the keys.dat file) from the program # directory - shared.config = ConfigParser.SafeConfigParser() shared.config.read('keys.dat') try: shared.config.get('bitmessagesettings', 'settingsversion') diff --git a/src/proofofwork.py b/src/proofofwork.py index f65c127f..f2c32c06 100644 --- a/src/proofofwork.py +++ b/src/proofofwork.py @@ -4,16 +4,17 @@ import hashlib from struct import unpack, pack import sys +from shared import config #import os def _set_idle(): if 'linux' in sys.platform: import os - os.nice(20) + os.nice(20) # @UndefinedVariable else: try: sys.getwindowsversion() - import win32api,win32process,win32con + import win32api,win32process,win32con # @UnresolvedImport pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS) diff --git a/src/shared.py b/src/shared.py index 256008c1..b225012c 100644 --- a/src/shared.py +++ b/src/shared.py @@ -8,7 +8,9 @@ import Queue import pickle import os import time +import ConfigParser +config = ConfigParser.SafeConfigParser() myECCryptorObjects = {} MyECSubscriptionCryptorObjects = {} myAddressesByHash = {} #The key in this dictionary is the RIPE hash which is encoded in an address and value is the address itself. diff --git a/src/singleton.py b/src/singleton.py index 7ecca3b7..ee5c3077 100644 --- a/src/singleton.py +++ b/src/singleton.py @@ -34,7 +34,7 @@ class singleinstance: print(e.errno) raise else: # non Windows - import fcntl + import fcntl # @UnresolvedImport self.fp = open(self.lockfile, 'w') try: fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -53,7 +53,7 @@ class singleinstance: os.close(self.fd) os.unlink(self.lockfile) else: - import fcntl + import fcntl # @UnresolvedImport fcntl.lockf(self.fp, fcntl.LOCK_UN) if os.path.isfile(self.lockfile): os.unlink(self.lockfile) From fa7932974dd5a7cdba858db5769d0c9a0f3ff64c Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Sun, 23 Jun 2013 20:53:14 +0100 Subject: [PATCH 35/93] Updated gitignore for pydev development --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index e0055bc7..1efe77d8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,4 @@ src/build src/dist src/.project -src/.pydevprojecy +src/.pydevproject From 01e20177bc8d89ca623c36d44107a5f3b3d05d76 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Sun, 23 Jun 2013 21:17:34 +0100 Subject: [PATCH 36/93] Adding src/.settings/ to .gitignore (for Eclipse developers) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1efe77d8..8e9f9031 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ src/build src/dist src/.project src/.pydevproject +src/.settings/ \ No newline at end of file From 9925d55df2fb48038981e7c589a255030dc05d7c Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Sun, 23 Jun 2013 21:30:16 +0100 Subject: [PATCH 37/93] Removed unused imports from bitmessagemain --- src/bitmessagemain.py | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 3fe31747..3b189445 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -22,32 +22,12 @@ alreadyAttemptedConnectionsList = { numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer = {} neededPubkeys = {} -import sys -import Queue -from addresses import * -import shared -from defaultKnownNodes import * -import time -import socket -import threading -import hashlib -from struct import * -import pickle -import random -import sqlite3 -from time import strftime, localtime, gmtime -import string -import socks -import highlevelcrypto -from pyelliptic.openssl import OpenSSL #import ctypes import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. # The next 3 are used for the API from SimpleXMLRPCServer import * import json -from subprocess import call # used when the API must execute an outside program import singleton -import proofofwork # Classes from class_sqlThread import * @@ -60,10 +40,6 @@ from class_addressGenerator import * # Helper Functions import helper_startup import helper_bootstrap -import helper_inbox -import helper_sent -import helper_generic -import helper_bitcoin def isInSqlInventory(hash): t = (hash,) From cc304b4e8b28afa6944889727d9acabdb333f40e Mon Sep 17 00:00:00 2001 From: Delia Eris Date: Sun, 23 Jun 2013 21:49:18 -0500 Subject: [PATCH 38/93] spelling implimented -> implemented --- src/bitmessageqt/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 3f0c7e6f..a18ba07c 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2682,12 +2682,12 @@ class settingsDialog(QtGui.QDialog): self.ui.checkBoxMinimizeToTray.setDisabled(True) self.ui.checkBoxShowTrayNotifications.setDisabled(True) self.ui.labelSettingsNote.setText(_translate( - "MainWindow", "Options have been disabled because they either aren\'t applicable or because they haven\'t yet been implimented for your operating system.")) + "MainWindow", "Options have been disabled because they either aren\'t applicable or because they haven\'t yet been implemented for your operating system.")) elif 'linux' in sys.platform: self.ui.checkBoxStartOnLogon.setDisabled(True) self.ui.checkBoxMinimizeToTray.setDisabled(True) self.ui.labelSettingsNote.setText(_translate( - "MainWindow", "Options have been disabled because they either aren\'t applicable or because they haven\'t yet been implimented for your operating system.")) + "MainWindow", "Options have been disabled because they either aren\'t applicable or because they haven\'t yet been implemented for your operating system.")) # On the Network settings tab: self.ui.lineEditTCPPort.setText(str( shared.config.get('bitmessagesettings', 'port'))) From c3ea67ed05fa2dfa6bbcfac1355c47d310743fea Mon Sep 17 00:00:00 2001 From: DivineOmega Date: Mon, 24 Jun 2013 13:56:30 +0100 Subject: [PATCH 39/93] Changed headings of list of connections per stream so that it fits visually --- src/bitmessageqt/bitmessageui.py | 4 ++-- src/bitmessageqt/bitmessageui.ui | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index fa0a11f3..1186e814 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -537,9 +537,9 @@ class Ui_MainWindow(object): item.setText(_translate("MainWindow", "Address", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.blackwhitelist), _translate("MainWindow", "Blacklist", None)) item = self.tableWidgetConnectionCount.horizontalHeaderItem(0) - item.setText(_translate("MainWindow", "Stream Number", None)) + item.setText(_translate("MainWindow", "Stream #", None)) item = self.tableWidgetConnectionCount.horizontalHeaderItem(1) - item.setText(_translate("MainWindow", "Number of Connections", None)) + item.setText(_translate("MainWindow", "Connections", None)) self.labelTotalConnections.setText(_translate("MainWindow", "Total connections: 0", None)) self.labelStartupTime.setText(_translate("MainWindow", "Since startup at asdf:", None)) self.labelMessageCount.setText(_translate("MainWindow", "Processed 0 person-to-person message.", None)) diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index c758e706..48f5c224 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -840,12 +840,12 @@ p, li { white-space: pre-wrap; } - Stream Number + Stream # - Number of Connections + Connections From c857f73d0bb3d967dcc1d06b963e575b076d7484 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 15:51:01 -0400 Subject: [PATCH 40/93] Continued moving code into individual modules --- src/bitmessagemain.py | 112 ++------------------------------- src/bitmessageqt/__init__.py | 2 - src/class_addressGenerator.py | 14 ++--- src/class_outgoingSynSender.py | 41 ++++++------ src/class_receiveDataThread.py | 102 +++++++++++++++--------------- src/class_sendDataThread.py | 11 ++-- src/class_singleCleaner.py | 16 +++-- src/class_singleListener.py | 8 +-- src/class_singleWorker.py | 56 ++++++++--------- src/shared.py | 75 ++++++++++++++++++++++ src/tr.py | 30 +++++++++ 11 files changed, 231 insertions(+), 236 deletions(-) create mode 100644 src/tr.py diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 3b189445..63f1f8f1 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -8,19 +8,6 @@ # yet contain logic to expand into further streams. # The software version variable is now held in shared.py -verbose = 1 -maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # Equals two days and 12 hours. -lengthOfTimeToLeaveObjectsInInventory = 237600 # Equals two days and 18 hours. This should be longer than maximumAgeOfAnObjectThatIAmWillingToAccept so that we don't process messages twice. -lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time. -maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 # Equals two days and 12 hours -maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours -useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the normal network, you won't be able to send or sometimes receive messages. -encryptedBroadcastSwitchoverTime = 1369735200 - -alreadyAttemptedConnectionsList = { -} # This is a list of nodes to which we have already attempted a connection -numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer = {} -neededPubkeys = {} #import ctypes import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. @@ -41,19 +28,6 @@ from class_addressGenerator import * import helper_startup import helper_bootstrap -def isInSqlInventory(hash): - t = (hash,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put('''select hash from inventory where hash=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - if queryreturn == []: - return False - else: - return True - - def connectToStream(streamNumber): selfInitiatedConnections[streamNumber] = {} if sys.platform[0:3] == 'win': @@ -66,46 +40,6 @@ def connectToStream(streamNumber): a.start() - -def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): - shared.softwareVersion - payload = '' - payload += pack('>L', 2) # protocol version. - payload += pack('>q', 1) # bitflags of the services I offer. - 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 += '\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('>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 += pack('>H', shared.config.getint( - 'bitmessagesettings', 'port')) # my external IPv6 and port - - random.seed() - payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf - userAgent = '/PyBitmessage:' + shared.softwareVersion + \ - '/' # 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 += encodeVarint( - 1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection. - payload += encodeVarint(myStreamNumber) - - datatosend = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - datatosend = datatosend + 'version\x00\x00\x00\x00\x00' # version command - datatosend = datatosend + pack('>L', len(payload)) # payload length - datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] - return datatosend + payload - - - - # This is one of several classes that constitute the API # 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/ @@ -729,50 +663,14 @@ class singleAPI(threading.Thread): se.register_introspection_functions() se.serve_forever() -# This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions. -class translateClass: - def __init__(self, context, text): - self.context = context - self.text = text - def arg(self,argument): - if '%' in self.text: - return translateClass(self.context, self.text.replace('%','',1)) # This doesn't actually do anything with the arguments because we don't have a UI in which to display this information anyway. - else: - return self.text - -def _translate(context, text): - return translateText(context, text) - -def translateText(context, text): - if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): - try: - from PyQt4 import QtCore, QtGui - 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 'Error message:', err - os._exit(0) - return QtGui.QApplication.translate(context, text) - else: - if '%' in text: - return translateClass(context, text.replace('%','',1)) - else: - return text - - selfInitiatedConnections = {} # This is a list of current connections (the thread pointers at least) -ackdataForWhichImWatching = {} -alreadyAttemptedConnectionsListLock = threading.Lock() -eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack( - '>Q', random.randrange(1, 18446744073709551615)) -successfullyDecryptMessageTimings = [ -] # A list of the amounts of time it took to successfully decrypt msg messages -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. -if useVeryEasyProofOfWorkForTesting: + + + + +if shared.useVeryEasyProofOfWorkForTesting: shared.networkDefaultProofOfWorkNonceTrialsPerByte = int( shared.networkDefaultProofOfWorkNonceTrialsPerByte / 16) shared.networkDefaultPayloadLengthExtraBytes = int( diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 3f0c7e6f..9930b318 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -12,7 +12,6 @@ except Exception as err: print 'Error message:', err sys.exit() - try: _encoding = QtGui.QApplication.UnicodeUTF8 except AttributeError: @@ -21,7 +20,6 @@ except AttributeError: def _translate(context, text): return QtGui.QApplication.translate(context, text) - withMessagingMenu = False try: from gi.repository import MessagingMenu diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index c19a294b..38c7d5b9 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -1,6 +1,5 @@ import shared import threading -import bitmessagemain import time import sys from pyelliptic.openssl import OpenSSL @@ -9,6 +8,7 @@ import hashlib import highlevelcrypto from addresses import * from pyelliptic import arithmetic +import tr class addressGenerator(threading.Thread): @@ -44,7 +44,7 @@ class addressGenerator(threading.Thread): if addressVersionNumber == 3: # currently the only one supported. if command == 'createRandomAddress': shared.UISignalQueue.put(( - 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Generating one new address"))) + 'updateStatusBar', tr.translateText("MainWindow", "Generating one new address"))) # 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, # we won't store the \x00 or \x00\x00 bytes thus making the @@ -112,10 +112,10 @@ class addressGenerator(threading.Thread): # 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. - bitmessagemain.apiAddressGeneratorReturnQueue.put(address) + shared.apiAddressGeneratorReturnQueue.put(address) shared.UISignalQueue.put(( - 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) + 'updateStatusBar', tr.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) shared.UISignalQueue.put(('writeNewAddressToTable', ( label, address, streamNumber))) shared.reloadMyAddressHashes() @@ -235,13 +235,13 @@ class addressGenerator(threading.Thread): # 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. - bitmessagemain.apiAddressGeneratorReturnQueue.put( + shared.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) shared.UISignalQueue.put(( - 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address"))) + 'updateStatusBar', tr.translateText("MainWindow", "Done generating address"))) # shared.reloadMyAddressHashes() elif command == 'getDeterministicAddress': - bitmessagemain.apiAddressGeneratorReturnQueue.put(address) + shared.apiAddressGeneratorReturnQueue.put(address) else: raise Exception( "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command) diff --git a/src/class_outgoingSynSender.py b/src/class_outgoingSynSender.py index d3310698..d547b3e3 100644 --- a/src/class_outgoingSynSender.py +++ b/src/class_outgoingSynSender.py @@ -5,8 +5,9 @@ import shared import socks import socket import sys +import tr -import bitmessagemain +#import bitmessagemain from class_sendDataThread import * from class_receiveDataThread import * @@ -33,25 +34,25 @@ class outgoingSynSender(threading.Thread): shared.knownNodesLock.acquire() HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) shared.knownNodesLock.release() - bitmessagemain.alreadyAttemptedConnectionsListLock.acquire() - while HOST in bitmessagemain.alreadyAttemptedConnectionsList or HOST in shared.connectedHostsList: - bitmessagemain.alreadyAttemptedConnectionsListLock.release() + shared.alreadyAttemptedConnectionsListLock.acquire() + while HOST in shared.alreadyAttemptedConnectionsList or HOST in shared.connectedHostsList: + shared.alreadyAttemptedConnectionsListLock.release() # print 'choosing new sample' random.seed() shared.knownNodesLock.acquire() HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) shared.knownNodesLock.release() time.sleep(1) - # Clear out the bitmessagemain.alreadyAttemptedConnectionsList every half + # Clear out the shared.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() - bitmessagemain.alreadyAttemptedConnectionsListResetTime) > 1800: - bitmessagemain.alreadyAttemptedConnectionsList.clear() - bitmessagemain.alreadyAttemptedConnectionsListResetTime = int( + if (time.time() - shared.alreadyAttemptedConnectionsListResetTime) > 1800: + shared.alreadyAttemptedConnectionsList.clear() + shared.alreadyAttemptedConnectionsListResetTime = int( time.time()) - bitmessagemain.alreadyAttemptedConnectionsListLock.acquire() - bitmessagemain.alreadyAttemptedConnectionsList[HOST] = 0 - bitmessagemain.alreadyAttemptedConnectionsListLock.release() + shared.alreadyAttemptedConnectionsListLock.acquire() + shared.alreadyAttemptedConnectionsList[HOST] = 0 + shared.alreadyAttemptedConnectionsListLock.release() PORT, timeNodeLastSeen = shared.knownNodes[ self.streamNumber][HOST] sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) @@ -59,13 +60,13 @@ class outgoingSynSender(threading.Thread): # can rebind faster sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(20) - if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and bitmessagemain.verbose >= 2: + if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2: shared.printLock.acquire() print 'Trying an outgoing connection to', HOST, ':', PORT shared.printLock.release() # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a': - if bitmessagemain.verbose >= 2: + if shared.verbose >= 2: shared.printLock.acquire() print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT shared.printLock.release() @@ -86,7 +87,7 @@ class outgoingSynSender(threading.Thread): sock.setproxy( proxytype, sockshostname, socksport, rdns) elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5': - if bitmessagemain.verbose >= 2: + if shared.verbose >= 2: shared.printLock.acquire() print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT shared.printLock.release() @@ -111,9 +112,9 @@ class outgoingSynSender(threading.Thread): sock.connect((HOST, PORT)) rd = receiveDataThread() rd.daemon = True # close the main program even if there are threads left - objectsOfWhichThisRemoteNodeIsAlreadyAware = {} + someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory. rd.setup(sock, HOST, PORT, self.streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) + someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) rd.start() shared.printLock.acquire() print self, 'connected to', HOST, 'during an outgoing attempt.' @@ -121,12 +122,12 @@ class outgoingSynSender(threading.Thread): sd = sendDataThread() sd.setup(sock, HOST, PORT, self.streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware) + someObjectsOfWhichThisRemoteNodeIsAlreadyAware) sd.start() sd.sendVersionMessage() except socks.GeneralProxyError as err: - if bitmessagemain.verbose >= 2: + if shared.verbose >= 2: shared.printLock.acquire() print 'Could NOT connect to', HOST, 'during outgoing attempt.', err shared.printLock.release() @@ -141,7 +142,7 @@ class outgoingSynSender(threading.Thread): shared.printLock.release() except socks.Socks5AuthError as err: shared.UISignalQueue.put(( - 'updateStatusBar', bitmessagemain.translateText( + 'updateStatusBar', tr.translateText( "MainWindow", "SOCKS5 Authentication problem: %1").arg(str(err)))) except socks.Socks5Error as err: pass @@ -152,7 +153,7 @@ class outgoingSynSender(threading.Thread): if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err) else: - if bitmessagemain.verbose >= 1: + if shared.verbose >= 1: shared.printLock.acquire() print 'Could NOT connect to', HOST, 'during outgoing attempt.', err shared.printLock.release() diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index c1148667..3d658255 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -17,14 +17,12 @@ import helper_generic import helper_bitcoin import helper_inbox import helper_sent -import bitmessagemain -from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers, numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer, neededPubkeys - +import tr +#from bitmessagemain import shared.lengthOfTimeToLeaveObjectsInInventory, shared.lengthOfTimeToHoldOnToAllPubkeys, shared.maximumAgeOfAnObjectThatIAmWillingToAccept, shared.maximumAgeOfObjectsThatIAdvertiseToOthers, shared.maximumAgeOfNodesThatIAdvertiseToOthers, shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer, shared.neededPubkeys # This thread is created either by the synSenderThread(for outgoing # connections) or the singleListenerThread(for incoming connectiosn). - class receiveDataThread(threading.Thread): def __init__(self): @@ -39,7 +37,7 @@ class receiveDataThread(threading.Thread): HOST, port, streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware, + someObjectsOfWhichThisRemoteNodeIsAlreadyAware, selfInitiatedConnections): self.sock = sock self.HOST = HOST @@ -58,7 +56,7 @@ class receiveDataThread(threading.Thread): self.selfInitiatedConnections[streamNumber][self] = 0 self.ackDataThatWeHaveYetToSend = [ ] # When we receive a message bound for us, we store the acknowledgement that we need to send (the ackdata) here until we are done processing all other data received from this peer. - self.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware + self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware def run(self): shared.printLock.acquire() @@ -101,7 +99,7 @@ class receiveDataThread(threading.Thread): print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err shared.printLock.release() try: - del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ + del shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ self.HOST] except: pass @@ -111,14 +109,14 @@ class receiveDataThread(threading.Thread): shared.printLock.release() def processData(self): - # if bitmessagemain.verbose >= 3: + # if shared.verbose >= 3: # shared.printLock.acquire() # print 'self.data is currently ', repr(self.data) # shared.printLock.release() if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length return if self.data[0:4] != '\xe9\xbe\xb4\xd9': - if bitmessagemain.verbose >= 1: + if shared.verbose >= 1: shared.printLock.acquire() print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) shared.printLock.release() @@ -183,8 +181,8 @@ class receiveDataThread(threading.Thread): shared.printLock.release() del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ objectHash] - elif bitmessagemain.isInSqlInventory(objectHash): - if bitmessagemain.verbose >= 3: + elif shared.isInSqlInventory(objectHash): + if shared.verbose >= 3: shared.printLock.acquire() print 'Inventory (SQL on disk) already has object listed in inv message.' shared.printLock.release() @@ -199,7 +197,7 @@ class receiveDataThread(threading.Thread): print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) shared.printLock.release() try: - del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ + del shared.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: pass @@ -209,7 +207,7 @@ class receiveDataThread(threading.Thread): print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) shared.printLock.release() try: - del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ + del shared.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: pass @@ -217,7 +215,7 @@ class receiveDataThread(threading.Thread): shared.printLock.acquire() print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) shared.printLock.release() - numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] = len( + shared.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: self.data = self.ackDataThatWeHaveYetToSend.pop() @@ -285,8 +283,8 @@ class receiveDataThread(threading.Thread): shared.sqlLock.acquire() # Select all hashes which are younger than two days old and in this # stream. - t = (int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers, int( - time.time()) - lengthOfTimeToHoldOnToAllPubkeys, self.streamNumber) + t = (int(time.time()) - shared.maximumAgeOfObjectsThatIAdvertiseToOthers, int( + time.time()) - shared.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) @@ -295,14 +293,14 @@ class receiveDataThread(threading.Thread): bigInvList = {} for row in queryreturn: hash, = row - if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: + if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: 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.objectsOfWhichThisRemoteNodeIsAlreadyAware: + if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: objectType, streamNumber, payload, receivedTime = storedValue - if streamNumber == self.streamNumber and receivedTime > int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers: + if streamNumber == self.streamNumber and receivedTime > int(time.time()) - shared.maximumAgeOfObjectsThatIAdvertiseToOthers: bigInvList[hash] = 0 numberOfObjectsInInvMessage = 0 payload = '' @@ -360,7 +358,7 @@ class receiveDataThread(threading.Thread): if embeddedTime > (int(time.time()) + 10800): # prevent funny business print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.' return - if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): + if embeddedTime < (int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept): print 'The embedded time in this broadcast message is too old. Ignoring message.' return if len(data) < 180: @@ -384,7 +382,7 @@ class receiveDataThread(threading.Thread): print 'We have already received this broadcast object. Ignoring.' shared.inventoryLock.release() return - elif bitmessagemain.isInSqlInventory(self.inventoryHash): + elif shared.isInSqlInventory(self.inventoryHash): print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.' shared.inventoryLock.release() return @@ -749,7 +747,7 @@ class receiveDataThread(threading.Thread): if embeddedTime > int(time.time()) + 10800: print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime return - if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: + if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept: print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime return streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint( @@ -764,7 +762,7 @@ class receiveDataThread(threading.Thread): print 'We have already received this msg message. Ignoring.' shared.inventoryLock.release() return - elif bitmessagemain.isInSqlInventory(self.inventoryHash): + elif shared.isInSqlInventory(self.inventoryHash): print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.' shared.inventoryLock.release() return @@ -808,11 +806,11 @@ class receiveDataThread(threading.Thread): def processmsg(self, readPosition, encryptedData): initialDecryptionSuccessful = False # Let's check whether this is a message acknowledgement bound for us. - if encryptedData[readPosition:] in bitmessagemain.ackdataForWhichImWatching: + if encryptedData[readPosition:] in shared.ackdataForWhichImWatching: shared.printLock.acquire() print 'This msg IS an acknowledgement bound for me.' shared.printLock.release() - del bitmessagemain.ackdataForWhichImWatching[encryptedData[readPosition:]] + del shared.ackdataForWhichImWatching[encryptedData[readPosition:]] t = ('ackreceived', encryptedData[readPosition:]) shared.sqlLock.acquire() shared.sqlSubmitQueue.put( @@ -821,13 +819,13 @@ class receiveDataThread(threading.Thread): shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], bitmessagemain.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], tr.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode( time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8'))))) return else: shared.printLock.acquire() print 'This was NOT an acknowledgement bound for me.' - # print 'bitmessagemain.ackdataForWhichImWatching', bitmessagemain.ackdataForWhichImWatching + # print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching shared.printLock.release() # This is not an acknowledgement bound for me. See if it is a message @@ -1076,14 +1074,14 @@ class receiveDataThread(threading.Thread): # Display timing data timeRequiredToAttemptToDecryptMessage = time.time( ) - self.messageProcessingStartTime - bitmessagemain.successfullyDecryptMessageTimings.append( + shared.successfullyDecryptMessageTimings.append( timeRequiredToAttemptToDecryptMessage) sum = 0 - for item in bitmessagemain.successfullyDecryptMessageTimings: + for item in shared.successfullyDecryptMessageTimings: sum += item shared.printLock.acquire() print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage - print 'Average time for all message decryption successes since startup:', sum / len(bitmessagemain.successfullyDecryptMessageTimings) + print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings) shared.printLock.release() def isAckDataValid(self, ackData): @@ -1111,9 +1109,9 @@ class receiveDataThread(threading.Thread): return '[' + mailingListName + '] ' + subject def possibleNewPubkey(self, toRipe): - if toRipe in neededPubkeys: + if toRipe in shared.neededPubkeys: print 'We have been awaiting the arrival of this pubkey.' - del neededPubkeys[toRipe] + del shared.neededPubkeys[toRipe] t = (toRipe,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put( @@ -1149,7 +1147,7 @@ class receiveDataThread(threading.Thread): else: readPosition += 4 - if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys: + if embeddedTime < int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys: shared.printLock.acquire() print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime shared.printLock.release() @@ -1175,7 +1173,7 @@ class receiveDataThread(threading.Thread): print 'We have already received this pubkey. Ignoring it.' shared.inventoryLock.release() return - elif bitmessagemain.isInSqlInventory(inventoryHash): + elif shared.isInSqlInventory(inventoryHash): print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.' shared.inventoryLock.release() return @@ -1371,7 +1369,7 @@ class receiveDataThread(threading.Thread): if embeddedTime > int(time.time()) + 10800: print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime return - if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: + if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept: print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime return requestedAddressVersionNumber, addressVersionLength = decodeVarint( @@ -1390,7 +1388,7 @@ class receiveDataThread(threading.Thread): print 'We have already received this getpubkey request. Ignoring it.' shared.inventoryLock.release() return - elif bitmessagemain.isInSqlInventory(inventoryHash): + elif shared.isInSqlInventory(inventoryHash): print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.' shared.inventoryLock.release() return @@ -1430,7 +1428,7 @@ class receiveDataThread(threading.Thread): shared.myAddressesByHash[requestedHash], 'lastpubkeysendtime')) except: lastPubkeySendTime = 0 - if lastPubkeySendTime < time.time() - lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago + if lastPubkeySendTime < time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago shared.printLock.acquire() 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() @@ -1452,11 +1450,11 @@ class receiveDataThread(threading.Thread): # We have received an inv message def recinv(self, data): totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = 0 # ..from all peers, counting duplicates seperately (because they take up memory) - if len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) > 0: - for key, value in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer.items(): + if len(shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) > 0: + for key, value in shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer.items(): totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave += value shared.printLock.acquire() - print 'number of keys(hosts) in numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) + print 'number of keys(hosts) in shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) print 'totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = ', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave shared.printLock.release() numberOfItemsInInv, lengthOfVarint = decodeVarint(data[:10]) @@ -1472,13 +1470,13 @@ 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.' shared.printLock.release() return - self.objectsOfWhichThisRemoteNodeIsAlreadyAware[ + self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[ data[lengthOfVarint:32 + lengthOfVarint]] = 0 if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: shared.printLock.acquire() print 'Inventory (in memory) has inventory item already.' shared.printLock.release() - elif bitmessagemain.isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): + elif shared.isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): print 'Inventory (SQL on disk) has inventory item already.' else: self.sendgetdata(data[lengthOfVarint:32 + lengthOfVarint]) @@ -1491,11 +1489,11 @@ 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.' shared.printLock.release() break - self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[ + self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[data[ lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0 self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0 - numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ + shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ self.HOST] = len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) # Send a getdata message to our peer to request the object with the given @@ -1602,7 +1600,7 @@ class receiveDataThread(threading.Thread): numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint( data[:10]) - if bitmessagemain.verbose >= 1: + if shared.verbose >= 1: shared.printLock.acquire() print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' shared.printLock.release() @@ -1845,7 +1843,7 @@ class receiveDataThread(threading.Thread): datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] datatosend = datatosend + payload - if bitmessagemain.verbose >= 1: + if shared.verbose >= 1: shared.printLock.acquire() print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' shared.printLock.release() @@ -1895,7 +1893,7 @@ class receiveDataThread(threading.Thread): # print 'addrsInMyStream.items()', addrsInMyStream.items() for HOST, value in addrsInMyStream.items(): PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time @@ -1907,7 +1905,7 @@ class receiveDataThread(threading.Thread): payload += pack('>H', PORT) # remote port for HOST, value in addrsInChildStreamLeft.items(): PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time @@ -1919,7 +1917,7 @@ class receiveDataThread(threading.Thread): payload += pack('>H', PORT) # remote port for HOST, value in addrsInChildStreamRight.items(): PORT, timeLastReceivedMessageFromThisNode = value - if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. + if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time @@ -1937,7 +1935,7 @@ class receiveDataThread(threading.Thread): datatosend = datatosend + payload try: self.sock.sendall(datatosend) - if bitmessagemain.verbose >= 1: + if shared.verbose >= 1: shared.printLock.acquire() print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' shared.printLock.release() @@ -1991,7 +1989,7 @@ class receiveDataThread(threading.Thread): if not self.initiatedConnection: shared.broadcastToSendDataQueues(( 0, 'setStreamNumber', (self.HOST, self.streamNumber))) - if data[72:80] == bitmessagemain.eightBytesOfRandomDataUsedToDetectConnectionsToSelf: + if data[72:80] == shared.eightBytesOfRandomDataUsedToDetectConnectionsToSelf: shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) shared.printLock.acquire() print 'Closing connection to myself: ', self.HOST @@ -2018,7 +2016,7 @@ class receiveDataThread(threading.Thread): print 'Sending version message' shared.printLock.release() try: - self.sock.sendall(bitmessagemain.assembleVersionMessage( + self.sock.sendall(shared.assembleVersionMessage( self.HOST, self.PORT, self.streamNumber)) except Exception as err: # if not 'Bad file descriptor' in err: diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index 1e3528dd..c1992067 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -8,7 +8,7 @@ import random import sys import socket -import bitmessagemain +#import bitmessagemain # Every connection to a peer has a sendDataThread (and also a # receiveDataThread). @@ -29,7 +29,7 @@ class sendDataThread(threading.Thread): HOST, PORT, streamNumber, - objectsOfWhichThisRemoteNodeIsAlreadyAware): + someObjectsOfWhichThisRemoteNodeIsAlreadyAware): self.sock = sock self.HOST = HOST self.PORT = PORT @@ -38,13 +38,13 @@ class sendDataThread(threading.Thread): 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.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware shared.printLock.acquire() print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber shared.printLock.release() def sendVersionMessage(self): - datatosend = bitmessagemain.assembleVersionMessage( + datatosend = shared.assembleVersionMessage( self.HOST, self.PORT, self.streamNumber) # the IP and port of the remote host, and my streamNumber. shared.printLock.acquire() @@ -123,7 +123,7 @@ class sendDataThread(threading.Thread): print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST break elif command == 'sendinv': - if data not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: + if data not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: payload = '\x01' + data 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' @@ -147,6 +147,7 @@ class sendDataThread(threading.Thread): print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.HOST break 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): # Send out a pong message to keep the connection alive. shared.printLock.acquire() diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index f04a5507..5b77fdd4 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -1,8 +1,6 @@ import threading import shared import time -from bitmessagemain import lengthOfTimeToLeaveObjectsInInventory, lengthOfTimeToHoldOnToAllPubkeys, maximumAgeOfAnObjectThatIAmWillingToAccept, maximumAgeOfObjectsThatIAdvertiseToOthers, maximumAgeOfNodesThatIAdvertiseToOthers,\ - neededPubkeys import sys '''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. @@ -58,15 +56,15 @@ class singleCleaner(threading.Thread): shared.sqlLock.acquire() # inventory (clears pubkeys after 28 days and everything else # after 2 days and 12 hours) - t = (int(time.time()) - lengthOfTimeToLeaveObjectsInInventory, int( - time.time()) - lengthOfTimeToHoldOnToAllPubkeys) + t = (int(time.time()) - shared.lengthOfTimeToLeaveObjectsInInventory, int( + time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys) shared.sqlSubmitQueue.put( '''DELETE FROM inventory WHERE (receivedtime'pubkey') OR (receivedtime (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))): + if int(time.time()) - lastactiontime > (shared.maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))): print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.' 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 shared.neededPubkeys[ + toripe] # We need to take this entry out of the shared.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: pass @@ -107,7 +105,7 @@ class singleCleaner(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.workerQueue.put(('sendmessage', '')) else: # status == msgsent - if int(time.time()) - lastactiontime > (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (msgretrynumber))): + if int(time.time()) - lastactiontime > (shared.maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (msgretrynumber))): 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) diff --git a/src/class_singleListener.py b/src/class_singleListener.py index 12f954a4..fff351bf 100644 --- a/src/class_singleListener.py +++ b/src/class_singleListener.py @@ -1,8 +1,6 @@ import threading import shared import socket -import Queue - from class_sendDataThread import * from class_receiveDataThread import * @@ -64,18 +62,18 @@ class singleListener(threading.Thread): shared.printLock.release() a.close() a, (HOST, PORT) = sock.accept() - objectsOfWhichThisRemoteNodeIsAlreadyAware = {} + someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory. a.settimeout(20) sd = sendDataThread() sd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware) + a, HOST, PORT, -1, someObjectsOfWhichThisRemoteNodeIsAlreadyAware) sd.start() rd = receiveDataThread() rd.daemon = True # close the main program even if there are threads left rd.setup( - a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) + a, HOST, PORT, -1, someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) rd.start() shared.printLock.acquire() diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index e0d54c37..8b659247 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -1,15 +1,13 @@ import threading import shared import time -from time import strftime, localtime, gmtime import random from addresses import * -import bitmessagemain import highlevelcrypto import proofofwork -from bitmessagemain import neededPubkeys, encryptedBroadcastSwitchoverTime import sys from class_addressGenerator import pointMult +import tr # This thread, of which there is only one, does the heavy lifting: # calculating POWs. @@ -32,7 +30,7 @@ class singleWorker(threading.Thread): toripe, = row neededPubkeys[toripe] = 0 - # Initialize the bitmessagemain.ackdataForWhichImWatching data structure using data + # Initialize the shared.ackdataForWhichImWatching data structure using data # from the sql database. shared.sqlLock.acquire() shared.sqlSubmitQueue.put( @@ -43,7 +41,7 @@ class singleWorker(threading.Thread): for row in queryreturn: ackdata, = row print 'Watching for ackdata', ackdata.encode('hex') - bitmessagemain.ackdataForWhichImWatching[ackdata] = 0 + shared.ackdataForWhichImWatching[ackdata] = 0 shared.sqlLock.acquire() shared.sqlSubmitQueue.put( @@ -262,7 +260,7 @@ class singleWorker(threading.Thread): fromaddress, subject, body, ackdata = row status, addressVersionNumber, streamNumber, ripe = decodeAddress( fromaddress) - if addressVersionNumber == 2 and int(time.time()) < encryptedBroadcastSwitchoverTime: + """if addressVersionNumber == 2 and int(time.time()) < shared.encryptedBroadcastSwitchoverTime: # We need to convert our private keys to public keys in order # to include them. try: @@ -272,7 +270,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, tr.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -307,7 +305,7 @@ class singleWorker(threading.Thread): payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) print '(For broadcast message) Doing proof of work...' shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send broadcast...")))) + ackdata, tr.translateText("MainWindow", "Doing work necessary to send broadcast...")))) initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce @@ -322,7 +320,7 @@ class singleWorker(threading.Thread): shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Broadcast sent on %1").arg(unicode( + 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'))))) # Update the status of the message in the 'sent' table to have @@ -335,8 +333,8 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put(t) queryreturn = shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') - shared.sqlLock.release() - elif addressVersionNumber == 3 or int(time.time()) > encryptedBroadcastSwitchoverTime: + shared.sqlLock.release()""" + if addressVersionNumber == 2 or addressVersionNumber == 3: # We need to convert our private keys to public keys in order # to include them. try: @@ -346,7 +344,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, tr.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -394,7 +392,7 @@ class singleWorker(threading.Thread): payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) print '(For broadcast message) Doing proof of work...' shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send broadcast...")))) + ackdata, tr.translateText("MainWindow", "Doing work necessary to send broadcast...")))) initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce @@ -409,7 +407,7 @@ class singleWorker(threading.Thread): shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Broadcast sent on %1").arg(unicode( + 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'))))) # Update the status of the message in the 'sent' table to have @@ -467,7 +465,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, bitmessagemain.translateText("MainWindow",'Encryption key was requested earlier.')))) + toripe, tr.translateText("MainWindow",'Encryption key was requested earlier.')))) else: # We have not yet sent a request for the pubkey t = (toaddress,) @@ -479,7 +477,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, bitmessagemain.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + toripe, tr.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) self.requestPubKey(toaddress) shared.sqlLock.acquire() # Get all messages that are ready to be sent, and also all messages @@ -521,16 +519,16 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - toripe, bitmessagemain.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) + toripe, tr.translateText("MainWindow",'Sending a request for the recipient\'s encryption key.')))) self.requestPubKey(toaddress) continue - bitmessagemain.ackdataForWhichImWatching[ackdata] = 0 + shared.ackdataForWhichImWatching[ackdata] = 0 toStatus, toAddressVersionNumber, toStreamNumber, toHash = decodeAddress( toaddress) fromStatus, fromAddressVersionNumber, fromStreamNumber, fromHash = decodeAddress( fromaddress) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Looking up the receiver\'s public key")))) + ackdata, tr.translateText("MainWindow", "Looking up the receiver\'s public key")))) shared.printLock.acquire() print 'Found a message in our database that needs to be sent with this pubkey.' print 'First 150 characters of message:', repr(message[:150]) @@ -593,7 +591,7 @@ class singleWorker(threading.Thread): requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) + ackdata, tr.translateText("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this.")))) elif toAddressVersionNumber == 3: requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint( pubkeyPayload[readPosition:readPosition + 10]) @@ -605,7 +603,7 @@ class singleWorker(threading.Thread): requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr.translateText("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float( requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes))))) 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): @@ -619,7 +617,7 @@ class singleWorker(threading.Thread): shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr.translateText("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do.").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float( requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes)).arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) continue @@ -640,7 +638,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, tr.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -686,7 +684,7 @@ class singleWorker(threading.Thread): fromaddress, 'privencryptionkey') except: shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( - ackdata, bitmessagemain.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) + ackdata, tr.translateText("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file.")))) continue privSigningKeyHex = shared.decodeWalletImportFormat( @@ -743,7 +741,7 @@ class singleWorker(threading.Thread): queryreturn = shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() - shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,bitmessagemain.translateText("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) + shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr.translateText("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8'))))) continue encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) @@ -766,7 +764,7 @@ class singleWorker(threading.Thread): objectType = 'msg' shared.inventory[inventoryHash] = ( objectType, toStreamNumber, encryptedPayload, int(time.time())) - shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, bitmessagemain.translateText("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(unicode( + shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr.translateText("MainWindow", "Message sent. Waiting on acknowledgement. Sent on %1").arg(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') shared.broadcastToSendDataQueues(( @@ -804,7 +802,7 @@ class singleWorker(threading.Thread): statusbar = 'Doing the computations necessary to request the recipient\'s public key.' shared.UISignalQueue.put(('updateStatusBar', statusbar)) shared.UISignalQueue.put(('updateSentItemStatusByHash', ( - ripe, bitmessagemain.translateText("MainWindow",'Doing work necessary to request encryption key.')))) + ripe, tr.translateText("MainWindow",'Doing work necessary to request encryption key.')))) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) initialHash = hashlib.sha512(payload).digest() @@ -832,8 +830,8 @@ class singleWorker(threading.Thread): shared.sqlLock.release() shared.UISignalQueue.put(( - 'updateStatusBar', bitmessagemain.translateText("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) - shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, bitmessagemain.translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( + 'updateStatusBar', tr.translateText("MainWindow",'Broacasting the public key request. This program will auto-retry if they are offline.'))) + shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, tr.translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode( strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime): diff --git a/src/shared.py b/src/shared.py index b225012c..95be2a94 100644 --- a/src/shared.py +++ b/src/shared.py @@ -1,4 +1,12 @@ softwareVersion = '0.3.3-2' +verbose = 1 +maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # Equals two days and 12 hours. +lengthOfTimeToLeaveObjectsInInventory = 237600 # Equals two days and 18 hours. This should be longer than maximumAgeOfAnObjectThatIAmWillingToAccept so that we don't process messages twice. +lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time. +maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 # Equals two days and 12 hours +maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours +useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the normal network, you won't be able to send or sometimes receive messages. + import threading import sys @@ -9,6 +17,10 @@ import pickle import os import time import ConfigParser +import socket +import random +import highlevelcrypto +import shared config = ConfigParser.SafeConfigParser() myECCryptorObjects = {} @@ -31,11 +43,74 @@ appdata = '' #holds the location of the application data storage directory statusIconColor = 'red' connectedHostsList = {} #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice. shutdown = 0 #Set to 1 by the doCleanShutdown function. Used to tell the proof of work worker threads to exit. +alreadyAttemptedConnectionsList = { +} # This is a list of nodes to which we have already attempted a connection +alreadyAttemptedConnectionsListLock = threading.Lock() +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 = {} +neededPubkeys = {} +eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack( + '>Q', random.randrange(1, 18446744073709551615)) +successfullyDecryptMessageTimings = [ + ] # A list of the amounts of time it took to successfully decrypt msg messages +apiAddressGeneratorReturnQueue = Queue.Queue( + ) # The address generator thread uses this queue to get information back to the API thread. +ackdataForWhichImWatching = {} #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. networkDefaultPayloadLengthExtraBytes = 14000 #To make sending short messages a little more difficult, this value is added to the payload length for use in calculating the proof of work target. + + +def isInSqlInventory(hash): + t = (hash,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put('''select hash from inventory where hash=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + if queryreturn == []: + return False + else: + return True + +def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): + payload = '' + payload += pack('>L', 2) # protocol version. + payload += pack('>q', 1) # bitflags of the services I offer. + 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 += '\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('>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 += pack('>H', shared.config.getint( + 'bitmessagesettings', 'port')) # my external IPv6 and port + + random.seed() + payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf + userAgent = '/PyBitmessage:' + shared.softwareVersion + \ + '/' # 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 += encodeVarint( + 1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection. + payload += encodeVarint(myStreamNumber) + + datatosend = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. + datatosend = datatosend + 'version\x00\x00\x00\x00\x00' # version command + datatosend = datatosend + pack('>L', len(payload)) # payload length + datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] + return datatosend + payload + def lookupAppdataFolder(): APPNAME = "PyBitmessage" from os import path, environ diff --git a/src/tr.py b/src/tr.py new file mode 100644 index 00000000..1f3ef9b8 --- /dev/null +++ b/src/tr.py @@ -0,0 +1,30 @@ +import shared + +# This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions. +class translateClass: + def __init__(self, context, text): + self.context = context + self.text = text + def arg(self,argument): + if '%' in self.text: + return translateClass(self.context, self.text.replace('%','',1)) # This doesn't actually do anything with the arguments because we don't have a UI in which to display this information anyway. + else: + return self.text + +def _translate(context, text): + return translateText(context, text) + +def translateText(context, text): + if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): + try: + from PyQt4 import QtCore, QtGui + 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 'Error message:', err + os._exit(0) + return QtGui.QApplication.translate(context, text) + else: + if '%' in text: + return translateClass(context, text.replace('%','',1)) + else: + return text \ No newline at end of file From 436fced04b6361ef246a12cc32502284439e256d Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 16:18:18 -0400 Subject: [PATCH 41/93] neededPubkeys data structure now in shared module --- src/class_singleWorker.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 8b659247..6da251b2 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -28,7 +28,7 @@ class singleWorker(threading.Thread): shared.sqlLock.release() for row in queryreturn: toripe, = row - neededPubkeys[toripe] = 0 + shared.neededPubkeys[toripe] = 0 # Initialize the shared.ackdataForWhichImWatching data structure using data # from the sql database. @@ -75,9 +75,9 @@ class singleWorker(threading.Thread): self.doPOWForMyV3Pubkey(data) """elif command == 'newpubkey': toAddressVersion,toStreamNumber,toRipe = data - if toRipe in neededPubkeys: + if toRipe in shared.neededPubkeys: print 'We have been awaiting the arrival of this pubkey.' - del neededPubkeys[toRipe] + del shared.neededPubkeys[toRipe] t = (toRipe,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') @@ -454,7 +454,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() else: # We don't have the needed pubkey. Set the status to 'awaitingpubkey' and request it if we haven't already - if toripe in neededPubkeys: + if toripe in shared.neededPubkeys: # We already sent a request for the pubkey t = (toaddress,) shared.sqlLock.acquire() @@ -503,7 +503,7 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put((toripe,)) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() - if queryreturn == [] and toripe not in neededPubkeys: + if queryreturn == [] and toripe not in shared.neededPubkeys: # We no longer have the needed pubkey and we haven't requested # it. shared.printLock.acquire() @@ -789,7 +789,7 @@ class singleWorker(threading.Thread): toAddress) + '. Please report this error to Atheros.') shared.printLock.release() return - neededPubkeys[ripe] = 0 + shared.neededPubkeys[ripe] = 0 payload = pack('>Q', (int(time.time()) + random.randrange( -300, 300))) # the current time plus or minus five minutes. payload += encodeVarint(addressVersionNumber) From dacd9aa9250f0f0f38fb23b7f6c9ca1a94a0e1a5 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 16:25:31 -0400 Subject: [PATCH 42/93] Add strftime import --- src/class_singleWorker.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 6da251b2..13cceb9e 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -1,6 +1,7 @@ import threading import shared import time +from time import strftime, localtime, gmtime import random from addresses import * import highlevelcrypto From 5a7d86cca921fbbc6aa3c623c699ddb84ea5fc8f Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 16:57:19 -0400 Subject: [PATCH 43/93] Fix edge-case bug in possibleNewPubkey function --- src/class_receiveDataThread.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 3d658255..46dfeeae 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -1115,7 +1115,7 @@ class receiveDataThread(threading.Thread): t = (toRipe,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put( - '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') + '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''') shared.sqlSubmitQueue.put(t) shared.sqlReturnQueue.get() shared.sqlSubmitQueue.put('commit') From acb8b51e00e5226921aed568b3d9c047cc818050 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 17:00:35 -0400 Subject: [PATCH 44/93] sock.sendall errors need-not go to stderr --- src/class_receiveDataThread.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 46dfeeae..0c12f8f6 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -243,7 +243,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() def recverack(self): @@ -334,7 +334,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # We have received a broadcast message @@ -1513,7 +1513,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # We have received a getdata request from our peer @@ -1583,7 +1583,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # Send an inv message with just one hash to all of our peers @@ -1942,7 +1942,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # We have received a version message @@ -2021,7 +2021,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # Sends a verack message @@ -2035,7 +2035,7 @@ class receiveDataThread(threading.Thread): except Exception as err: # if not 'Bad file descriptor' in err: shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) + print 'sock.sendall error:', err shared.printLock.release() # cf # 83 From 3204c6b833902b1296ade01b1e35b468f5ebc60d Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 17:29:04 -0400 Subject: [PATCH 45/93] added new variable: doTimingAttackMitigation --- src/class_receiveDataThread.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 0c12f8f6..544dbb82 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -1,3 +1,5 @@ +doTimingAttackMitigation = False + import time import threading import shared @@ -413,7 +415,7 @@ class receiveDataThread(threading.Thread): sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.messageProcessingStartTime) - if sleepTime > 0: + if sleepTime > 0 and doTimingAttackMitigation: shared.printLock.acquire() print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' shared.printLock.release() @@ -792,7 +794,7 @@ class receiveDataThread(threading.Thread): sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.messageProcessingStartTime) - if sleepTime > 0: + if sleepTime > 0 and doTimingAttackMitigation: shared.printLock.acquire() print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' shared.printLock.release() @@ -1190,7 +1192,7 @@ class receiveDataThread(threading.Thread): lengthOfTimeWeShouldUseToProcessThisMessage = .2 sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.pubkeyProcessingStartTime) - if sleepTime > 0: + if sleepTime > 0 and doTimingAttackMitigation: shared.printLock.acquire() print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' shared.printLock.release() @@ -1428,7 +1430,7 @@ class receiveDataThread(threading.Thread): shared.myAddressesByHash[requestedHash], 'lastpubkeysendtime')) except: lastPubkeySendTime = 0 - if lastPubkeySendTime < time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago + if lastPubkeySendTime < time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was at least 28 days ago... shared.printLock.acquire() 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() From 61ab0013aa584686bc835752b88ce1a1c9a5e691 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 17:29:15 -0400 Subject: [PATCH 46/93] added new variable: doTimingAttackMitigation --- src/class_receiveDataThread.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 544dbb82..e5293fe8 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -1,4 +1,4 @@ -doTimingAttackMitigation = False +doTimingAttackMitigation = True import time import threading From 5bb339c0fedcbff2e905ffa6d6a43f4997ca53c9 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 24 Jun 2013 23:41:20 -0400 Subject: [PATCH 47/93] apiAddressGeneratorReturnQueue is now in the shared module --- src/bitmessagemain.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 63f1f8f1..80198ab9 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -187,11 +187,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): unicode(label, 'utf-8') except: return 'API Error 0017: Label is not valid UTF-8 data.' - apiAddressGeneratorReturnQueue.queue.clear() + shared.apiAddressGeneratorReturnQueue.queue.clear() streamNumberForAddress = 1 shared.addressGeneratorQueue.put(( 'createRandomAddress', 3, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes)) - return apiAddressGeneratorReturnQueue.get() + return shared.apiAddressGeneratorReturnQueue.get() elif method == 'createDeterministicAddresses': if len(params) == 0: return 'API Error 0000: I need parameters!' @@ -264,13 +264,13 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): return 'API Error 0004: Why would you ask me to generate 0 addresses for you?' if numberOfAddresses > 999: 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() + shared.apiAddressGeneratorReturnQueue.queue.clear() print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.' shared.addressGeneratorQueue.put( ('createDeterministicAddresses', addressVersionNumber, streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes)) data = '{"addresses":[' - queueReturn = apiAddressGeneratorReturnQueue.get() + queueReturn = shared.apiAddressGeneratorReturnQueue.get() for item in queueReturn: if len(data) > 20: data += ',' @@ -290,12 +290,12 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): return 'API Error 0002: The address version number currently must be 3. ' + addressVersionNumber + ' isn\'t supported.' if streamNumber != 1: return 'API Error 0003: The stream number must be 1. Others aren\'t supported.' - apiAddressGeneratorReturnQueue.queue.clear() + shared.apiAddressGeneratorReturnQueue.queue.clear() print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.' shared.addressGeneratorQueue.put( ('getDeterministicAddress', addressVersionNumber, streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe)) - return apiAddressGeneratorReturnQueue.get() + return shared.apiAddressGeneratorReturnQueue.get() elif method == 'getAllInboxMessages': shared.sqlLock.acquire() shared.sqlSubmitQueue.put( From b6c1467d80b318c9f36c9ad437c25b6c1fe01609 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Tue, 25 Jun 2013 16:26:12 -0400 Subject: [PATCH 48/93] added missing imports --- src/bitmessagemain.py | 1 + src/bitmessageqt/__init__.py | 34 +++++++++++++++++----------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 35babf8c..74f48d1a 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -15,6 +15,7 @@ import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdo from SimpleXMLRPCServer import * import json import singleton +import os # Classes from class_sqlThread import * diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index a99503a6..e11b537a 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -3,23 +3,6 @@ try: except: pass -try: - from PyQt4 import QtCore, QtGui - from PyQt4.QtCore import * - from PyQt4.QtGui import * -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 it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\' (without quotes).' - print 'Error message:', err - sys.exit() - -try: - _encoding = QtGui.QApplication.UnicodeUTF8 -except AttributeError: - print 'QtGui.QApplication.UnicodeUTF8 error:', err - -def _translate(context, text): - return QtGui.QApplication.translate(context, text) - withMessagingMenu = False try: from gi.repository import MessagingMenu @@ -47,6 +30,23 @@ from pyelliptic.openssl import OpenSSL import pickle import platform +try: + from PyQt4 import QtCore, QtGui + from PyQt4.QtCore import * + from PyQt4.QtGui import * +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 it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\' (without quotes).' + print 'Error message:', err + sys.exit() + +try: + _encoding = QtGui.QApplication.UnicodeUTF8 +except AttributeError: + print 'QtGui.QApplication.UnicodeUTF8 error:', err + +def _translate(context, text): + return QtGui.QApplication.translate(context, text) + class MyForm(QtGui.QMainWindow): From 8bd00dc730b277a3541c133f42da40696ede0718 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Tue, 25 Jun 2013 17:14:44 -0400 Subject: [PATCH 49/93] added newchandialog.py --- src/bitmessageqt/__init__.py | 10 ++ src/bitmessageqt/newchandialog.py | 99 ++++++++++++++ src/bitmessageqt/newchandialog.ui | 181 ++++++++++++++++++++++++++ src/translations/bitmessage_fr_BE.pro | 43 +++--- 4 files changed, 317 insertions(+), 16 deletions(-) create mode 100644 src/bitmessageqt/newchandialog.py create mode 100644 src/bitmessageqt/newchandialog.ui diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index e11b537a..ce477836 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2844,6 +2844,16 @@ class NewAddressDialog(QtGui.QDialog): self.ui.groupBoxDeterministic.setHidden(True) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) +class NewChanDialog(QtGui.QDialog): + + def __init__(self, parent): + QtGui.QWidget.__init__(self, parent) + self.ui = Ui_NewChanDialog() + self.ui.setupUi(self) + self.parent = parent + self.ui.groupBoxCreateChan.setHidden(True) + QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) + class iconGlossaryDialog(QtGui.QDialog): diff --git a/src/bitmessageqt/newchandialog.py b/src/bitmessageqt/newchandialog.py new file mode 100644 index 00000000..5c5e11f2 --- /dev/null +++ b/src/bitmessageqt/newchandialog.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'newchandialog.ui' +# +# Created: Tue Jun 25 17:03:01 2013 +# by: PyQt4 UI code generator 4.10.2 +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore, QtGui + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + def _fromUtf8(s): + return s + +try: + _encoding = QtGui.QApplication.UnicodeUTF8 + def _translate(context, text, disambig): + return QtGui.QApplication.translate(context, text, disambig, _encoding) +except AttributeError: + def _translate(context, text, disambig): + return QtGui.QApplication.translate(context, text, disambig) + +class Ui_NewChanDialog(object): + def setupUi(self, NewChanDialog): + NewChanDialog.setObjectName(_fromUtf8("NewChanDialog")) + NewChanDialog.resize(447, 441) + self.formLayout = QtGui.QFormLayout(NewChanDialog) + self.formLayout.setObjectName(_fromUtf8("formLayout")) + self.radioButtonCreateChan = QtGui.QRadioButton(NewChanDialog) + self.radioButtonCreateChan.setObjectName(_fromUtf8("radioButtonCreateChan")) + self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.radioButtonCreateChan) + self.radioButtonJoinChan = QtGui.QRadioButton(NewChanDialog) + self.radioButtonJoinChan.setChecked(True) + self.radioButtonJoinChan.setObjectName(_fromUtf8("radioButtonJoinChan")) + self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.radioButtonJoinChan) + self.groupBoxJoinChan = QtGui.QGroupBox(NewChanDialog) + self.groupBoxJoinChan.setObjectName(_fromUtf8("groupBoxJoinChan")) + self.gridLayout_2 = QtGui.QGridLayout(self.groupBoxJoinChan) + self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) + self.label = QtGui.QLabel(self.groupBoxJoinChan) + self.label.setWordWrap(True) + self.label.setObjectName(_fromUtf8("label")) + self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1) + self.label_2 = QtGui.QLabel(self.groupBoxJoinChan) + self.label_2.setObjectName(_fromUtf8("label_2")) + self.gridLayout_2.addWidget(self.label_2, 1, 0, 1, 1) + self.lineEditChanNameJoin = QtGui.QLineEdit(self.groupBoxJoinChan) + self.lineEditChanNameJoin.setObjectName(_fromUtf8("lineEditChanNameJoin")) + self.gridLayout_2.addWidget(self.lineEditChanNameJoin, 2, 0, 1, 1) + self.label_3 = QtGui.QLabel(self.groupBoxJoinChan) + self.label_3.setObjectName(_fromUtf8("label_3")) + self.gridLayout_2.addWidget(self.label_3, 3, 0, 1, 1) + self.lineEditChanBitmessageAddress = QtGui.QLineEdit(self.groupBoxJoinChan) + self.lineEditChanBitmessageAddress.setObjectName(_fromUtf8("lineEditChanBitmessageAddress")) + self.gridLayout_2.addWidget(self.lineEditChanBitmessageAddress, 4, 0, 1, 1) + self.formLayout.setWidget(3, QtGui.QFormLayout.SpanningRole, self.groupBoxJoinChan) + self.groupBoxCreateChan = QtGui.QGroupBox(NewChanDialog) + self.groupBoxCreateChan.setObjectName(_fromUtf8("groupBoxCreateChan")) + self.gridLayout = QtGui.QGridLayout(self.groupBoxCreateChan) + self.gridLayout.setObjectName(_fromUtf8("gridLayout")) + self.label_4 = QtGui.QLabel(self.groupBoxCreateChan) + self.label_4.setWordWrap(True) + self.label_4.setObjectName(_fromUtf8("label_4")) + self.gridLayout.addWidget(self.label_4, 0, 0, 1, 1) + self.label_5 = QtGui.QLabel(self.groupBoxCreateChan) + self.label_5.setObjectName(_fromUtf8("label_5")) + self.gridLayout.addWidget(self.label_5, 1, 0, 1, 1) + self.lineEditChanNameCreate = QtGui.QLineEdit(self.groupBoxCreateChan) + self.lineEditChanNameCreate.setObjectName(_fromUtf8("lineEditChanNameCreate")) + self.gridLayout.addWidget(self.lineEditChanNameCreate, 2, 0, 1, 1) + self.formLayout.setWidget(2, QtGui.QFormLayout.SpanningRole, self.groupBoxCreateChan) + self.buttonBox = QtGui.QDialogButtonBox(NewChanDialog) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) + self.buttonBox.setObjectName(_fromUtf8("buttonBox")) + self.formLayout.setWidget(4, QtGui.QFormLayout.FieldRole, self.buttonBox) + + self.retranslateUi(NewChanDialog) + QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), NewChanDialog.accept) + QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), NewChanDialog.reject) + QtCore.QObject.connect(self.radioButtonJoinChan, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.groupBoxJoinChan.setShown) + QtCore.QObject.connect(self.radioButtonCreateChan, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.groupBoxCreateChan.setShown) + QtCore.QMetaObject.connectSlotsByName(NewChanDialog) + + def retranslateUi(self, NewChanDialog): + NewChanDialog.setWindowTitle(_translate("NewChanDialog", "Dialog", None)) + self.radioButtonCreateChan.setText(_translate("NewChanDialog", "Create a new chan", None)) + self.radioButtonJoinChan.setText(_translate("NewChanDialog", "Join a chan", None)) + self.groupBoxJoinChan.setTitle(_translate("NewChanDialog", "Join a chan", None)) + self.label.setText(_translate("NewChanDialog", "

A chan is a set of encryption keys that is shared by a group of people. The keys and bitmessage address used by a chan is generated from a human-friendly word or phrase (the chan name).

Chans are experimental and are unmoderatable.

", None)) + self.label_2.setText(_translate("NewChanDialog", "Chan name:", None)) + self.label_3.setText(_translate("NewChanDialog", "Chan bitmessage address:", None)) + self.groupBoxCreateChan.setTitle(_translate("NewChanDialog", "Create a chan", None)) + self.label_4.setText(_translate("NewChanDialog", "Enter a name for your chan. If you choose a sufficiently complex chan name (like a strong and unique passphrase) and none of your friends share it publicly then the chan will be secure and private.", None)) + self.label_5.setText(_translate("NewChanDialog", "Chan name:", None)) + diff --git a/src/bitmessageqt/newchandialog.ui b/src/bitmessageqt/newchandialog.ui new file mode 100644 index 00000000..2e6e4657 --- /dev/null +++ b/src/bitmessageqt/newchandialog.ui @@ -0,0 +1,181 @@ + + + NewChanDialog + + + + 0 + 0 + 447 + 441 + + + + Dialog + + + + + + Create a new chan + + + + + + + Join a chan + + + true + + + + + + + Join a chan + + + + + + <html><head/><body><p>A chan is a set of encryption keys that is shared by a group of people. The keys and bitmessage address used by a chan is generated from a human-friendly word or phrase (the chan name).</p><p>Chans are experimental and are unmoderatable.</p></body></html> + + + true + + + + + + + Chan name: + + + + + + + + + + Chan bitmessage address: + + + + + + + + + + + + + Create a chan + + + + + + Enter a name for your chan. If you choose a sufficiently complex chan name (like a strong and unique passphrase) and none of your friends share it publicly then the chan will be secure and private. + + + true + + + + + + + Chan name: + + + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + NewChanDialog + accept() + + + 428 + 454 + + + 157 + 274 + + + + + buttonBox + rejected() + NewChanDialog + reject() + + + 430 + 460 + + + 286 + 274 + + + + + radioButtonJoinChan + toggled(bool) + groupBoxJoinChan + setShown(bool) + + + 74 + 49 + + + 96 + 227 + + + + + radioButtonCreateChan + toggled(bool) + groupBoxCreateChan + setShown(bool) + + + 72 + 28 + + + 65 + 92 + + + + + diff --git a/src/translations/bitmessage_fr_BE.pro b/src/translations/bitmessage_fr_BE.pro index 7b0a8814..d86fdc4d 100644 --- a/src/translations/bitmessage_fr_BE.pro +++ b/src/translations/bitmessage_fr_BE.pro @@ -1,21 +1,32 @@ -SOURCES = ../about.py\ - ../addresses.py\ - ../bitmessage_icons_rc.py\ +SOURCES = ../addresses.py\ ../bitmessagemain.py\ + ../class_addressGenerator.py\ + ../class_outgoingSynSender.py\ + ../class_receiveDataThread.py\ + ../class_sendDataThread.py\ + ../class_singleCleaner.py\ + ../class_singleListener.py\ + ../class_singleWorker.py\ + ../class_sqlThread.py\ + ../helper_bitcoin.py\ + ../helper_bootstrap.py\ + ../helper_generic.py\ + ../helper_inbox.py\ + ../helper_sent.py\ + ../helper_startup.py\ + ../shared.py ../bitmessageqt/__init__.py\ - ../bitmessageui.py\ - ../defaultKnownNodes.py\ - ../help.py\ - ../highlevelcrypto.py\ - ../iconglossary.py\ - ../newaddressdialog.py\ - ../newsubscriptiondialog.py\ - ../proofofwork.py\ - ../regenerateaddresses.py\ - ../settings.py\ - ../shared.py\ - ../singleton.py\ - ../specialaddressbehavior.py + ../bitmessageqt/about.py\ + ../bitmessageqt/bitmessageui.py\ + ../bitmessageqt/help.py\ + ../bitmessageqt/iconglossary.py\ + ../bitmessageqt/newaddressdialog.py\ + ../bitmessageqt/newchandialog.py\ + ../bitmessageqt/newsubscriptiondialog.py\ + ../bitmessageqt/regenerateaddresses.py\ + ../bitmessageqt/settings.py\ + ../bitmessageqt/specialaddressbehavior.py + TRANSLATIONS = bitmessage_fr_BE.ts From 84035772f2a1280d923a09bc61510785893368dc Mon Sep 17 00:00:00 2001 From: Gregor Robinson Date: Tue, 25 Jun 2013 21:28:06 +0000 Subject: [PATCH 50/93] Rename files with spaces in names. These filenames are technically allowed, but aren't that fun. --- src/{api client.py => api_client.py} | 0 src/{messages.dat reader.py => message_data_reader.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename src/{api client.py => api_client.py} (100%) rename src/{messages.dat reader.py => message_data_reader.py} (100%) diff --git a/src/api client.py b/src/api_client.py similarity index 100% rename from src/api client.py rename to src/api_client.py diff --git a/src/messages.dat reader.py b/src/message_data_reader.py similarity index 100% rename from src/messages.dat reader.py rename to src/message_data_reader.py From ad5517b41b4b21b7127e8a41e94efa587c7c50e6 Mon Sep 17 00:00:00 2001 From: Carlos Killpack Date: Wed, 26 Jun 2013 03:11:32 -0600 Subject: [PATCH 51/93] Fixed issue #157: Use $XDG_CONFIG_HOME --- src/shared.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/shared.py b/src/shared.py index 5dc6964b..22c3b9f6 100644 --- a/src/shared.py +++ b/src/shared.py @@ -124,7 +124,18 @@ def lookupAppdataFolder(): elif 'win32' in sys.platform or 'win64' in sys.platform: dataFolder = path.join(environ['APPDATA'], APPNAME) + '\\' else: - dataFolder = path.expanduser(path.join("~", "." + APPNAME + "/")) + from shutil import move + try: + dataFolder = path.join(environ["XDG_CONFIG_HOME"], APPNAME) + except KeyError: + dataFolder = path.join(environ["HOME"], ".config", APPNAME) + # Migrate existing data to the proper location if this is an existing install + try: + print "Moving data folder to ~/.config/%s" % APPNAME + move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) + dataFolder = dataFolder + '/' + except IOError: + dataFolder = dataFolder + '/' return dataFolder def isAddressInMyAddressBook(address): From 0b08fe6bad9fea63c6fe50ba6af82f04e896f8e5 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Wed, 26 Jun 2013 11:55:33 -0400 Subject: [PATCH 52/93] Some initial coding work for chans --- src/bitmessagemain.py | 5 ----- src/class_addressGenerator.py | 36 ++++++++++++++++++++++++----------- src/helper_startup.py | 30 ++++++++++++++--------------- 3 files changed, 40 insertions(+), 31 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 74f48d1a..c4c2b6db 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -706,11 +706,6 @@ if __name__ == "__main__": signal.signal(signal.SIGINT, helper_generic.signal_handler) # signal.signal(signal.SIGINT, signal.SIG_DFL) - # Check the Major version, the first element in the array - if sqlite3.sqlite_version_info[0] < 3: - 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) - helper_startup.loadConfig() helper_bootstrap.knownNodes() diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 38c7d5b9..08c7773e 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -21,7 +21,15 @@ class addressGenerator(threading.Thread): queueValue = shared.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 - if len(queueValue) == 7: + if queueValue[0] == 'createChan': + command, addressVersionNumber, streamNumber, label, deterministicPassphrase = queueValue + eighteenByteRipe = False + numberOfAddressesToMake = 1 + elif queueValue[0] == 'joinChan': + command, chanAddress, label, deterministicPassphrase = queueValue + eighteenByteRipe = False + numberOfAddressesToMake = 1 + elif len(queueValue) == 7: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue elif len(queueValue) == 9: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue @@ -122,7 +130,7 @@ class addressGenerator(threading.Thread): shared.workerQueue.put(( 'doPOWForMyV3Pubkey', ripe.digest())) - elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress': + elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress' or command == 'createChan' or command == 'joinChan': 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.') @@ -176,7 +184,17 @@ class addressGenerator(threading.Thread): print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.' address = encodeAddress(3, streamNumber, ripe.digest()) - if command == 'createDeterministicAddresses': + saveAddressToDisk = True + # If we are joining an existing chan, let us check to make sure it matches the provided Bitmessage address + if command == 'joinChan': + if address != chanAddress: + #todo: show an error message in the UI + shared.apiAddressGeneratorReturnQueue.put('API Error 0018: Chan name does not match address.') + saveAddressToDisk = False + if command == 'getDeterministicAddress': + saveAddressToDisk = False + + if saveAddressToDisk: # 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 privSigningKey = '\x80' + potentialPrivSigningKey @@ -198,6 +216,8 @@ class addressGenerator(threading.Thread): shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') + if command == 'joinChan' or command == 'createChan': + shared.config.set(address, 'chan', 'true') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( @@ -213,18 +233,11 @@ class addressGenerator(threading.Thread): label, address, str(streamNumber)))) listOfNewAddressesToSendOutThroughTheAPI.append( address) - # 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.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( potentialPrivEncryptionKey.encode('hex')) shared.myAddressesByHash[ ripe.digest()] = address + #todo: don't send out pubkey if dealing with a chan; save in pubkeys table instead. shared.workerQueue.put(( 'doPOWForMyV3Pubkey', ripe.digest())) except: @@ -242,6 +255,7 @@ class addressGenerator(threading.Thread): # shared.reloadMyAddressHashes() elif command == 'getDeterministicAddress': shared.apiAddressGeneratorReturnQueue.put(address) + #todo: return things to the API if createChan or joinChan assuming saveAddressToDisk else: raise Exception( "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command) diff --git a/src/helper_startup.py b/src/helper_startup.py index df27fd6e..08f8d48a 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -77,18 +77,18 @@ def loadConfig(): with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) - 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', 'socksproxytype', 'none') - shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') - shared.config.set('bitmessagesettings', 'socksport', '9050') - shared.config.set('bitmessagesettings', 'socksauthentication', 'false') - shared.config.set('bitmessagesettings', 'socksusername', '') - shared.config.set('bitmessagesettings', 'sockspassword', '') - shared.config.set('bitmessagesettings', 'keysencrypted', 'false') - shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) + 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', 'socksproxytype', 'none') + shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') + shared.config.set('bitmessagesettings', 'socksport', '9050') + shared.config.set('bitmessagesettings', 'socksauthentication', 'false') + shared.config.set('bitmessagesettings', 'socksusername', '') + shared.config.set('bitmessagesettings', 'sockspassword', '') + shared.config.set('bitmessagesettings', 'keysencrypted', 'false') + shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) From 1657dfec2410833ca6c37e0b81d35e4cb87c8812 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Wed, 26 Jun 2013 13:35:53 -0400 Subject: [PATCH 53/93] Move code related to settings file upgrade --- src/class_sqlThread.py | 18 +++++++++++++++++- src/helper_startup.py | 16 ---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 5848e868..ebe6a7ff 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -69,6 +69,22 @@ class sqlThread(threading.Thread): 'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err)) os._exit(0) + if shared.config.getint('bitmessagesettings', 'settingsversion') == 1: + shared.config.set('bitmessagesettings', 'settingsversion', '2') + # 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', 'sockshostname', 'localhost') + shared.config.set('bitmessagesettings', 'socksport', '9050') + shared.config.set('bitmessagesettings', 'socksauthentication', 'false') + shared.config.set('bitmessagesettings', 'socksusername', '') + shared.config.set('bitmessagesettings', 'sockspassword', '') + shared.config.set('bitmessagesettings', 'keysencrypted', 'false') + shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') + with open(shared.appdata + 'keys.dat', 'wb') as configfile: + shared.config.write(configfile) + # 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: @@ -158,7 +174,7 @@ class sqlThread(threading.Thread): self.cur.execute( ''' VACUUM ''') # After code refactoring, the possible status values for sent messages - # as changed. + # have changed. self.cur.execute( '''update sent set status='doingmsgpow' where status='doingpow' ''') self.cur.execute( diff --git a/src/helper_startup.py b/src/helper_startup.py index 08f8d48a..e6590b0e 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -76,19 +76,3 @@ def loadConfig(): os.makedirs(shared.appdata) with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) - - 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', 'socksproxytype', 'none') - shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') - shared.config.set('bitmessagesettings', 'socksport', '9050') - shared.config.set('bitmessagesettings', 'socksauthentication', 'false') - shared.config.set('bitmessagesettings', 'socksusername', '') - shared.config.set('bitmessagesettings', 'sockspassword', '') - shared.config.set('bitmessagesettings', 'keysencrypted', 'false') - shared.config.set('bitmessagesettings', 'messagesencrypted', 'false') - with open(shared.appdata + 'keys.dat', 'wb') as configfile: - shared.config.write(configfile) From 0f8b9f97bd74edc012cfc9ad561e848558c3550c Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Wed, 26 Jun 2013 14:22:13 -0400 Subject: [PATCH 54/93] Increment version number to 0.3.4 --- Makefile | 4 +++- debian.sh | 4 ++-- src/build_osx.py | 2 +- src/shared.py | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 9de3e463..ac602a3f 100755 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ APP=pybitmessage -VERSION=0.3.3-2 +VERSION=0.3.4 DEST_SHARE=$(DESTDIR)/usr/share DEST_APP=$(DEST_SHARE)/$(APP) @@ -18,6 +18,7 @@ install: mkdir -m 755 -p $(DEST_APP)/pyelliptic mkdir -m 755 -p $(DEST_APP)/socks mkdir -m 755 -p $(DEST_APP)/bitmessageqt + mkdir -m 755 -p $(DEST_APP)/translations mkdir -m 755 -p $(DEST_SHARE)/pixmaps mkdir -m 755 -p $(DEST_SHARE)/icons mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor @@ -35,6 +36,7 @@ install: install -m 644 src/pyelliptic/*.py $(DEST_APP)/pyelliptic install -m 644 src/socks/*.py $(DEST_APP)/socks install -m 644 src/bitmessageqt/*.py $(DEST_APP)/bitmessageqt + install -m 644 src/translations/*.qm $(DEST_APP)/translations install -m 755 debian/pybm $(DESTDIR)/usr/bin/$(APP) install -m 644 desktop/$(APP).desktop $(DEST_SHARE)/applications/$(APP).desktop diff --git a/debian.sh b/debian.sh index 42817522..4b9410ed 100755 --- a/debian.sh +++ b/debian.sh @@ -7,8 +7,8 @@ #!/bin/bash APP=pybitmessage -PREV_VERSION=0.3.2 -VERSION=0.3.3-2 +PREV_VERSION=0.3.3 +VERSION=0.3.4 ARCH_TYPE=all #update version numbers automatically - so you don't have to diff --git a/src/build_osx.py b/src/build_osx.py index db004769..aac551b9 100644 --- a/src/build_osx.py +++ b/src/build_osx.py @@ -14,7 +14,7 @@ from setuptools import setup # @UnresolvedImport name = "Bitmessage" mainscript = 'bitmessagemain.py' -version = "0.3.3" +version = "0.3.4" if sys.platform == 'darwin': extra_options = dict( diff --git a/src/shared.py b/src/shared.py index 22c3b9f6..4b3ef73b 100644 --- a/src/shared.py +++ b/src/shared.py @@ -1,4 +1,4 @@ -softwareVersion = '0.3.3-2' +softwareVersion = '0.3.4' verbose = 1 maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # Equals two days and 12 hours. lengthOfTimeToLeaveObjectsInInventory = 237600 # Equals two days and 18 hours. This should be longer than maximumAgeOfAnObjectThatIAmWillingToAccept so that we don't process messages twice. From 6facca4cb39d2fe2653b0078b95b470e6a961721 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 15:25:31 +0800 Subject: [PATCH 55/93] Added a class for background working --- src/class_bgWorker.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/class_bgWorker.py diff --git a/src/class_bgWorker.py b/src/class_bgWorker.py new file mode 100644 index 00000000..9e374ee6 --- /dev/null +++ b/src/class_bgWorker.py @@ -0,0 +1,38 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# cody by linker.lin@me.com + +__author__ = 'linkerlin' + + +import threading +import Queue +import time + +class BGWorker(threading.Thread): + def __init__(self): + threading.Thread.__init__(self) + self.q = Queue.Queue() + + def post(self,job): + self.q.put(job) + + def run(self): + while 1: + job=None + try: + job = self.q.get(block=True) + if job: + job() + except Exception as ex: + print "Error,job exception:",ex.message,type(ex) + time.sleep(0.05) + else: + #print "job: ", job, " done" + pass + finally: + time.sleep(0.05) + +bgworker = BGWorker() +bgworker.setDaemon(True) +bgworker.start() From e47d35769b4e4fe5b893789c9bbc44156fe40c18 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 15:36:34 +0800 Subject: [PATCH 56/93] renamed class BGWorker to bgWorker --- src/class_bgWorker.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/class_bgWorker.py b/src/class_bgWorker.py index 9e374ee6..c163bcc0 100644 --- a/src/class_bgWorker.py +++ b/src/class_bgWorker.py @@ -9,7 +9,7 @@ import threading import Queue import time -class BGWorker(threading.Thread): +class bgWorker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.q = Queue.Queue() @@ -33,6 +33,6 @@ class BGWorker(threading.Thread): finally: time.sleep(0.05) -bgworker = BGWorker() +bgworker = bgWorker() bgworker.setDaemon(True) bgworker.start() From 0aa7efab340cbf8f98c3c4b861ce485ff5adc968 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 15:43:24 +0800 Subject: [PATCH 57/93] renamed class BGWorker to bgWorker --- src/bitmessagemain.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index c4c2b6db..6e88e3bd 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -10,6 +10,12 @@ # The software version variable is now held in shared.py #import ctypes +try: + from gevent import monkey + monkey.patch_all() +except ImportError as ex: + print "cannot find gevent" + import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. # The next 3 are used for the API from SimpleXMLRPCServer import * From 5df22b4181dea5da0d401c9b2ffd965a29d1c973 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 16:45:03 +0800 Subject: [PATCH 58/93] Made gevent happy with PyQt. --- src/bitmessageqt/__init__.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index ce477836..49395ed9 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2927,7 +2927,22 @@ class UISignaler(QThread): else: sys.stderr.write( 'Command sent to UISignaler not recognized: %s\n' % command) +try: + import gevent +except ImportError as ex: + print "cannot find gevent" +else: + def mainloop(app): + while True: + app.processEvents() + while app.hasPendingEvents(): + app.processEvents() + gevent.sleep() + gevent.sleep() # don't appear to get here but cooperate again + def testprint(): + #print 'this is running' + gevent.spawn_later(1, testprint) def run(): app = QtGui.QApplication(sys.argv) @@ -2946,5 +2961,8 @@ def run(): myapp.appIndicatorInit(app) myapp.ubuntuMessagingMenuInit() myapp.notifierInit() - - sys.exit(app.exec_()) + if gevent is None: + sys.exit(app.exec_()) + else: + gevent.joinall([gevent.spawn(testprint), gevent.spawn(mainloop, app)]) + print 'done' From 3eea6d6a884b26d40fe8f3badd7fdff9bbd02361 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 17:28:17 +0800 Subject: [PATCH 59/93] Removed a blank line. --- src/bitmessageqt/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 49395ed9..d0b71155 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2939,7 +2939,6 @@ else: app.processEvents() gevent.sleep() gevent.sleep() # don't appear to get here but cooperate again - def testprint(): #print 'this is running' gevent.spawn_later(1, testprint) From e8eaf65f07a7cdc5cce52acafe19d98214f46c4a Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 17:48:32 +0800 Subject: [PATCH 60/93] Sleep more , save more. --- src/bitmessageqt/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index d0b71155..64cc8419 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2938,7 +2938,7 @@ else: while app.hasPendingEvents(): app.processEvents() gevent.sleep() - gevent.sleep() # don't appear to get here but cooperate again + gevent.sleep(0.01) # don't appear to get here but cooperate again def testprint(): #print 'this is running' gevent.spawn_later(1, testprint) From 9fa90ccc3fc937884a3cf659b5534b9d891fc280 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 17:50:43 +0800 Subject: [PATCH 61/93] Sleep more , save more. --- src/bitmessageqt/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 64cc8419..cc65a602 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2937,7 +2937,7 @@ else: app.processEvents() while app.hasPendingEvents(): app.processEvents() - gevent.sleep() + gevent.sleep(0.01) gevent.sleep(0.01) # don't appear to get here but cooperate again def testprint(): #print 'this is running' From 284b3a24f7e3b88afee218de3cddecdab925b7e5 Mon Sep 17 00:00:00 2001 From: "miao.lin" Date: Fri, 28 Jun 2013 18:22:10 +0800 Subject: [PATCH 62/93] Put setDaemon inside init. --- src/class_bgWorker.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class_bgWorker.py b/src/class_bgWorker.py index c163bcc0..c01e26ef 100644 --- a/src/class_bgWorker.py +++ b/src/class_bgWorker.py @@ -13,6 +13,7 @@ class bgWorker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.q = Queue.Queue() + self.setDaemon(True) def post(self,job): self.q.put(job) @@ -34,5 +35,4 @@ class bgWorker(threading.Thread): time.sleep(0.05) bgworker = bgWorker() -bgworker.setDaemon(True) bgworker.start() From 80e5adad8ce3924bfa3df247a2623314e2b21785 Mon Sep 17 00:00:00 2001 From: linkerlin Date: Fri, 28 Jun 2013 22:26:31 +0800 Subject: [PATCH 63/93] Made it compatible with gevent 1.0dev version. --- src/bitmessageqt/__init__.py | 102 +++++++++++++++++++---------------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index cc65a602..9d8c7e59 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2875,58 +2875,68 @@ class myTableWidgetItem(QTableWidgetItem): def __lt__(self, other): return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject()) - -class UISignaler(QThread): +from threading import Thread +class UISignaler(Thread,QThread): def __init__(self, parent=None): + Thread.__init__(self, parent) QThread.__init__(self, parent) def run(self): while True: - command, data = shared.UISignalQueue.get() - if command == 'writeNewAddressToTable': - label, address, streamNumber = data - self.emit(SIGNAL( - "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), label, address, str(streamNumber)) - elif command == 'updateStatusBar': - self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"), data) - elif command == 'updateSentItemStatusByHash': - hash, message = data - self.emit(SIGNAL( - "updateSentItemStatusByHash(PyQt_PyObject,PyQt_PyObject)"), hash, message) - elif command == 'updateSentItemStatusByAckdata': - ackData, message = data - self.emit(SIGNAL( - "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), ackData, message) - elif command == 'displayNewInboxMessage': - inventoryHash, toAddress, fromAddress, subject, body = data - self.emit(SIGNAL( - "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), - inventoryHash, toAddress, fromAddress, subject, body) - elif command == 'displayNewSentMessage': - toAddress, fromLabel, fromAddress, subject, message, ackdata = data - self.emit(SIGNAL( - "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), - toAddress, fromLabel, fromAddress, subject, message, ackdata) - elif command == 'updateNetworkStatusTab': - self.emit(SIGNAL("updateNetworkStatusTab()")) - elif command == 'incrementNumberOfMessagesProcessed': - self.emit(SIGNAL("incrementNumberOfMessagesProcessed()")) - elif command == 'incrementNumberOfPubkeysProcessed': - self.emit(SIGNAL("incrementNumberOfPubkeysProcessed()")) - elif command == 'incrementNumberOfBroadcastsProcessed': - self.emit(SIGNAL("incrementNumberOfBroadcastsProcessed()")) - elif command == 'setStatusIcon': - self.emit(SIGNAL("setStatusIcon(PyQt_PyObject)"), data) - elif command == 'rerenderInboxFromLabels': - self.emit(SIGNAL("rerenderInboxFromLabels()")) - elif command == 'rerenderSubscriptions': - self.emit(SIGNAL("rerenderSubscriptions()")) - elif command == 'removeInboxRowByMsgid': - self.emit(SIGNAL("removeInboxRowByMsgid(PyQt_PyObject)"), data) - else: - sys.stderr.write( - 'Command sent to UISignaler not recognized: %s\n' % command) + try: + command, data = shared.UISignalQueue.get() + if command == 'writeNewAddressToTable': + label, address, streamNumber = data + self.emit(SIGNAL( + "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), label, address, str(streamNumber)) + elif command == 'updateStatusBar': + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"), data) + elif command == 'updateSentItemStatusByHash': + hash, message = data + self.emit(SIGNAL( + "updateSentItemStatusByHash(PyQt_PyObject,PyQt_PyObject)"), hash, message) + elif command == 'updateSentItemStatusByAckdata': + ackData, message = data + self.emit(SIGNAL( + "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), ackData, message) + elif command == 'displayNewInboxMessage': + inventoryHash, toAddress, fromAddress, subject, body = data + self.emit(SIGNAL( + "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), + inventoryHash, toAddress, fromAddress, subject, body) + elif command == 'displayNewSentMessage': + toAddress, fromLabel, fromAddress, subject, message, ackdata = data + self.emit(SIGNAL( + "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), + toAddress, fromLabel, fromAddress, subject, message, ackdata) + elif command == 'updateNetworkStatusTab': + self.emit(SIGNAL("updateNetworkStatusTab()")) + elif command == 'incrementNumberOfMessagesProcessed': + self.emit(SIGNAL("incrementNumberOfMessagesProcessed()")) + elif command == 'incrementNumberOfPubkeysProcessed': + self.emit(SIGNAL("incrementNumberOfPubkeysProcessed()")) + elif command == 'incrementNumberOfBroadcastsProcessed': + self.emit(SIGNAL("incrementNumberOfBroadcastsProcessed()")) + elif command == 'setStatusIcon': + self.emit(SIGNAL("setStatusIcon(PyQt_PyObject)"), data) + elif command == 'rerenderInboxFromLabels': + self.emit(SIGNAL("rerenderInboxFromLabels()")) + elif command == 'rerenderSubscriptions': + self.emit(SIGNAL("rerenderSubscriptions()")) + elif command == 'removeInboxRowByMsgid': + self.emit(SIGNAL("removeInboxRowByMsgid(PyQt_PyObject)"), data) + else: + sys.stderr.write( + 'Command sent to UISignaler not recognized: %s\n' % command) + except Exception,ex: + # uncaught exception will block gevent + import traceback + traceback.print_exc() + traceback.print_stack() + print ex + pass + try: import gevent except ImportError as ex: From 935fe33a478276ef1f909054cc1edc51e97aa0d4 Mon Sep 17 00:00:00 2001 From: Carlos Killpack Date: Sat, 29 Jun 2013 10:27:40 -0600 Subject: [PATCH 64/93] Real logging, please incorporate into new and existing code. --- src/debug.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/debug.py diff --git a/src/debug.py b/src/debug.py new file mode 100644 index 00000000..d8033f2d --- /dev/null +++ b/src/debug.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +''' +Logging and debuging facility +============================= + +Levels: + DEBUG Detailed information, typically of interest only when diagnosing problems. + INFO Confirmation that things are working as expected. + WARNING An indication that something unexpected happened, or indicative of some problem in the + near future (e.g. ‘disk space low’). The software is still working as expected. + ERROR Due to a more serious problem, the software has not been able to perform some function. + CRITICAL A serious error, indicating that the program itself may be unable to continue running. + +There are three loggers: `console_only`, `file_only` and `both`. + +Use: `from debug import logger` to import this facility into whatever module you wish to log messages from. + Logging is thread-safe so you don't have to worry about locks, just import and log. +''' +import logging +import logging.config + +# TODO(xj9): Get from a config file. +log_level = 'DEBUG' + +logging.config.dictConfig({ + 'version': 1, + 'formatters': { + 'default': { + 'format': '%(asctime)s - %(levelname)s - %(message)s', + }, + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'formatter': 'default', + 'level': log_level, + 'stream': 'ext://sys.stdout' + }, + 'file': { + 'class': 'logging.handlers.RotatingFileHandler', + 'formatter': 'default', + 'level': log_level, + 'filename': 'bm.log', + 'maxBytes': 1024, + 'backupCount': 0, + } + }, + 'loggers': { + 'console_only': { + 'handlers': ['console'], + }, + 'file_only': { + 'handlers': ['file'], + }, + 'both': { + 'handlers': ['console', 'file'], + }, + }, + 'root': { + 'level': log_level, + 'handlers': ['console'], + }, +}) +# TODO (xj9): Get from a config file. +logger = logging.getLogger('console_only') From 4a84a30fc6509686422a2b491b79164367d8e321 Mon Sep 17 00:00:00 2001 From: Linker Lin Date: Sun, 30 Jun 2013 01:29:35 +0800 Subject: [PATCH 65/93] replace acquire lock by 'with' statement --- src/bitmessagemain.py | 36 +-- src/bitmessageqt/__init__.py | 14 +- src/class_outgoingSynSender.py | 48 +-- src/class_receiveDataThread.py | 571 +++++++++++++++++---------------- src/class_sendDataThread.py | 66 ++-- src/class_singleCleaner.py | 8 +- src/class_singleListener.py | 24 +- src/class_singleWorker.py | 134 ++++---- src/class_sqlThread.py | 34 +- 9 files changed, 468 insertions(+), 467 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 6e88e3bd..1b7dc6ff 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -465,9 +465,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): status, addressVersionNumber, streamNumber, toRipe = decodeAddress( toAddress) if status != 'success': - shared.printLock.acquire() - print 'API Error 0007: Could not decode address:', toAddress, ':', status - shared.printLock.release() + with shared.printLock: + print 'API Error 0007: Could not decode address:', toAddress, ':', status + if status == 'checksumfailed': return 'API Error 0008: Checksum failed for address: ' + toAddress if status == 'invalidcharacters': @@ -482,9 +482,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): status, addressVersionNumber, streamNumber, fromRipe = decodeAddress( fromAddress) if status != 'success': - shared.printLock.acquire() - print 'API Error 0007: Could not decode address:', fromAddress, ':', status - shared.printLock.release() + with shared.printLock: + print 'API Error 0007: Could not decode address:', fromAddress, ':', status + if status == 'checksumfailed': return 'API Error 0008: Checksum failed for address: ' + fromAddress if status == 'invalidcharacters': @@ -547,9 +547,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): status, addressVersionNumber, streamNumber, fromRipe = decodeAddress( fromAddress) if status != 'success': - shared.printLock.acquire() - print 'API Error 0007: Could not decode address:', fromAddress, ':', status - shared.printLock.release() + with shared.printLock: + print 'API Error 0007: Could not decode address:', fromAddress, ':', status + if status == 'checksumfailed': return 'API Error 0008: Checksum failed for address: ' + fromAddress if status == 'invalidcharacters': @@ -618,9 +618,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): status, addressVersionNumber, streamNumber, toRipe = decodeAddress( address) if status != 'success': - shared.printLock.acquire() - print 'API Error 0007: Could not decode address:', address, ':', status - shared.printLock.release() + with shared.printLock: + print 'API Error 0007: Could not decode address:', address, ':', status + if status == 'checksumfailed': return 'API Error 0008: Checksum failed for address: ' + address if status == 'invalidcharacters': @@ -747,9 +747,9 @@ if __name__ == "__main__": except: apiNotifyPath = '' if apiNotifyPath != '': - shared.printLock.acquire() - print 'Trying to call', apiNotifyPath - shared.printLock.release() + with shared.printLock: + print 'Trying to call', apiNotifyPath + call([apiNotifyPath, "startingUp"]) singleAPIThread = singleAPI() singleAPIThread.daemon = True # close the main program even if there are threads left @@ -780,9 +780,9 @@ if __name__ == "__main__": import bitmessageqt bitmessageqt.run() else: - shared.printLock.acquire() - print 'Running as a daemon. You can use Ctrl+C to exit.' - shared.printLock.release() + with shared.printLock: + print 'Running as a daemon. You can use Ctrl+C to exit.' + while True: time.sleep(20) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 9d8c7e59..4eefdbf2 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -1288,9 +1288,9 @@ class MyForm(QtGui.QMainWindow): status, addressVersionNumber, streamNumber, ripe = decodeAddress( toAddress) if status != 'success': - shared.printLock.acquire() - print 'Error: Could not decode', toAddress, ':', status - shared.printLock.release() + with shared.printLock: + print 'Error: Could not decode', toAddress, ':', status + if status == 'missingbm': self.statusBar().showMessage(_translate( "MainWindow", "Error: Bitmessage addresses start with BM- Please check %1").arg(toAddress)) @@ -2621,9 +2621,9 @@ class MyForm(QtGui.QMainWindow): def updateStatusBar(self, data): if data != "": - shared.printLock.acquire() - print 'Status bar:', data - shared.printLock.release() + with shared.printLock: + print 'Status bar:', data + self.statusBar().showMessage(data) @@ -2973,5 +2973,5 @@ def run(): if gevent is None: sys.exit(app.exec_()) else: - gevent.joinall([gevent.spawn(testprint), gevent.spawn(mainloop, app)]) + gevent.joinall([gevent.spawn(testprint), gevent.spawn(mainloop, app), gevent.spawn(mainloop, app), gevent.spawn(mainloop, app), gevent.spawn(mainloop, app), gevent.spawn(mainloop, app)]) print 'done' diff --git a/src/class_outgoingSynSender.py b/src/class_outgoingSynSender.py index d547b3e3..2c4766f4 100644 --- a/src/class_outgoingSynSender.py +++ b/src/class_outgoingSynSender.py @@ -61,15 +61,15 @@ class outgoingSynSender(threading.Thread): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(20) if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2: - shared.printLock.acquire() - print 'Trying an outgoing connection to', HOST, ':', PORT - shared.printLock.release() + with shared.printLock: + print 'Trying an outgoing connection to', HOST, ':', PORT + # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a': if shared.verbose >= 2: - shared.printLock.acquire() - print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT - shared.printLock.release() + with shared.printLock: + print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT + proxytype = socks.PROXY_TYPE_SOCKS4 sockshostname = shared.config.get( 'bitmessagesettings', 'sockshostname') @@ -88,9 +88,9 @@ class outgoingSynSender(threading.Thread): proxytype, sockshostname, socksport, rdns) elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5': if shared.verbose >= 2: - shared.printLock.acquire() - print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT - shared.printLock.release() + with shared.printLock: + print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT + proxytype = socks.PROXY_TYPE_SOCKS5 sockshostname = shared.config.get( 'bitmessagesettings', 'sockshostname') @@ -116,9 +116,9 @@ class outgoingSynSender(threading.Thread): rd.setup(sock, HOST, PORT, self.streamNumber, someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) rd.start() - shared.printLock.acquire() - print self, 'connected to', HOST, 'during an outgoing attempt.' - shared.printLock.release() + with shared.printLock: + print self, 'connected to', HOST, 'during an outgoing attempt.' + sd = sendDataThread() sd.setup(sock, HOST, PORT, self.streamNumber, @@ -128,18 +128,18 @@ class outgoingSynSender(threading.Thread): except socks.GeneralProxyError as err: if shared.verbose >= 2: - shared.printLock.acquire() - print 'Could NOT connect to', HOST, 'during outgoing attempt.', err - shared.printLock.release() + with shared.printLock: + print 'Could NOT connect to', HOST, 'during outgoing attempt.', err + PORT, timeLastSeen = shared.knownNodes[ self.streamNumber][HOST] if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure. shared.knownNodesLock.acquire() del shared.knownNodes[self.streamNumber][HOST] shared.knownNodesLock.release() - shared.printLock.acquire() - print 'deleting ', HOST, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.' - shared.printLock.release() + with shared.printLock: + print 'deleting ', HOST, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.' + except socks.Socks5AuthError as err: shared.UISignalQueue.put(( 'updateStatusBar', tr.translateText( @@ -154,18 +154,18 @@ class outgoingSynSender(threading.Thread): print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err) else: if shared.verbose >= 1: - shared.printLock.acquire() - print 'Could NOT connect to', HOST, 'during outgoing attempt.', err - shared.printLock.release() + with shared.printLock: + print 'Could NOT connect to', HOST, 'during outgoing attempt.', err + PORT, timeLastSeen = shared.knownNodes[ self.streamNumber][HOST] if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure. shared.knownNodesLock.acquire() del shared.knownNodes[self.streamNumber][HOST] shared.knownNodesLock.release() - shared.printLock.acquire() - print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.' - shared.printLock.release() + with shared.printLock: + print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.' + except Exception as err: sys.stderr.write( 'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: ') diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index e5293fe8..5abc7b43 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -61,67 +61,67 @@ class receiveDataThread(threading.Thread): self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware def run(self): - shared.printLock.acquire() - print 'ID of the receiveDataThread is', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) - shared.printLock.release() + with shared.printLock: + print 'ID of the receiveDataThread is', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) + while True: try: self.data += self.sock.recv(4096) except socket.timeout: - shared.printLock.acquire() - print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' - shared.printLock.release() + with shared.printLock: + print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' + break except Exception as err: - shared.printLock.acquire() - print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err - shared.printLock.release() + with shared.printLock: + print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err + break # print 'Received', repr(self.data) if self.data == "": - shared.printLock.acquire() - print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' - shared.printLock.release() + with shared.printLock: + print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' + break else: self.processData() try: del self.selfInitiatedConnections[self.streamNumber][self] - shared.printLock.acquire() - print 'removed self (a receiveDataThread) from selfInitiatedConnections' - shared.printLock.release() + with shared.printLock: + print 'removed self (a receiveDataThread) from selfInitiatedConnections' + except: pass shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) try: del shared.connectedHostsList[self.HOST] except Exception as err: - shared.printLock.acquire() - print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err - shared.printLock.release() + with shared.printLock: + print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err + try: del shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[ self.HOST] except: pass shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) - shared.printLock.acquire() - print 'The size of the connectedHostsList is now:', len(shared.connectedHostsList) - shared.printLock.release() + with shared.printLock: + print 'The size of the connectedHostsList is now:', len(shared.connectedHostsList) + def processData(self): # if shared.verbose >= 3: - # shared.printLock.acquire() - # print 'self.data is currently ', repr(self.data) - # shared.printLock.release() + # with shared.printLock: + # print 'self.data is currently ', repr(self.data) + # if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length return if self.data[0:4] != '\xe9\xbe\xb4\xd9': if shared.verbose >= 1: - shared.printLock.acquire() - print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) - shared.printLock.release() + with shared.printLock: + print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) + self.data = "" return self.payloadLength, = unpack('>L', self.data[16:20]) @@ -142,9 +142,9 @@ class receiveDataThread(threading.Thread): shared.knownNodesLock.release() if self.payloadLength <= 180000000: # If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.) remoteCommand = self.data[4:16] - shared.printLock.acquire() - print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.HOST - shared.printLock.release() + with shared.printLock: + print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.HOST + if remoteCommand == 'version\x00\x00\x00\x00\x00': self.recversion(self.data[24:self.payloadLength + 24]) elif remoteCommand == 'verack\x00\x00\x00\x00\x00\x00': @@ -178,16 +178,16 @@ class receiveDataThread(threading.Thread): objectHash, = random.sample( self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1) if objectHash in shared.inventory: - shared.printLock.acquire() - print 'Inventory (in memory) already has object listed in inv message.' - shared.printLock.release() + with shared.printLock: + print 'Inventory (in memory) already has object listed in inv message.' + del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ objectHash] elif shared.isInSqlInventory(objectHash): if shared.verbose >= 3: - shared.printLock.acquire() - print 'Inventory (SQL on disk) already has object listed in inv message.' - shared.printLock.release() + with shared.printLock: + print 'Inventory (SQL on disk) already has object listed in inv message.' + del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[ objectHash] else: @@ -195,9 +195,9 @@ class receiveDataThread(threading.Thread): 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: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - shared.printLock.release() + with shared.printLock: + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + try: del shared.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. @@ -205,18 +205,18 @@ class receiveDataThread(threading.Thread): pass break if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - shared.printLock.release() + with shared.printLock: + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + try: del shared.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: pass if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: - shared.printLock.acquire() - print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) - shared.printLock.release() + with shared.printLock: + print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) + shared.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: @@ -244,9 +244,9 @@ class receiveDataThread(threading.Thread): '\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: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + def recverack(self): print 'verack received' @@ -264,19 +264,19 @@ class receiveDataThread(threading.Thread): shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[ self.streamNumber][self.HOST] - shared.printLock.acquire() - print 'Connection fully established with', self.HOST, remoteNodeIncomingPort - 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.' - shared.printLock.release() + with shared.printLock: + print 'Connection fully established with', self.HOST, remoteNodeIncomingPort + 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.HOST, remoteNodeIncomingPort)]) # This lets all of our peers know about this new node. self.sendaddr() # This is one large addr message to this one peer. if not self.initiatedConnection and len(shared.connectedHostsList) > 200: - shared.printLock.acquire() - print 'We are connected to too many people. Closing connection.' - shared.printLock.release() + with shared.printLock: + print 'We are connected to too many people. Closing connection.' + shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) return self.sendBigInv() @@ -328,16 +328,16 @@ class receiveDataThread(threading.Thread): headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' headerData += pack('>L', len(payload)) headerData += hashlib.sha512(payload).digest()[:4] - shared.printLock.acquire() - print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' - shared.printLock.release() + with shared.printLock: + print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' + try: self.sock.sendall(headerData + payload) except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # We have received a broadcast message def recbroadcast(self, data): @@ -416,13 +416,13 @@ class receiveDataThread(threading.Thread): sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.messageProcessingStartTime) if sleepTime > 0 and doTimingAttackMitigation: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' + # A broadcast message has a valid time and POW and requires processing. # The recbroadcast function calls this one. @@ -459,9 +459,9 @@ class receiveDataThread(threading.Thread): sendersHash = data[readPosition:readPosition + 20] if sendersHash not in shared.broadcastSendersForWhichImWatching: # Display timing data - shared.printLock.acquire() - print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() + with shared.printLock: + print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime + return # At this point, this message claims to be from sendersHash and # we are interested in it. We still have to hash the public key @@ -524,9 +524,9 @@ class receiveDataThread(threading.Thread): fromAddress = encodeAddress( sendersAddressVersion, sendersStream, ripe.digest()) - shared.printLock.acquire() - print 'fromAddress:', fromAddress - shared.printLock.release() + with shared.printLock: + print 'fromAddress:', fromAddress + if messageEncodingType == 2: bodyPositionIndex = string.find(message, '\nBody:') if bodyPositionIndex > 1: @@ -567,9 +567,9 @@ class receiveDataThread(threading.Thread): call([apiNotifyPath, "newBroadcast"]) # Display timing data - shared.printLock.acquire() - print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() + with shared.printLock: + print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime + if broadcastVersion == 2: cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint( data[readPosition:readPosition + 10]) @@ -587,9 +587,9 @@ class receiveDataThread(threading.Thread): # print 'cryptorObject.decrypt Exception:', err if not initialDecryptionSuccessful: # This is not a broadcast I am interested in. - shared.printLock.acquire() - print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.' + return # At this point this is a broadcast I have decrypted and thus am # interested in. @@ -680,9 +680,9 @@ class receiveDataThread(threading.Thread): fromAddress = encodeAddress( sendersAddressVersion, sendersStream, ripe.digest()) - shared.printLock.acquire() - print 'fromAddress:', fromAddress - shared.printLock.release() + with shared.printLock: + print 'fromAddress:', fromAddress + if messageEncodingType == 2: bodyPositionIndex = string.find(message, '\nBody:') if bodyPositionIndex > 1: @@ -723,9 +723,9 @@ class receiveDataThread(threading.Thread): call([apiNotifyPath, "newBroadcast"]) # Display timing data - shared.printLock.acquire() - print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime - shared.printLock.release() + with shared.printLock: + print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime + # We have received a msg message. def recmsg(self, data): @@ -795,13 +795,13 @@ class receiveDataThread(threading.Thread): sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.messageProcessingStartTime) if sleepTime > 0 and doTimingAttackMitigation: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' + # A msg message has a valid time and POW and requires processing. The # recmsg function calls this one. @@ -809,9 +809,9 @@ class receiveDataThread(threading.Thread): initialDecryptionSuccessful = False # Let's check whether this is a message acknowledgement bound for us. if encryptedData[readPosition:] in shared.ackdataForWhichImWatching: - shared.printLock.acquire() - print 'This msg IS an acknowledgement bound for me.' - shared.printLock.release() + with shared.printLock: + print 'This msg IS an acknowledgement bound for me.' + del shared.ackdataForWhichImWatching[encryptedData[readPosition:]] t = ('ackreceived', encryptedData[readPosition:]) shared.sqlLock.acquire() @@ -825,10 +825,10 @@ class receiveDataThread(threading.Thread): time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8'))))) return else: - shared.printLock.acquire() - print 'This was NOT an acknowledgement bound for me.' + with shared.printLock: + print 'This was NOT an acknowledgement bound for me.' # print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching - 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. @@ -838,16 +838,17 @@ class receiveDataThread(threading.Thread): encryptedData[readPosition:]) toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data. initialDecryptionSuccessful = True - print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') + with shared.printLock: + print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') break except Exception as err: pass # print 'cryptorObject.decrypt Exception:', err if not initialDecryptionSuccessful: # This is not a message bound for me. - shared.printLock.acquire() - print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.' + else: # This is a message bound for me. toAddress = shared.myAddressesByHash[ @@ -896,12 +897,12 @@ class receiveDataThread(threading.Thread): print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use. if toRipe != decryptedData[readPosition:readPosition + 20]: - shared.printLock.acquire() - print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.' - print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html' - print 'your toRipe:', toRipe.encode('hex') - print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex') - shared.printLock.release() + with shared.printLock: + print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.' + print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html' + print 'your toRipe:', toRipe.encode('hex') + print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex') + return readPosition += 20 messageEncodingType, messageEncodingTypeLength = decodeVarint( @@ -932,9 +933,9 @@ class receiveDataThread(threading.Thread): except Exception as err: print 'ECDSA verify failed', err return - shared.printLock.acquire() - print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' - shared.printLock.release() + with shared.printLock: + print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' + # calculate the fromRipe. sha = hashlib.new('sha512') sha.update(pubSigningKey + pubEncryptionKey) @@ -980,9 +981,9 @@ class receiveDataThread(threading.Thread): queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() if queryreturn != []: - shared.printLock.acquire() - print 'Message ignored because address is in blacklist.' - shared.printLock.release() + with shared.printLock: + print 'Message ignored because address is in blacklist.' + blockMessage = True else: # We're using a whitelist t = (fromAddress,) @@ -1081,10 +1082,10 @@ class receiveDataThread(threading.Thread): sum = 0 for item in shared.successfullyDecryptMessageTimings: sum += item - shared.printLock.acquire() - print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage - print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings) - shared.printLock.release() + with shared.printLock: + print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage + print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings) + def isAckDataValid(self, ackData): if len(ackData) < 24: @@ -1124,9 +1125,9 @@ class receiveDataThread(threading.Thread): shared.sqlLock.release() shared.workerQueue.put(('sendmessage', '')) else: - shared.printLock.acquire() - print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') + # We have received a pubkey def recpubkey(self, data): @@ -1150,14 +1151,14 @@ class receiveDataThread(threading.Thread): readPosition += 4 if embeddedTime < int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys: - shared.printLock.acquire() - print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime - shared.printLock.release() + with shared.printLock: + print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime + return if embeddedTime > int(time.time()) + 10800: - shared.printLock.acquire() - print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.' - shared.printLock.release() + with shared.printLock: + print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.' + return addressVersion, varintLength = decodeVarint( data[readPosition:readPosition + 10]) @@ -1193,13 +1194,13 @@ class receiveDataThread(threading.Thread): sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \ (time.time() - self.pubkeyProcessingStartTime) if sleepTime > 0 and doTimingAttackMitigation: - shared.printLock.acquire() - print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' + time.sleep(sleepTime) - shared.printLock.acquire() - print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.' - shared.printLock.release() + with shared.printLock: + print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.' + def processpubkey(self, data): readPosition = 8 # for the nonce @@ -1223,9 +1224,9 @@ class receiveDataThread(threading.Thread): print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.' return if addressVersion >= 4 or addressVersion == 1: - shared.printLock.acquire() - print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.' - shared.printLock.release() + with shared.printLock: + print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.' + return if addressVersion == 2: if len(data) < 146: # sanity check. This is the minimum possible length. @@ -1249,12 +1250,12 @@ class receiveDataThread(threading.Thread): ripeHasher.update(sha.digest()) ripe = ripeHasher.digest() - shared.printLock.acquire() - print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber - print 'ripe', ripe.encode('hex') - print 'publicSigningKey in hex:', publicSigningKey.encode('hex') - print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber + print 'ripe', ripe.encode('hex') + print 'publicSigningKey in hex:', publicSigningKey.encode('hex') + print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') + t = (ripe,) shared.sqlLock.acquire() @@ -1318,12 +1319,12 @@ class receiveDataThread(threading.Thread): ripeHasher.update(sha.digest()) ripe = ripeHasher.digest() - shared.printLock.acquire() - print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber - print 'ripe', ripe.encode('hex') - print 'publicSigningKey in hex:', publicSigningKey.encode('hex') - print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber + print 'ripe', ripe.encode('hex') + print 'publicSigningKey in hex:', publicSigningKey.encode('hex') + print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') + t = (ripe,) shared.sqlLock.acquire() @@ -1420,10 +1421,10 @@ class receiveDataThread(threading.Thread): if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine if decodeAddress(shared.myAddressesByHash[requestedHash])[1] != requestedAddressVersionNumber: - 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') - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + '(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. That shouldn\'t have happened. Ignoring.\n') + return try: lastPubkeySendTime = int(shared.config.get( @@ -1431,9 +1432,9 @@ class receiveDataThread(threading.Thread): except: lastPubkeySendTime = 0 if lastPubkeySendTime < time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was at least 28 days ago... - shared.printLock.acquire() - 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() + with shared.printLock: + print 'Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.' + if requestedAddressVersionNumber == 2: shared.workerQueue.put(( 'doPOWForMyV2Pubkey', requestedHash)) @@ -1441,13 +1442,13 @@ class receiveDataThread(threading.Thread): shared.workerQueue.put(( 'doPOWForMyV3Pubkey', requestedHash)) else: - 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 - shared.printLock.release() + with shared.printLock: + print 'Found getpubkey-requested-hash in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime + else: - shared.printLock.acquire() - print 'This getpubkey request is not for any of my keys.' - shared.printLock.release() + with shared.printLock: + print 'This getpubkey request is not for any of my keys.' + # We have received an inv message def recinv(self, data): @@ -1455,10 +1456,10 @@ class receiveDataThread(threading.Thread): if len(shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) > 0: for key, value in shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer.items(): totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave += value - shared.printLock.acquire() - print 'number of keys(hosts) in shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) - print 'totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = ', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave - shared.printLock.release() + with shared.printLock: + print 'number of keys(hosts) in shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer:', len(shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer) + print 'totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = ', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave + numberOfItemsInInv, lengthOfVarint = decodeVarint(data[:10]) if numberOfItemsInInv > 50000: sys.stderr.write('Too many items in inv message!') @@ -1468,16 +1469,16 @@ class receiveDataThread(threading.Thread): return if numberOfItemsInInv == 1: # we'll just request this data from the person who advertised the object. if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation - shared.printLock.acquire() - 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() + with shared.printLock: + print 'We already have', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.' + return self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[ data[lengthOfVarint:32 + lengthOfVarint]] = 0 if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: - shared.printLock.acquire() - print 'Inventory (in memory) has inventory item already.' - shared.printLock.release() + with shared.printLock: + print 'Inventory (in memory) has inventory item already.' + elif shared.isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): print 'Inventory (SQL on disk) has inventory item already.' else: @@ -1487,9 +1488,9 @@ class receiveDataThread(threading.Thread): for i in range(numberOfItemsInInv): # upon finishing dealing with an incoming message, the receiveDataThread will request a random object from the peer. This way if we get multiple inv messages from multiple peers which list mostly the same objects, we will make getdata requests for different random objects from the various peers. if len(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) == 32: # The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously. if totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave > 200000 and len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 1000: # inv flooding attack mitigation - shared.printLock.acquire() - 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() + with shared.printLock: + 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.' + break self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[data[ lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0 @@ -1501,9 +1502,9 @@ class receiveDataThread(threading.Thread): # Send a getdata message to our peer to request the object with the given # hash def sendgetdata(self, hash): - shared.printLock.acquire() - print 'sending getdata to retrieve object with hash:', hash.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'sending getdata to retrieve object with hash:', hash.encode('hex') + payload = '\x01' + hash headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData += 'getdata\x00\x00\x00\x00\x00' @@ -1514,9 +1515,9 @@ class receiveDataThread(threading.Thread): self.sock.sendall(headerData + payload) except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # We have received a getdata request from our peer def recgetdata(self, data): @@ -1528,9 +1529,9 @@ class receiveDataThread(threading.Thread): for i in xrange(numberOfRequestedInventoryItems): hash = data[lengthOfVarint + ( i * 32):32 + lengthOfVarint + (i * 32)] - shared.printLock.acquire() - print 'received getdata request for item:', hash.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'received getdata request for item:', hash.encode('hex') + # print 'inventory is', shared.inventory if hash in shared.inventory: objectType, streamNumber, payload, receivedTime = shared.inventory[ @@ -1555,24 +1556,24 @@ class receiveDataThread(threading.Thread): def sendData(self, objectType, payload): headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. if objectType == 'pubkey': - shared.printLock.acquire() - print 'sending pubkey' - shared.printLock.release() + with shared.printLock: + print 'sending pubkey' + headerData += 'pubkey\x00\x00\x00\x00\x00\x00' elif objectType == 'getpubkey' or objectType == 'pubkeyrequest': - shared.printLock.acquire() - print 'sending getpubkey' - shared.printLock.release() + with shared.printLock: + print 'sending getpubkey' + headerData += 'getpubkey\x00\x00\x00' elif objectType == 'msg': - shared.printLock.acquire() - print 'sending msg' - shared.printLock.release() + with shared.printLock: + print 'sending msg' + headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' elif objectType == 'broadcast': - shared.printLock.acquire() - print 'sending broadcast' - shared.printLock.release() + with shared.printLock: + print 'sending broadcast' + headerData += 'broadcast\x00\x00\x00' else: sys.stderr.write( @@ -1584,15 +1585,15 @@ class receiveDataThread(threading.Thread): self.sock.sendall(headerData + payload) except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # Send an inv message with just one hash to all of our peers def broadcastinv(self, hash): - shared.printLock.acquire() - print 'broadcasting inv with hash:', hash.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'broadcasting inv with hash:', hash.encode('hex') + shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash)) # We have received an addr message. @@ -1603,9 +1604,9 @@ class receiveDataThread(threading.Thread): data[:10]) if shared.verbose >= 1: - shared.printLock.acquire() - print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' - shared.printLock.release() + with shared.printLock: + print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' + if self.remoteProtocolVersion == 1: if numberOfAddressesIncluded > 1000 or numberOfAddressesIncluded == 0: @@ -1618,25 +1619,25 @@ class receiveDataThread(threading.Thread): 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': - shared.printLock.acquire() - print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) - shared.printLock.release() + with shared.printLock: + print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) + continue except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - shared.printLock.release() + 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[4 + lengthOfNumberOfAddresses + ( 34 * i):8 + lengthOfNumberOfAddresses + (34 * i)]) except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - shared.printLock.release() + 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 @@ -1646,20 +1647,20 @@ class receiveDataThread(threading.Thread): recaddrServices, = unpack('>Q', data[8 + lengthOfNumberOfAddresses + ( 34 * i):16 + lengthOfNumberOfAddresses + (34 * i)]) except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) - shared.printLock.release() + 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[32 + lengthOfNumberOfAddresses + ( 34 * i):34 + lengthOfNumberOfAddresses + (34 * i)]) except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) - shared.printLock.release() + 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 @@ -1708,9 +1709,9 @@ class receiveDataThread(threading.Thread): shared.knownNodesLock.release() self.broadcastaddr( listOfAddressDetailsToBroadcastToPeers) # no longer broadcast - shared.printLock.acquire() - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' - shared.printLock.release() + 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 @@ -1722,25 +1723,25 @@ class receiveDataThread(threading.Thread): 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': - shared.printLock.acquire() - print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) - shared.printLock.release() + with shared.printLock: + print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) + continue except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - shared.printLock.release() + 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - shared.printLock.release() + 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 @@ -1750,20 +1751,20 @@ class receiveDataThread(threading.Thread): recaddrServices, = unpack('>Q', data[12 + lengthOfNumberOfAddresses + ( 38 * i):20 + lengthOfNumberOfAddresses + (38 * i)]) except Exception as err: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) - shared.printLock.release() + 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: - shared.printLock.acquire() - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) - shared.printLock.release() + 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 @@ -1791,9 +1792,9 @@ class receiveDataThread(threading.Thread): shared.knownNodes[recaddrStream][hostFromAddrMessage] = ( recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodesLock.release() - shared.printLock.acquire() - print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream - shared.printLock.release() + with shared.printLock: + print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream + needToWriteKnownNodesToDisk = True hostDetails = ( timeSomeoneElseReceivedMessageFromThisNode, @@ -1817,9 +1818,9 @@ class receiveDataThread(threading.Thread): output.close() shared.knownNodesLock.release() self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) - shared.printLock.acquire() - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' - shared.printLock.release() + 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 @@ -1846,9 +1847,9 @@ class receiveDataThread(threading.Thread): datatosend = datatosend + payload if shared.verbose >= 1: - shared.printLock.acquire() - print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' - shared.printLock.release() + with shared.printLock: + print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' + shared.broadcastToSendDataQueues(( self.streamNumber, 'sendaddr', datatosend)) @@ -1938,14 +1939,14 @@ class receiveDataThread(threading.Thread): try: self.sock.sendall(datatosend) if shared.verbose >= 1: - shared.printLock.acquire() - print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' - shared.printLock.release() + with shared.printLock: + print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' + except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # We have received a version message def recversion(self, data): @@ -1956,9 +1957,9 @@ class receiveDataThread(threading.Thread): self.remoteProtocolVersion, = unpack('>L', data[:4]) if self.remoteProtocolVersion <= 1: shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closing connection to old protocol version 1 node: ', self.HOST - shared.printLock.release() + with shared.printLock: + print 'Closing connection to old protocol version 1 node: ', self.HOST + return # print 'remoteProtocolVersion', self.remoteProtocolVersion self.myExternalIP = socket.inet_ntoa(data[40:44]) @@ -1975,14 +1976,14 @@ class receiveDataThread(threading.Thread): readPosition += lengthOfNumberOfStreamsInVersionMessage self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint( data[readPosition:]) - shared.printLock.acquire() - print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber - shared.printLock.release() + with shared.printLock: + print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber + if self.streamNumber != 1: shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.' - shared.printLock.release() + with shared.printLock: + print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.' + 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. @@ -1993,9 +1994,9 @@ class receiveDataThread(threading.Thread): 0, 'setStreamNumber', (self.HOST, self.streamNumber))) if data[72:80] == shared.eightBytesOfRandomDataUsedToDetectConnectionsToSelf: shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) - shared.printLock.acquire() - print 'Closing connection to myself: ', self.HOST - shared.printLock.release() + with shared.printLock: + print 'Closing connection to myself: ', self.HOST + return shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', ( self.HOST, self.remoteProtocolVersion))) @@ -2014,31 +2015,31 @@ class receiveDataThread(threading.Thread): # Sends a version message def sendversion(self): - shared.printLock.acquire() - print 'Sending version message' - shared.printLock.release() + with shared.printLock: + print 'Sending version message' + try: self.sock.sendall(shared.assembleVersionMessage( self.HOST, self.PORT, self.streamNumber)) except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # Sends a verack message def sendverack(self): - shared.printLock.acquire() - print 'Sending verack' - shared.printLock.release() + with shared.printLock: + print 'Sending verack' + try: self.sock.sendall( '\xE9\xBE\xB4\xD9\x76\x65\x72\x61\x63\x6B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35') except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - print 'sock.sendall error:', err - shared.printLock.release() + with shared.printLock: + print 'sock.sendall error:', err + # cf # 83 # e1 diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index c1992067..dec436e9 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -18,9 +18,9 @@ class sendDataThread(threading.Thread): threading.Thread.__init__(self) self.mailbox = Queue.Queue() shared.sendDataQueues.append(self.mailbox) - shared.printLock.acquire() - print 'The length of sendDataQueues at sendDataThread init is:', len(shared.sendDataQueues) - shared.printLock.release() + with shared.printLock: + print 'The length of sendDataQueues at sendDataThread init is:', len(shared.sendDataQueues) + self.data = '' def setup( @@ -39,48 +39,48 @@ class sendDataThread(threading.Thread): 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.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware - shared.printLock.acquire() - print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber - shared.printLock.release() + with shared.printLock: + print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber + def sendVersionMessage(self): datatosend = shared.assembleVersionMessage( self.HOST, self.PORT, self.streamNumber) # the IP and port of the remote host, and my streamNumber. - shared.printLock.acquire() - print 'Sending version packet: ', repr(datatosend) - shared.printLock.release() + with shared.printLock: + print 'Sending version packet: ', repr(datatosend) + try: self.sock.sendall(datatosend) except Exception as err: # if not 'Bad file descriptor' in err: - shared.printLock.acquire() - sys.stderr.write('sock.sendall error: %s\n' % err) - shared.printLock.release() + with shared.printLock: + sys.stderr.write('sock.sendall error: %s\n' % err) + self.versionSent = 1 def run(self): while True: deststream, command, data = self.mailbox.get() - # shared.printLock.acquire() - # print 'sendDataThread, destream:', deststream, ', Command:', command, ', ID:',id(self), ', HOST:', self.HOST - # shared.printLock.release() + # with shared.printLock: + # print 'sendDataThread, destream:', deststream, ', Command:', command, ', ID:',id(self), ', HOST:', self.HOST + # if deststream == self.streamNumber or deststream == 0: if command == 'shutdown': if data == self.HOST or data == 'all': - shared.printLock.acquire() - print 'sendDataThread (associated with', self.HOST, ') ID:', id(self), 'shutting down now.' - shared.printLock.release() + with shared.printLock: + print 'sendDataThread (associated with', self.HOST, ') ID:', id(self), 'shutting down now.' + try: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() except: pass shared.sendDataQueues.remove(self.mailbox) - shared.printLock.acquire() - print 'len of sendDataQueues', len(shared.sendDataQueues) - shared.printLock.release() + with shared.printLock: + print 'len of sendDataQueues', len(shared.sendDataQueues) + break # When you receive an incoming connection, a sendDataThread is # created even though you don't yet know what stream number the @@ -91,16 +91,16 @@ class sendDataThread(threading.Thread): elif command == 'setStreamNumber': hostInMessage, specifiedStreamNumber = data if hostInMessage == self.HOST: - shared.printLock.acquire() - print 'setting the stream number in the sendData thread (ID:', id(self), ') to', specifiedStreamNumber - shared.printLock.release() + with shared.printLock: + print 'setting the stream number in the sendData thread (ID:', id(self), ') to', specifiedStreamNumber + self.streamNumber = specifiedStreamNumber elif command == 'setRemoteProtocolVersion': hostInMessage, specifiedRemoteProtocolVersion = data if hostInMessage == self.HOST: - shared.printLock.acquire() - print 'setting the remote node\'s protocol version in the sendData thread (ID:', id(self), ') to', specifiedRemoteProtocolVersion - shared.printLock.release() + with shared.printLock: + print 'setting the remote node\'s protocol version in the sendData thread (ID:', id(self), ') to', specifiedRemoteProtocolVersion + self.remoteProtocolVersion = specifiedRemoteProtocolVersion elif command == 'sendaddr': try: @@ -150,9 +150,9 @@ class sendDataThread(threading.Thread): 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): # Send out a pong message to keep the connection alive. - shared.printLock.acquire() - print 'Sending pong to', self.HOST, 'to keep connection alive.' - shared.printLock.release() + with shared.printLock: + print 'Sending pong to', self.HOST, 'to keep connection alive.' + 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') @@ -168,7 +168,7 @@ class sendDataThread(threading.Thread): print 'sendDataThread thread', self, 'ending now. Was connected to', self.HOST break else: - shared.printLock.acquire() - print 'sendDataThread ID:', id(self), 'ignoring command', command, 'because the thread is not in stream', deststream - shared.printLock.release() + with shared.printLock: + print 'sendDataThread ID:', id(self), 'ignoring command', command, 'because the thread is not in stream', deststream + diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 5b77fdd4..6fed68a5 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -78,11 +78,11 @@ class singleCleaner(threading.Thread): queryreturn = shared.sqlReturnQueue.get() for row in queryreturn: if len(row) < 5: - shared.printLock.acquire() - sys.stderr.write( - 'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row)) + with shared.printLock: + sys.stderr.write( + 'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row)) time.sleep(3) - shared.printLock.release() + break toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, pubkeyretrynumber, msgretrynumber = row if status == 'awaitingpubkey': diff --git a/src/class_singleListener.py b/src/class_singleListener.py index fff351bf..58bddf6f 100644 --- a/src/class_singleListener.py +++ b/src/class_singleListener.py @@ -27,9 +27,9 @@ class singleListener(threading.Thread): while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': time.sleep(300) - shared.printLock.acquire() - print 'Listening for incoming connections.' - shared.printLock.release() + with shared.printLock: + print 'Listening for incoming connections.' + HOST = '' # Symbolic name meaning all available interfaces PORT = shared.config.getint('bitmessagesettings', 'port') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -46,9 +46,9 @@ class singleListener(threading.Thread): while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': time.sleep(10) while len(shared.connectedHostsList) > 220: - shared.printLock.acquire() - print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' - shared.printLock.release() + with shared.printLock: + print 'We are connected to too many people. Not accepting further incoming connections for ten seconds.' + time.sleep(10) a, (HOST, PORT) = sock.accept() @@ -57,9 +57,9 @@ class singleListener(threading.Thread): # because the two computers will share the same external IP. This # is here to prevent connection flooding. while HOST in shared.connectedHostsList: - shared.printLock.acquire() - print 'We are already connected to', HOST + '. Ignoring connection.' - shared.printLock.release() + with shared.printLock: + print 'We are already connected to', HOST + '. Ignoring connection.' + a.close() a, (HOST, PORT) = sock.accept() someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory. @@ -76,6 +76,6 @@ class singleListener(threading.Thread): a, HOST, PORT, -1, someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections) rd.start() - shared.printLock.acquire() - print self, 'connected to', HOST, 'during INCOMING request.' - shared.printLock.release() + with shared.printLock: + print self, 'connected to', HOST, 'during INCOMING request.' + diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 13cceb9e..1a0fe149 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -88,14 +88,14 @@ class singleWorker(threading.Thread): shared.sqlLock.release() self.sendMsg() else: - shared.printLock.acquire() - print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') - shared.printLock.release()""" + with shared.printLock: + print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') + """ else: - shared.printLock.acquire() - sys.stderr.write( - 'Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command) - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + 'Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command) + shared.workerQueue.task_done() def doPOWForMyV2Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW @@ -123,10 +123,10 @@ class singleWorker(threading.Thread): privEncryptionKeyBase58 = shared.config.get( myAddress, 'privencryptionkey') except Exception as err: - 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) - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + 'Error within doPOWForMyV2Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err) + return privSigningKeyHex = shared.decodeWalletImportFormat( @@ -162,9 +162,9 @@ class singleWorker(threading.Thread): shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime) - shared.printLock.acquire() - print 'broadcasting inv with hash:', inventoryHash.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'broadcasting inv with hash:', inventoryHash.encode('hex') + shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) shared.UISignalQueue.put(('updateStatusBar', '')) @@ -190,10 +190,10 @@ class singleWorker(threading.Thread): privEncryptionKeyBase58 = shared.config.get( myAddress, 'privencryptionkey') except Exception as err: - 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) - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + 'Error within doPOWForMyV3Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err) + return privSigningKeyHex = shared.decodeWalletImportFormat( @@ -238,9 +238,9 @@ class singleWorker(threading.Thread): shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime) - shared.printLock.acquire() - print 'broadcasting inv with hash:', inventoryHash.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'broadcasting inv with hash:', inventoryHash.encode('hex') + shared.broadcastToSendDataQueues(( streamNumber, 'sendinv', inventoryHash)) shared.UISignalQueue.put(('updateStatusBar', '')) @@ -423,10 +423,10 @@ class singleWorker(threading.Thread): shared.sqlSubmitQueue.put('commit') shared.sqlLock.release() else: - shared.printLock.acquire() - sys.stderr.write( - 'Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n') - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + 'Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n') + def sendMsg(self): # Check to see if there are any messages queued to be sent @@ -507,10 +507,10 @@ class singleWorker(threading.Thread): if queryreturn == [] and toripe not in shared.neededPubkeys: # We no longer have the needed pubkey and we haven't requested # it. - 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')) - shared.printLock.release() + with shared.printLock: + 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')) + t = (toaddress,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put( @@ -530,10 +530,10 @@ class singleWorker(threading.Thread): fromaddress) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', ( ackdata, tr.translateText("MainWindow", "Looking up the receiver\'s public key")))) - shared.printLock.acquire() - print 'Found a message in our database that needs to be sent with this pubkey.' - print 'First 150 characters of message:', repr(message[:150]) - shared.printLock.release() + with shared.printLock: + print 'Found a message in our database that needs to be sent with this pubkey.' + print 'First 150 characters of message:', repr(message[:150]) + # mark the pubkey as 'usedpersonally' so that we don't ever delete # it. @@ -553,10 +553,10 @@ class singleWorker(threading.Thread): queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() if queryreturn == []: - shared.printLock.acquire() - sys.stderr.write( - '(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n') - shared.printLock.release() + with shared.printLock: + sys.stderr.write( + '(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n') + return for row in queryreturn: pubkeyPayload, = row @@ -746,19 +746,19 @@ class singleWorker(threading.Thread): continue encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) - 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 - shared.printLock.release() + with shared.printLock: + print '(For msg message) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes + powStartTime = time.time() initialHash = hashlib.sha512(encryptedPayload).digest() trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print '(For msg message) Found proof of work', trialValue, 'Nonce:', nonce - try: - print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' - except: - pass - shared.printLock.release() + with shared.printLock: + print '(For msg message) Found proof of work', trialValue, 'Nonce:', nonce + try: + print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' + except: + pass + encryptedPayload = pack('>Q', nonce) + encryptedPayload inventoryHash = calculateInventoryHash(encryptedPayload) @@ -785,10 +785,10 @@ class singleWorker(threading.Thread): toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress( toAddress) if toStatus != 'success': - shared.printLock.acquire() - sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr( - toAddress) + '. Please report this error to Atheros.') - shared.printLock.release() + with shared.printLock: + sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr( + toAddress) + '. Please report this error to Atheros.') + return shared.neededPubkeys[ripe] = 0 payload = pack('>Q', (int(time.time()) + random.randrange( @@ -796,9 +796,9 @@ class singleWorker(threading.Thread): payload += encodeVarint(addressVersionNumber) payload += encodeVarint(streamNumber) payload += ripe - shared.printLock.acquire() - print 'making request for pubkey with ripe:', ripe.encode('hex') - shared.printLock.release() + with shared.printLock: + print 'making request for pubkey with ripe:', ripe.encode('hex') + # print 'trial value', trialValue statusbar = 'Doing the computations necessary to request the recipient\'s public key.' shared.UISignalQueue.put(('updateStatusBar', statusbar)) @@ -808,9 +808,9 @@ class singleWorker(threading.Thread): 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print 'Found proof of work', trialValue, 'Nonce:', nonce - shared.printLock.release() + with shared.printLock: + print 'Found proof of work', trialValue, 'Nonce:', nonce + payload = pack('>Q', nonce) + payload inventoryHash = calculateInventoryHash(payload) @@ -839,19 +839,19 @@ class singleWorker(threading.Thread): payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) - shared.printLock.acquire() - print '(For ack message) Doing proof of work...' - shared.printLock.release() + with shared.printLock: + print '(For ack message) Doing proof of work...' + powStartTime = time.time() initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) - shared.printLock.acquire() - print '(For ack message) Found proof of work', trialValue, 'Nonce:', nonce - try: - print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' - except: - pass - shared.printLock.release() + with shared.printLock: + print '(For ack message) Found proof of work', trialValue, 'Nonce:', nonce + try: + print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.' + except: + pass + payload = pack('>Q', nonce) + payload headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData += 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index ebe6a7ff..84014a8c 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -61,9 +61,9 @@ class sqlThread(threading.Thread): print 'Created messages database file' except Exception as err: if str(err) == 'table inbox already exists': - shared.printLock.acquire() - print 'Database file already exists.' - shared.printLock.release() + with shared.printLock: + print 'Database file already exists.' + else: sys.stderr.write( 'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err)) @@ -225,14 +225,14 @@ class sqlThread(threading.Thread): self.conn.commit() elif item == 'exit': self.conn.close() - shared.printLock.acquire() - print 'sqlThread exiting gracefully.' - shared.printLock.release() + with shared.printLock: + print 'sqlThread exiting gracefully.' + return elif item == 'movemessagstoprog': - shared.printLock.acquire() - print 'the sqlThread is moving the messages.dat file to the local program directory.' - shared.printLock.release() + with shared.printLock: + print 'the sqlThread is moving the messages.dat file to the local program directory.' + self.conn.commit() self.conn.close() shutil.move( @@ -241,9 +241,9 @@ class sqlThread(threading.Thread): self.conn.text_factory = str self.cur = self.conn.cursor() elif item == 'movemessagstoappdata': - shared.printLock.acquire() - print 'the sqlThread is moving the messages.dat file to the Appdata folder.' - shared.printLock.release() + with shared.printLock: + print 'the sqlThread is moving the messages.dat file to the Appdata folder.' + self.conn.commit() self.conn.close() shutil.move( @@ -263,11 +263,11 @@ class sqlThread(threading.Thread): try: self.cur.execute(item, parameters) except Exception as err: - 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('This program shall now abruptly exit!\n') - shared.printLock.release() + with shared.printLock: + 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') + os._exit(0) shared.sqlReturnQueue.put(self.cur.fetchall()) From 3e079787be48e8b7e5f120bfe0008839c10fe9c8 Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Sun, 30 Jun 2013 11:17:49 +0100 Subject: [PATCH 66/93] Altered Makefile to avoid needing to chase changes --- Makefile | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/Makefile b/Makefile index ac602a3f..d6ef4f33 100755 --- a/Makefile +++ b/Makefile @@ -27,16 +27,7 @@ install: mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24 mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24/apps - install -m 644 src/*.ui $(DEST_APP) - install -m 644 src/*.py $(DEST_APP) - install -m 644 src/*.qrc $(DEST_APP) - - install -m 644 src/images/*.png $(DEST_APP)/images - install -m 644 src/images/*.ico $(DEST_APP)/images - install -m 644 src/pyelliptic/*.py $(DEST_APP)/pyelliptic - install -m 644 src/socks/*.py $(DEST_APP)/socks - install -m 644 src/bitmessageqt/*.py $(DEST_APP)/bitmessageqt - install -m 644 src/translations/*.qm $(DEST_APP)/translations + cp -r src/* $(DEST_APP) install -m 755 debian/pybm $(DESTDIR)/usr/bin/$(APP) install -m 644 desktop/$(APP).desktop $(DEST_SHARE)/applications/$(APP).desktop From b038edf2b2ae498eedd25059abd58214ba58175d Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Sun, 30 Jun 2013 16:16:41 +0100 Subject: [PATCH 67/93] Repairing debian packaging --- Makefile | 52 +++++++++++++++++++-------------------- debian.sh | 3 ++- debian/changelog | 30 +++++++++++++++++++++++ debian/rules | 64 ++++++++++++++++++++++-------------------------- 4 files changed, 87 insertions(+), 62 deletions(-) diff --git a/Makefile b/Makefile index d6ef4f33..afb6744e 100755 --- a/Makefile +++ b/Makefile @@ -1,43 +1,43 @@ APP=pybitmessage VERSION=0.3.4 -DEST_SHARE=$(DESTDIR)/usr/share -DEST_APP=$(DEST_SHARE)/$(APP) +DEST_SHARE=${DESTDIR}/usr/share +DEST_APP=${DEST_SHARE}/${APP} all: debug: source: - tar -cvzf ../$(APP)_$(VERSION).orig.tar.gz ../$(APP)-$(VERSION) --exclude-vcs + tar -cvzf ../${APP}_${VERSION}.orig.tar.gz ../${APP}-${VERSION} --exclude-vcs install: - mkdir -m 755 -p $(DESTDIR)/usr/bin - mkdir -m 755 -p $(DEST_APP) - mkdir -m 755 -p $(DEST_SHARE)/applications - mkdir -m 755 -p $(DEST_APP)/images - mkdir -m 755 -p $(DEST_APP)/pyelliptic - mkdir -m 755 -p $(DEST_APP)/socks - mkdir -m 755 -p $(DEST_APP)/bitmessageqt - mkdir -m 755 -p $(DEST_APP)/translations - mkdir -m 755 -p $(DEST_SHARE)/pixmaps - mkdir -m 755 -p $(DEST_SHARE)/icons - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/scalable - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/scalable/apps - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24 - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24/apps + mkdir -m 755 -p ${DESTDIR}/usr/bin + mkdir -m 755 -p ${DEST_APP} + mkdir -m 755 -p ${DEST_SHARE}/applications + mkdir -m 755 -p ${DEST_APP}/images + mkdir -m 755 -p ${DEST_APP}/pyelliptic + mkdir -m 755 -p ${DEST_APP}/socks + mkdir -m 755 -p ${DEST_APP}/bitmessageqt + mkdir -m 755 -p ${DEST_APP}/translations + mkdir -m 755 -p ${DEST_SHARE}/pixmaps + mkdir -m 755 -p ${DEST_SHARE}/icons + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable/apps + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24 + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24/apps - cp -r src/* $(DEST_APP) - install -m 755 debian/pybm $(DESTDIR)/usr/bin/$(APP) + cp -r src/* ${DEST_APP} + install -m 755 debian/pybm ${DESTDIR}/usr/bin/${APP} - install -m 644 desktop/$(APP).desktop $(DEST_SHARE)/applications/$(APP).desktop - install -m 644 src/images/can-icon-24px.png $(DEST_SHARE)/icons/hicolor/24x24/apps/$(APP).png - install -m 644 desktop/can-icon.svg $(DEST_SHARE)/icons/hicolor/scalable/apps/$(APP).svg - install -m 644 desktop/can-icon.svg $(DEST_SHARE)/pixmaps/$(APP).svg + install -m 644 desktop/${APP}.desktop ${DEST_SHARE}/applications/${APP}.desktop + install -m 644 src/images/can-icon-24px.png ${DEST_SHARE}/icons/hicolor/24x24/apps/${APP}.png + install -m 644 desktop/can-icon.svg ${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg + install -m 644 desktop/can-icon.svg ${DEST_SHARE}/pixmaps/${APP}.svg clean: - rm -rf debian/$(APP) - rm -f ../$(APP)_*.deb ../$(APP)_*.asc ../$(APP)_*.dsc ../$(APP)*.changes + rm -rf debian/${APP} + rm -f ../${APP}_*.deb ../${APP}_*.asc ../${APP}_*.dsc ../${APP}*.changes rm -f *.sh~ src/*.pyc src/socks/*.pyc src/pyelliptic/*.pyc rm -f *.deb \#* \.#* debian/*.log debian/*.substvars rm -f Makefile~ diff --git a/debian.sh b/debian.sh index 4b9410ed..ac26380e 100755 --- a/debian.sh +++ b/debian.sh @@ -9,6 +9,7 @@ APP=pybitmessage PREV_VERSION=0.3.3 VERSION=0.3.4 +RELEASE=1 ARCH_TYPE=all #update version numbers automatically - so you don't have to @@ -27,5 +28,5 @@ dpkg-buildpackage -A # change the directory name back mv ../${APP}-${VERSION} ../PyBitmessage -gpg -ba ../${APP}_${VERSION}-1_${ARCH_TYPE}.deb +gpg -ba ../${APP}_${VERSION}-${RELEASE}_${ARCH_TYPE}.deb gpg -ba ../${APP}_${VERSION}.orig.tar.gz diff --git a/debian/changelog b/debian/changelog index 8c78203e..1d822cd1 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,33 @@ +pybitmessage (0.3.4-1) raring; urgency=low + + * Switched addr, msg, broadcast, and getpubkey message types + to 8 byte time. Last remaining type is pubkey. + * Added tooltips to show the full subject of messages + * Added Maximum Acceptable Difficulty fields in the settings + * Send out pubkey immediately after generating deterministic + addresses rather than waiting for a request + + -- Bob Mottram (4096 bits) Sun, 30 June 2013 11:23:00 +0100 + +pybitmessage (0.3.3-1) raring; urgency=low + + * Remove inbox item from GUI when using API command trashMessage + * Add missing trailing semicolons to pybitmessage.desktop + * Ensure $(DESTDIR)/usr/bin exists + * Update Makefile to correct sandbox violations when built + via Portage (Gentoo) + * Fix message authentication bug + + -- Bob Mottram (4096 bits) Sun, 30 June 2013 11:23:00 +0100 + +pybitmessage (0.3.211-1) raring; urgency=low + + * Removed multi-core proof of work + as the multiprocessing module does not work well with + pyinstaller's --onefile option. + + -- Bob Mottram (4096 bits) Sun, 30 June 2013 11:23:00 +0100 + pybitmessage (0.3.2-1) raring; urgency=low * Bugfix: Remove remaining references to the old myapp.trayIcon diff --git a/debian/rules b/debian/rules index 0f873425..2a7767b6 100755 --- a/debian/rules +++ b/debian/rules @@ -1,12 +1,13 @@ #!/usr/bin/make -f APP=pybitmessage - -DEST_MAIN=$(CURDIR)/debian/$(APP)/usr/bin -DEST_SHARE=$(CURDIR)/debian/$(APP)/usr/share -DEST_APP=$(DEST_SHARE)/$(APP) +DESTDIR=${CURDIR}/debian/${APP} +DEST_SHARE=${DESTDIR}/usr/share +DEST_APP=${DEST_SHARE}/${APP} build: build-stamp make +build-arch: build-stamp +build-indep: build-stamp build-stamp: dh_testdir touch build-stamp @@ -15,50 +16,43 @@ clean: dh_testroot rm -f build-stamp dh_clean -install: build clean +install: dh_testdir dh_testroot dh_prep + dh_clean -k dh_installdirs - mkdir -m 755 -p $(CURDIR)/debian/$(APP)/usr - mkdir -m 755 -p $(CURDIR)/debian/$(APP)/usr/bin - mkdir -m 755 -p $(DEST_APP) - mkdir -m 755 -p $(DEST_SHARE)/applications - mkdir -m 755 -p $(DEST_APP)/images - mkdir -m 755 -p $(DEST_APP)/pyelliptic - mkdir -m 755 -p $(DEST_APP)/socks - mkdir -m 755 -p $(DEST_APP)/bitmessageqt - mkdir -m 755 -p $(DEST_SHARE)/pixmaps - mkdir -m 755 -p $(DEST_SHARE)/icons - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/scalable - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/scalable/apps - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24 - mkdir -m 755 -p $(DEST_SHARE)/icons/hicolor/24x24/apps + mkdir -m 755 -p ${DESTDIR}/usr/bin + mkdir -m 755 -p ${DEST_APP} + mkdir -m 755 -p ${DEST_SHARE}/applications + mkdir -m 755 -p ${DEST_APP}/images + mkdir -m 755 -p ${DEST_APP}/pyelliptic + mkdir -m 755 -p ${DEST_APP}/socks + mkdir -m 755 -p ${DEST_APP}/bitmessageqt + mkdir -m 755 -p ${DEST_APP}/translations + mkdir -m 755 -p ${DEST_SHARE}/pixmaps + mkdir -m 755 -p ${DEST_SHARE}/icons + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable/apps + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24 + mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24/apps - install -m 644 $(CURDIR)/src/*.ui $(DEST_APP) - install -m 644 $(CURDIR)/src/*.py $(DEST_APP) - install -m 644 $(CURDIR)/src/*.qrc $(DEST_APP) + cp -r src/* ${DEST_APP} + install -m 755 debian/pybm ${DESTDIR}/usr/bin/${APP} - install -m 644 $(CURDIR)/src/images/*.png $(DEST_APP)/images - install -m 644 $(CURDIR)/src/images/*.ico $(DEST_APP)/images - install -m 644 $(CURDIR)/src/pyelliptic/*.py $(DEST_APP)/pyelliptic - install -m 644 $(CURDIR)/src/socks/*.py $(DEST_APP)/socks - install -m 644 $(CURDIR)/src/bitmessageqt/*.py $(DEST_APP)/bitmessageqt - install -m 755 $(CURDIR)/debian/pybm $(DEST_MAIN)/pybitmessage + install -m 644 desktop/${APP}.desktop ${DEST_SHARE}/applications/${APP}.desktop + install -m 644 src/images/can-icon-24px.png ${DEST_SHARE}/icons/hicolor/24x24/apps/${APP}.png + install -m 644 desktop/can-icon.svg ${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg + install -m 644 desktop/can-icon.svg ${DEST_SHARE}/pixmaps/${APP}.svg - install -m 644 $(CURDIR)/desktop/$(APP).desktop $(DEST_SHARE)/applications/$(APP).desktop - install -m 644 $(CURDIR)/src/images/can-icon-24px.png $(DEST_SHARE)/icons/hicolor/24x24/apps/$(APP).png - install -m 644 $(CURDIR)/desktop/can-icon.svg $(DEST_SHARE)/icons/hicolor/scalable/apps/$(APP).svg - install -m 644 $(CURDIR)/desktop/can-icon.svg $(DEST_SHARE)/pixmaps/$(APP).svg binary-indep: build install dh_shlibdeps dh_testdir dh_testroot dh_installchangelogs dh_installdocs -# dh_installexamples # dh_installman dh_link dh_compress @@ -68,5 +62,5 @@ binary-indep: build install dh_md5sums dh_builddeb binary-arch: build install -binary: binary-indep +binary: binary-indep binary-arch .PHONY: build clean binary-indep binary install From 95a1afb84b22884b8581a3e45825d9d4d9348d60 Mon Sep 17 00:00:00 2001 From: Pedro Gimeno Date: Mon, 1 Jul 2013 07:36:22 +0200 Subject: [PATCH 68/93] Fix issue #183 (CPU 100% usage) As per http://docs.python.org/2/howto/sockets.html#using-a-socket it's possible that a socket recv() call returns 0 bytes if the remote closes the connection. In that case, recv() does not obey settimeout(): it just doesn't block and returns zero bytes immediately, which in this case results in an infinite loop if the transmission was incomplete. --- src/class_receiveDataThread.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index e5293fe8..a023f80b 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -66,7 +66,10 @@ class receiveDataThread(threading.Thread): shared.printLock.release() while True: try: + dataLen = len(self.data) self.data += self.sock.recv(4096) + if len(self.data) == dataLen: # recv returns 0 bytes when the remote closes the connection + raise Exception("Remote closed the connection") except socket.timeout: shared.printLock.acquire() print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' From 8bf8e47cd125f1b7844c6229d06857417fd73480 Mon Sep 17 00:00:00 2001 From: RemideZ Date: Tue, 2 Jul 2013 13:52:16 +0200 Subject: [PATCH 69/93] Update __init__.py --- src/bitmessageqt/__init__.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index ce477836..fab7e458 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2933,8 +2933,11 @@ def run(): app = QtGui.QApplication(sys.argv) translator = QtCore.QTranslator() - translator.load("translations/bitmessage_" + str(locale.getlocale()[0])) - #translator.load("translations/bitmessage_fr_BE") # Try French instead + try: + translator.load("translations/bitmessage_" + str(locale.getlocale()[0])) + except: + # The above is not compatible with all versions of OSX. + translator.load("translations/bitmessage_en_US") # Default to english. QtGui.QApplication.installTranslator(translator) app.setStyleSheet("QStatusBar::item { border: 0px solid black }") From 8df9dc5731747958d3b40dce59b4ecfc4f70aab2 Mon Sep 17 00:00:00 2001 From: RemideZ Date: Tue, 2 Jul 2013 13:52:55 +0200 Subject: [PATCH 70/93] Update bitmessagemain.py --- src/bitmessagemain.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index c4c2b6db..811bcffd 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -29,6 +29,13 @@ from class_addressGenerator import * import helper_startup import helper_bootstrap +import sys +if sys.platform == 'darwin': + if float( str(sys.version_info[1]) + "." + str(sys.version_info[2])) < 7.5: + print "You should use python 2.7.5 or greater." + print "Your version:", str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) + sys.exit(0) + def connectToStream(streamNumber): selfInitiatedConnections[streamNumber] = {} if sys.platform[0:3] == 'win': From 2c8ca6623a1f4fbd6f749c473235a36334db5524 Mon Sep 17 00:00:00 2001 From: RemideZ Date: Tue, 2 Jul 2013 13:53:35 +0200 Subject: [PATCH 71/93] Update openssl.py --- src/pyelliptic/openssl.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 09df5ca4..ee75f90a 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -289,7 +289,12 @@ class _OpenSSL: self.HMAC.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] - self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC + try: + self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC + except: + # The above is not compatible with all versions of OSX. + self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1 + self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, From 55b899f5c1ee305161986601a0a5d656e99e0e5c Mon Sep 17 00:00:00 2001 From: Pedro Gimeno Date: Tue, 2 Jul 2013 17:43:54 +0200 Subject: [PATCH 72/93] Better fix for issue #183 The former patch was too local; this one integrates better with the structure of the code. --- src/class_receiveDataThread.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index a023f80b..ced951b2 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -65,11 +65,9 @@ class receiveDataThread(threading.Thread): print 'ID of the receiveDataThread is', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) shared.printLock.release() while True: + dataLen = len(self.data) try: - dataLen = len(self.data) self.data += self.sock.recv(4096) - if len(self.data) == dataLen: # recv returns 0 bytes when the remote closes the connection - raise Exception("Remote closed the connection") except socket.timeout: shared.printLock.acquire() print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' @@ -81,7 +79,7 @@ class receiveDataThread(threading.Thread): shared.printLock.release() break # print 'Received', repr(self.data) - if self.data == "": + if len(self.data) == dataLen: shared.printLock.acquire() print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' shared.printLock.release() From 68b235027695d499a3d8779fba1575d094cd8f0e Mon Sep 17 00:00:00 2001 From: RemideZ Date: Tue, 2 Jul 2013 20:25:18 +0200 Subject: [PATCH 73/93] Nicer formatting --- src/bitmessagemain.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 811bcffd..4a2071f5 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -31,9 +31,9 @@ import helper_bootstrap import sys if sys.platform == 'darwin': - if float( str(sys.version_info[1]) + "." + str(sys.version_info[2])) < 7.5: + if float( "{1}.{2}".format(*sys.version_info) ) < 7.5: print "You should use python 2.7.5 or greater." - print "Your version:", str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) + print "Your version: {0}.{1}.{2}".format(*sys.version_info) sys.exit(0) def connectToStream(streamNumber): From 1f8eee411996964f4a68a6a5a25bf3d65401c1c9 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 5 Jul 2013 16:01:20 -0400 Subject: [PATCH 74/93] removed apparently unnecessary loop --- src/bitmessageqt/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 4eefdbf2..ba0040fb 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2941,6 +2941,7 @@ try: import gevent except ImportError as ex: print "cannot find gevent" + gevent = None else: def mainloop(app): while True: From 39f4f85b111f811608e47b1f2fbd6fff752dc8df Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 5 Jul 2013 16:43:40 -0400 Subject: [PATCH 75/93] removed apparently unnecessary loop --- src/bitmessageqt/__init__.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index ba0040fb..ac554d92 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -2940,16 +2940,12 @@ class UISignaler(Thread,QThread): try: import gevent except ImportError as ex: - print "cannot find gevent" gevent = None else: def mainloop(app): while True: app.processEvents() - while app.hasPendingEvents(): - app.processEvents() - gevent.sleep(0.01) - gevent.sleep(0.01) # don't appear to get here but cooperate again + gevent.sleep(0.01) def testprint(): #print 'this is running' gevent.spawn_later(1, testprint) From 2b2fa867f058e649cb7502ac36e5de2334108b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Tue, 9 Jul 2013 12:19:31 +0200 Subject: [PATCH 76/93] Exit if `dpkg-buildpackage` fails. --- debian.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debian.sh b/debian.sh index ac26380e..10cbf61e 100755 --- a/debian.sh +++ b/debian.sh @@ -23,7 +23,7 @@ mv ../PyBitmessage ../${APP}-${VERSION} make source # Build the package -dpkg-buildpackage -A +dpkg-buildpackage -A || exit 1 # change the directory name back mv ../${APP}-${VERSION} ../PyBitmessage From e4869514ca79d4f8564a584304109b5244151b40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Tue, 9 Jul 2013 12:19:54 +0200 Subject: [PATCH 77/93] Add `make uninstall`. --- Makefile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Makefile b/Makefile index afb6744e..cacc103f 100755 --- a/Makefile +++ b/Makefile @@ -35,6 +35,14 @@ install: install -m 644 desktop/can-icon.svg ${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg install -m 644 desktop/can-icon.svg ${DEST_SHARE}/pixmaps/${APP}.svg +uninstall: + rm -Rf "${DEST_APP}" + rm -f "${DESTDIR}/usr/bin/${APP}" + rm -f "${DEST_SHARE}/applications/${APP}.desktop" + rm -f "${DEST_SHARE}/icons/hicolor/24x24/apps/${APP}.png" + rm -f "${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg" + rm -f "${DEST_SHARE}/pixmaps/${APP}.svg" + clean: rm -rf debian/${APP} rm -f ../${APP}_*.deb ../${APP}_*.asc ../${APP}_*.dsc ../${APP}*.changes From 2e2db97250d38f190cdc7aeb600360ba9c4054a6 Mon Sep 17 00:00:00 2001 From: Gregor Robinson Date: Wed, 10 Jul 2013 19:50:18 +0100 Subject: [PATCH 78/93] Don't propagate loggers; add some logging. --- src/debug.py | 3 +++ src/shared.py | 61 +++++++++++++++++++++++---------------------------- 2 files changed, 31 insertions(+), 33 deletions(-) diff --git a/src/debug.py b/src/debug.py index d8033f2d..14214686 100644 --- a/src/debug.py +++ b/src/debug.py @@ -48,12 +48,15 @@ logging.config.dictConfig({ 'loggers': { 'console_only': { 'handlers': ['console'], + 'propagate' : 0 }, 'file_only': { 'handlers': ['file'], + 'propagate' : 0 }, 'both': { 'handlers': ['console', 'file'], + 'propagate' : 0 }, }, 'root': { diff --git a/src/shared.py b/src/shared.py index 4b3ef73b..313e2ac6 100644 --- a/src/shared.py +++ b/src/shared.py @@ -118,7 +118,8 @@ def lookupAppdataFolder(): if "HOME" in environ: dataFolder = path.join(os.environ["HOME"], "Library/Application Support/", APPNAME) + '/' else: - print 'Could not find home folder, please report this message and your OS X version to the BitMessage Github.' + logger.critical('Could not find home folder, please report this message and your ' + 'OS X version to the BitMessage Github.') sys.exit() elif 'win32' in sys.platform or 'win64' in sys.platform: @@ -129,13 +130,14 @@ def lookupAppdataFolder(): dataFolder = path.join(environ["XDG_CONFIG_HOME"], APPNAME) except KeyError: dataFolder = path.join(environ["HOME"], ".config", APPNAME) + # Migrate existing data to the proper location if this is an existing install - try: - print "Moving data folder to ~/.config/%s" % APPNAME - move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) - dataFolder = dataFolder + '/' - except IOError: - dataFolder = dataFolder + '/' + if not os.path.exists(dataFolder): + try: + logger.info("Moving data folder to ~/.config/%s" % APPNAME) + move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) + except IOError: + dataFolder = dataFolder + '/' return dataFolder def isAddressInMyAddressBook(address): @@ -200,9 +202,7 @@ def decodeWalletImportFormat(WIFstring): def reloadMyAddressHashes(): - printLock.acquire() - print 'reloading keys from keys.dat file' - printLock.release() + logger.debug('reloading keys from keys.dat file') myECCryptorObjects.clear() myAddressesByHash.clear() #myPrivateKeys.clear() @@ -221,9 +221,7 @@ def reloadMyAddressHashes(): sys.stderr.write('Error in reloadMyAddressHashes: Can\'t handle address versions other than 2 or 3.\n') def reloadBroadcastSendersForWhichImWatching(): - printLock.acquire() - print 'reloading subscriptions...' - printLock.release() + logger.debug('reloading subscriptions...') broadcastSendersForWhichImWatching.clear() MyECSubscriptionCryptorObjects.clear() sqlLock.acquire() @@ -246,46 +244,43 @@ def doCleanShutdown(): knownNodesLock.acquire() UISignalQueue.put(('updateStatusBar','Saving the knownNodes list of peers to disk...')) output = open(appdata + 'knownnodes.dat', 'wb') - print 'finished opening knownnodes.dat. Now pickle.dump' + logger.info('finished opening knownnodes.dat. Now pickle.dump') pickle.dump(knownNodes, output) - print 'Completed pickle.dump. Closing output...' + logger.info('Completed pickle.dump. Closing output...') output.close() knownNodesLock.release() - printLock.acquire() - print 'Finished closing knownnodes.dat output file.' - printLock.release() + logger.info('Finished closing knownnodes.dat output file.') UISignalQueue.put(('updateStatusBar','Done saving the knownNodes list of peers to disk.')) broadcastToSendDataQueues((0, 'shutdown', 'all')) - printLock.acquire() - print 'Flushing inventory in memory out to disk...' - printLock.release() - UISignalQueue.put(('updateStatusBar','Flushing inventory in memory out to disk. This should normally only take a second...')) + logger.info('Flushing inventory in memory out to disk...') + UISignalQueue.put(('updateStatusBar','Flushing inventory in memory out to disk. ' + 'This should normally only take a second...')) flushInventory() - #This one last useless query will guarantee that the previous flush committed before we close the program. + # This one last useless query will guarantee that the previous flush committed before we close + # the program. sqlLock.acquire() sqlSubmitQueue.put('SELECT address FROM subscriptions') sqlSubmitQueue.put('') sqlReturnQueue.get() sqlSubmitQueue.put('exit') sqlLock.release() - printLock.acquire() - print 'Finished flushing inventory.' - printLock.release() - - time.sleep(.25) #Wait long enough to guarantee that any running proof of work worker threads will check the shutdown variable and exit. If the main thread closes before they do then they won't stop. + logger.info('Finished flushing inventory.') + # Wait long enough to guarantee that any running proof of work worker threads will check the + # shutdown variable and exit. If the main thread closes before they do then they won't stop. + time.sleep(.25) if safeConfigGetBoolean('bitmessagesettings','daemon'): - printLock.acquire() - print 'Done.' - printLock.release() + logger.info('Clean shutdown complete.') os._exit(0) -#When you want to command a sendDataThread to do something, like shutdown or send some data, this function puts your data into the queues for each of the sendDataThreads. The sendDataThreads are responsible for putting their queue into (and out of) the sendDataQueues list. +# When you want to command a sendDataThread to do something, like shutdown or send some data, this +# function puts your data into the queues for each of the sendDataThreads. The sendDataThreads are +# responsible for putting their queue into (and out of) the sendDataQueues list. def broadcastToSendDataQueues(data): - #print 'running broadcastToSendDataQueues' + # logger.debug('running broadcastToSendDataQueues') for q in sendDataQueues: q.put((data)) From 3179ea30f01912a55d1ede14b1fc161d48b7969a Mon Sep 17 00:00:00 2001 From: Gregor Robinson Date: Wed, 10 Jul 2013 20:15:04 +0100 Subject: [PATCH 79/93] These changes slipped from last commit. Sorry. --- src/shared.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/shared.py b/src/shared.py index 313e2ac6..c706038a 100644 --- a/src/shared.py +++ b/src/shared.py @@ -21,6 +21,7 @@ import socket import random import highlevelcrypto import shared +from debug import logger config = ConfigParser.SafeConfigParser() myECCryptorObjects = {} @@ -132,11 +133,11 @@ def lookupAppdataFolder(): dataFolder = path.join(environ["HOME"], ".config", APPNAME) # Migrate existing data to the proper location if this is an existing install - if not os.path.exists(dataFolder): - try: - logger.info("Moving data folder to ~/.config/%s" % APPNAME) - move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) - except IOError: + try: + logger.info("Moving data folder to %s" % (dataFolder)) + move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) + except IOError: + pass dataFolder = dataFolder + '/' return dataFolder @@ -255,8 +256,9 @@ def doCleanShutdown(): broadcastToSendDataQueues((0, 'shutdown', 'all')) logger.info('Flushing inventory in memory out to disk...') - UISignalQueue.put(('updateStatusBar','Flushing inventory in memory out to disk. ' - 'This should normally only take a second...')) + UISignalQueue.put(( + 'updateStatusBar', + 'Flushing inventory in memory out to disk. This should normally only take a second...')) flushInventory() # This one last useless query will guarantee that the previous flush committed before we close From 14266de0c69725b62823845a275ab9ec9bc56574 Mon Sep 17 00:00:00 2001 From: Rainulf Pineda Date: Thu, 11 Jul 2013 03:23:39 -0400 Subject: [PATCH 80/93] Updated bitmessageui for search. --- src/bitmessageqt/bitmessageui.ui | 76 ++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 14 deletions(-) diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index 48f5c224..8aef2309 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -14,7 +14,7 @@ Bitmessage - + :/newPrefix/images/can-icon-24px.png:/newPrefix/images/can-icon-24px.png @@ -22,7 +22,16 @@ - + + 0 + + + 0 + + + 0 + + 0 @@ -61,13 +70,52 @@ - + :/newPrefix/images/inbox.png:/newPrefix/images/inbox.png Inbox + + + + 0 + + + + + + + + + All + + + + + To + + + + + From + + + + + Subject + + + + + Received + + + + + + @@ -145,7 +193,7 @@ - + :/newPrefix/images/send.png:/newPrefix/images/send.png @@ -214,8 +262,8 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> +</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2';"><br /></p></body></html> @@ -303,7 +351,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/sent.png:/newPrefix/images/sent.png @@ -380,7 +428,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/identities.png:/newPrefix/images/identities.png @@ -480,7 +528,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/subscriptions.png:/newPrefix/images/subscriptions.png @@ -565,7 +613,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/addressbook.png:/newPrefix/images/addressbook.png @@ -647,7 +695,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/blacklist.png:/newPrefix/images/blacklist.png @@ -739,7 +787,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/networkstatus.png:/newPrefix/images/networkstatus.png @@ -758,7 +806,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/redicon.png:/newPrefix/images/redicon.png @@ -925,7 +973,7 @@ p, li { white-space: pre-wrap; } 0 0 795 - 18 + 20 From 855a9f963f02b79aaab1003ab63b18f480dc7527 Mon Sep 17 00:00:00 2001 From: Rainulf Pineda Date: Fri, 12 Jul 2013 02:01:33 -0400 Subject: [PATCH 81/93] Generated py for search. --- Makefile | 0 debian.sh | 0 debian/rules | 0 osx.sh | 0 src/bitmessageqt/bitmessageui.py | 30 +++++++++++++++++++++++++----- src/bitmessageqt/bitmessageui.ui | 20 ++++++++++---------- 6 files changed, 35 insertions(+), 15 deletions(-) mode change 100755 => 100644 Makefile mode change 100755 => 100644 debian.sh mode change 100755 => 100644 debian/rules mode change 100755 => 100644 osx.sh diff --git a/Makefile b/Makefile old mode 100755 new mode 100644 diff --git a/debian.sh b/debian.sh old mode 100755 new mode 100644 diff --git a/debian/rules b/debian/rules old mode 100755 new mode 100644 diff --git a/osx.sh b/osx.sh old mode 100755 new mode 100644 diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index 1186e814..dbb33fb0 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -2,8 +2,8 @@ # Form implementation generated from reading ui file 'bitmessageui.ui' # -# Created: Thu Jun 13 01:02:50 2013 -# by: PyQt4 UI code generator 4.10.1 +# Created: Fri Jul 12 01:59:15 2013 +# by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! @@ -54,6 +54,21 @@ class Ui_MainWindow(object): self.inbox.setObjectName(_fromUtf8("inbox")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.inbox) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) + self.horizontalLayoutSearch = QtGui.QHBoxLayout() + self.horizontalLayoutSearch.setContentsMargins(-1, 0, -1, -1) + self.horizontalLayoutSearch.setObjectName(_fromUtf8("horizontalLayoutSearch")) + self.searchLineEdit = QtGui.QLineEdit(self.inbox) + self.searchLineEdit.setObjectName(_fromUtf8("searchLineEdit")) + self.horizontalLayoutSearch.addWidget(self.searchLineEdit) + self.searchOptionCB = QtGui.QComboBox(self.inbox) + self.searchOptionCB.setObjectName(_fromUtf8("searchOptionCB")) + self.searchOptionCB.addItem(_fromUtf8("")) + self.searchOptionCB.addItem(_fromUtf8("")) + self.searchOptionCB.addItem(_fromUtf8("")) + self.searchOptionCB.addItem(_fromUtf8("")) + self.searchOptionCB.addItem(_fromUtf8("")) + self.horizontalLayoutSearch.addWidget(self.searchOptionCB) + self.verticalLayout_2.addLayout(self.horizontalLayoutSearch) self.tableWidgetInbox = QtGui.QTableWidget(self.inbox) self.tableWidgetInbox.setAlternatingRowColors(True) self.tableWidgetInbox.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) @@ -392,7 +407,7 @@ class Ui_MainWindow(object): self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 18)) + self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 20)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) @@ -467,6 +482,11 @@ class Ui_MainWindow(object): def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Bitmessage", None)) + self.searchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) + self.searchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) + self.searchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) + self.searchOptionCB.setItemText(3, _translate("MainWindow", "Subject", None)) + self.searchOptionCB.setItemText(4, _translate("MainWindow", "Received", None)) self.tableWidgetInbox.setSortingEnabled(True) item = self.tableWidgetInbox.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "To", None)) @@ -484,8 +504,8 @@ class Ui_MainWindow(object): self.textEditMessage.setHtml(_translate("MainWindow", "\n" "\n" -"


", None)) +"\n" +"


", None)) self.label.setText(_translate("MainWindow", "To:", None)) self.label_2.setText(_translate("MainWindow", "From:", None)) self.radioButtonBroadcast.setText(_translate("MainWindow", "Broadcast to everyone who is subscribed to your address", None)) diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index 8aef2309..65ad632d 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -14,7 +14,7 @@ Bitmessage - + :/newPrefix/images/can-icon-24px.png:/newPrefix/images/can-icon-24px.png @@ -70,7 +70,7 @@ - + :/newPrefix/images/inbox.png:/newPrefix/images/inbox.png @@ -193,7 +193,7 @@ - + :/newPrefix/images/send.png:/newPrefix/images/send.png @@ -351,7 +351,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/sent.png:/newPrefix/images/sent.png @@ -428,7 +428,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/identities.png:/newPrefix/images/identities.png @@ -528,7 +528,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/subscriptions.png:/newPrefix/images/subscriptions.png @@ -613,7 +613,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/addressbook.png:/newPrefix/images/addressbook.png @@ -695,7 +695,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/blacklist.png:/newPrefix/images/blacklist.png @@ -787,7 +787,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/networkstatus.png:/newPrefix/images/networkstatus.png @@ -806,7 +806,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/redicon.png:/newPrefix/images/redicon.png From 45cfead4d0cd06d69327c827b6196cf977f531cc Mon Sep 17 00:00:00 2001 From: Rainulf Pineda Date: Fri, 12 Jul 2013 04:24:24 -0400 Subject: [PATCH 82/93] Inbox search. --- src/bitmessageqt/__init__.py | 435 +++++++++++++++++-------------- src/bitmessageqt/bitmessageui.py | 34 +-- src/bitmessageqt/bitmessageui.ui | 6 +- 3 files changed, 258 insertions(+), 217 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index ae5ab8a7..8f3042a0 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -308,205 +308,10 @@ class MyForm(QtGui.QMainWindow): addressInKeysFile) # Load inbox from messages database file - font = QFont() - font.setBold(True) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT msgid, toaddress, fromaddress, subject, received, message, read FROM inbox where folder='inbox' ORDER BY received''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - msgid, toAddress, fromAddress, subject, received, message, read = row - subject = shared.fixPotentiallyInvalidUTF8Data(subject) - message = shared.fixPotentiallyInvalidUTF8Data(message) - try: - if toAddress == self.str_broadcast_subscribers: - toLabel = self.str_broadcast_subscribers - else: - toLabel = shared.config.get(toAddress, 'label') - except: - toLabel = '' - if toLabel == '': - toLabel = toAddress - - fromLabel = '' - t = (fromAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''select label from addressbook where address=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - - if queryreturn != []: - for row in queryreturn: - fromLabel, = row - - if fromLabel == '': # If this address wasn't in our address book... - t = (fromAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''select label from subscriptions where address=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - - if queryreturn != []: - for row in queryreturn: - fromLabel, = row - - self.ui.tableWidgetInbox.insertRow(0) - newItem = QtGui.QTableWidgetItem(unicode(toLabel, 'utf-8')) - newItem.setToolTip(unicode(toLabel, 'utf-8')) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - if not read: - newItem.setFont(font) - newItem.setData(Qt.UserRole, str(toAddress)) - if shared.safeConfigGetBoolean(toAddress, 'mailinglist'): - newItem.setTextColor(QtGui.QColor(137, 04, 177)) - self.ui.tableWidgetInbox.setItem(0, 0, newItem) - if fromLabel == '': - newItem = QtGui.QTableWidgetItem( - unicode(fromAddress, 'utf-8')) - newItem.setToolTip(unicode(fromAddress, 'utf-8')) - else: - newItem = QtGui.QTableWidgetItem(unicode(fromLabel, 'utf-8')) - newItem.setToolTip(unicode(fromLabel, 'utf-8')) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - if not read: - newItem.setFont(font) - newItem.setData(Qt.UserRole, str(fromAddress)) - - self.ui.tableWidgetInbox.setItem(0, 1, newItem) - newItem = QtGui.QTableWidgetItem(unicode(subject, 'utf-8')) - newItem.setToolTip(unicode(subject, 'utf-8')) - newItem.setData(Qt.UserRole, unicode(message, 'utf-8)')) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - if not read: - newItem.setFont(font) - self.ui.tableWidgetInbox.setItem(0, 2, newItem) - newItem = myTableWidgetItem(unicode(strftime(shared.config.get( - 'bitmessagesettings', 'timeformat'), localtime(int(received))), 'utf-8')) - newItem.setToolTip(unicode(strftime(shared.config.get( - 'bitmessagesettings', 'timeformat'), localtime(int(received))), 'utf-8')) - newItem.setData(Qt.UserRole, QByteArray(msgid)) - newItem.setData(33, int(received)) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - if not read: - newItem.setFont(font) - self.ui.tableWidgetInbox.setItem(0, 3, newItem) - self.ui.tableWidgetInbox.sortItems(3, Qt.DescendingOrder) - self.ui.tableWidgetInbox.keyPressEvent = self.tableWidgetInboxKeyPressEvent + self.loadInbox() # Load Sent items from database - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent where folder = 'sent' ORDER BY lastactiontime''') - shared.sqlSubmitQueue.put('') - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - for row in queryreturn: - toAddress, fromAddress, subject, message, status, ackdata, lastactiontime = row - subject = shared.fixPotentiallyInvalidUTF8Data(subject) - message = shared.fixPotentiallyInvalidUTF8Data(message) - try: - fromLabel = shared.config.get(fromAddress, 'label') - except: - fromLabel = '' - if fromLabel == '': - fromLabel = fromAddress - - toLabel = '' - t = (toAddress,) - shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''select label from addressbook where address=?''') - shared.sqlSubmitQueue.put(t) - queryreturn = shared.sqlReturnQueue.get() - shared.sqlLock.release() - - if queryreturn != []: - for row in queryreturn: - toLabel, = row - - self.ui.tableWidgetSent.insertRow(0) - if toLabel == '': - newItem = QtGui.QTableWidgetItem(unicode(toAddress, 'utf-8')) - newItem.setToolTip(unicode(toAddress, 'utf-8')) - else: - newItem = QtGui.QTableWidgetItem(unicode(toLabel, 'utf-8')) - newItem.setToolTip(unicode(toLabel, 'utf-8')) - newItem.setData(Qt.UserRole, str(toAddress)) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - self.ui.tableWidgetSent.setItem(0, 0, newItem) - if fromLabel == '': - newItem = QtGui.QTableWidgetItem( - unicode(fromAddress, 'utf-8')) - newItem.setToolTip(unicode(fromAddress, 'utf-8')) - else: - newItem = QtGui.QTableWidgetItem(unicode(fromLabel, 'utf-8')) - newItem.setToolTip(unicode(fromLabel, 'utf-8')) - newItem.setData(Qt.UserRole, str(fromAddress)) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - self.ui.tableWidgetSent.setItem(0, 1, newItem) - newItem = QtGui.QTableWidgetItem(unicode(subject, 'utf-8')) - newItem.setToolTip(unicode(subject, 'utf-8')) - newItem.setData(Qt.UserRole, unicode(message, 'utf-8)')) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - self.ui.tableWidgetSent.setItem(0, 2, newItem) - if status == 'awaitingpubkey': - statusText = _translate( - "MainWindow", "Waiting on their encryption key. Will request it again soon.") - elif status == 'doingpowforpubkey': - statusText = _translate( - "MainWindow", "Encryption key request queued.") - elif status == 'msgqueued': - statusText = _translate( - "MainWindow", "Queued.") - elif status == 'msgsent': - statusText = _translate("MainWindow", "Message sent. Waiting on acknowledgement. Sent at %1").arg( - unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - elif status == 'doingmsgpow': - statusText = _translate( - "MainWindow", "Need to do work to send message. Work is queued.") - elif status == 'ackreceived': - statusText = _translate("MainWindow", "Acknowledgement of the message received %1").arg( - unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - elif status == 'broadcastqueued': - statusText = _translate( - "MainWindow", "Broadcast queued.") - elif status == 'broadcastsent': - statusText = _translate("MainWindow", "Broadcast on %1").arg(unicode(strftime( - shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - elif status == 'toodifficult': - statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( - unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - elif status == 'badkey': - statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( - unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - elif status == 'forcepow': - statusText = _translate( - "MainWindow", "Forced difficulty override. Send should start soon.") - else: - statusText = _translate("MainWindow", "Unknown status: %1 %2").arg(status).arg(unicode( - strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) - newItem = myTableWidgetItem(statusText) - newItem.setToolTip(statusText) - newItem.setData(Qt.UserRole, QByteArray(ackdata)) - newItem.setData(33, int(lastactiontime)) - newItem.setFlags( - QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) - self.ui.tableWidgetSent.setItem(0, 3, newItem) - self.ui.tableWidgetSent.sortItems(3, Qt.DescendingOrder) - self.ui.tableWidgetSent.keyPressEvent = self.tableWidgetSentKeyPressEvent + self.loadSent() # Initialize the address book shared.sqlLock.acquire() @@ -527,6 +332,10 @@ class MyForm(QtGui.QMainWindow): # Initialize the Subscriptions self.rerenderSubscriptions() + # Initialize the inbox search + QtCore.QObject.connect(self.ui.inboxSearchLineEdit, QtCore.SIGNAL( + "returnPressed()"), self.inboxSearchLineEditPressed) + # Initialize the Blacklist or Whitelist if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': self.loadBlackWhiteList() @@ -686,6 +495,231 @@ class MyForm(QtGui.QMainWindow): self.appIndicatorShow() self.ui.tabWidget.setCurrentIndex(5) + # Load Sent items from database + def loadSent(self, where="", what=""): + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent where folder = 'sent' ORDER BY lastactiontime''') + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + toAddress, fromAddress, subject, message, status, ackdata, lastactiontime = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + try: + fromLabel = shared.config.get(fromAddress, 'label') + except: + fromLabel = '' + if fromLabel == '': + fromLabel = fromAddress + + toLabel = '' + t = (toAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''select label from addressbook where address=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + + if queryreturn != []: + for row in queryreturn: + toLabel, = row + + self.ui.tableWidgetSent.insertRow(0) + if toLabel == '': + newItem = QtGui.QTableWidgetItem(unicode(toAddress, 'utf-8')) + newItem.setToolTip(unicode(toAddress, 'utf-8')) + else: + newItem = QtGui.QTableWidgetItem(unicode(toLabel, 'utf-8')) + newItem.setToolTip(unicode(toLabel, 'utf-8')) + newItem.setData(Qt.UserRole, str(toAddress)) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + self.ui.tableWidgetSent.setItem(0, 0, newItem) + if fromLabel == '': + newItem = QtGui.QTableWidgetItem( + unicode(fromAddress, 'utf-8')) + newItem.setToolTip(unicode(fromAddress, 'utf-8')) + else: + newItem = QtGui.QTableWidgetItem(unicode(fromLabel, 'utf-8')) + newItem.setToolTip(unicode(fromLabel, 'utf-8')) + newItem.setData(Qt.UserRole, str(fromAddress)) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + self.ui.tableWidgetSent.setItem(0, 1, newItem) + newItem = QtGui.QTableWidgetItem(unicode(subject, 'utf-8')) + newItem.setToolTip(unicode(subject, 'utf-8')) + newItem.setData(Qt.UserRole, unicode(message, 'utf-8)')) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + self.ui.tableWidgetSent.setItem(0, 2, newItem) + if status == 'awaitingpubkey': + statusText = _translate( + "MainWindow", "Waiting on their encryption key. Will request it again soon.") + elif status == 'doingpowforpubkey': + statusText = _translate( + "MainWindow", "Encryption key request queued.") + elif status == 'msgqueued': + statusText = _translate( + "MainWindow", "Queued.") + elif status == 'msgsent': + statusText = _translate("MainWindow", "Message sent. Waiting on acknowledgement. Sent at %1").arg( + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + elif status == 'doingmsgpow': + statusText = _translate( + "MainWindow", "Need to do work to send message. Work is queued.") + elif status == 'ackreceived': + statusText = _translate("MainWindow", "Acknowledgement of the message received %1").arg( + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + elif status == 'broadcastqueued': + statusText = _translate( + "MainWindow", "Broadcast queued.") + elif status == 'broadcastsent': + statusText = _translate("MainWindow", "Broadcast on %1").arg(unicode(strftime( + shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + elif status == 'toodifficult': + statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + elif status == 'badkey': + statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + elif status == 'forcepow': + statusText = _translate( + "MainWindow", "Forced difficulty override. Send should start soon.") + else: + statusText = _translate("MainWindow", "Unknown status: %1 %2").arg(status).arg(unicode( + strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(lastactiontime)),'utf-8')) + newItem = myTableWidgetItem(statusText) + newItem.setToolTip(statusText) + newItem.setData(Qt.UserRole, QByteArray(ackdata)) + newItem.setData(33, int(lastactiontime)) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + self.ui.tableWidgetSent.setItem(0, 3, newItem) + self.ui.tableWidgetSent.sortItems(3, Qt.DescendingOrder) + self.ui.tableWidgetSent.keyPressEvent = self.tableWidgetSentKeyPressEvent + + # Load inbox from messages database file + def loadInbox(self, where="", what=""): + what = "%" + what + "%" + if where == "To": + where = "toaddress" + elif where == "From": + where = "fromaddress" + elif where == "Subject": + where = "subject" + elif where == "Received": + where = "received" + elif where == "Message": + where = "message" + else: + where = "toaddress || fromaddress || subject || received || message" + + sqlQuery = ''' + SELECT msgid, toaddress, fromaddress, subject, received, message, read + FROM inbox WHERE folder="inbox" AND %s LIKE "%s" + ORDER BY received + ''' % (where, what) + + while self.ui.tableWidgetInbox.rowCount() > 0: + self.ui.tableWidgetInbox.removeRow(0) + + font = QFont() + font.setBold(True) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put(sqlQuery) + shared.sqlSubmitQueue.put('') + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + for row in queryreturn: + msgid, toAddress, fromAddress, subject, received, message, read = row + subject = shared.fixPotentiallyInvalidUTF8Data(subject) + message = shared.fixPotentiallyInvalidUTF8Data(message) + try: + if toAddress == self.str_broadcast_subscribers: + toLabel = self.str_broadcast_subscribers + else: + toLabel = shared.config.get(toAddress, 'label') + except: + toLabel = '' + if toLabel == '': + toLabel = toAddress + + fromLabel = '' + t = (fromAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''select label from addressbook where address=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + + if queryreturn != []: + for row in queryreturn: + fromLabel, = row + + if fromLabel == '': # If this address wasn't in our address book... + t = (fromAddress,) + shared.sqlLock.acquire() + shared.sqlSubmitQueue.put( + '''select label from subscriptions where address=?''') + shared.sqlSubmitQueue.put(t) + queryreturn = shared.sqlReturnQueue.get() + shared.sqlLock.release() + + if queryreturn != []: + for row in queryreturn: + fromLabel, = row + + self.ui.tableWidgetInbox.insertRow(0) + newItem = QtGui.QTableWidgetItem(unicode(toLabel, 'utf-8')) + newItem.setToolTip(unicode(toLabel, 'utf-8')) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + if not read: + newItem.setFont(font) + newItem.setData(Qt.UserRole, str(toAddress)) + if shared.safeConfigGetBoolean(toAddress, 'mailinglist'): + newItem.setTextColor(QtGui.QColor(137, 04, 177)) + self.ui.tableWidgetInbox.setItem(0, 0, newItem) + if fromLabel == '': + newItem = QtGui.QTableWidgetItem( + unicode(fromAddress, 'utf-8')) + newItem.setToolTip(unicode(fromAddress, 'utf-8')) + else: + newItem = QtGui.QTableWidgetItem(unicode(fromLabel, 'utf-8')) + newItem.setToolTip(unicode(fromLabel, 'utf-8')) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + if not read: + newItem.setFont(font) + newItem.setData(Qt.UserRole, str(fromAddress)) + + self.ui.tableWidgetInbox.setItem(0, 1, newItem) + newItem = QtGui.QTableWidgetItem(unicode(subject, 'utf-8')) + newItem.setToolTip(unicode(subject, 'utf-8')) + newItem.setData(Qt.UserRole, unicode(message, 'utf-8)')) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + if not read: + newItem.setFont(font) + self.ui.tableWidgetInbox.setItem(0, 2, newItem) + newItem = myTableWidgetItem(unicode(strftime(shared.config.get( + 'bitmessagesettings', 'timeformat'), localtime(int(received))), 'utf-8')) + newItem.setToolTip(unicode(strftime(shared.config.get( + 'bitmessagesettings', 'timeformat'), localtime(int(received))), 'utf-8')) + newItem.setData(Qt.UserRole, QByteArray(msgid)) + newItem.setData(33, int(received)) + newItem.setFlags( + QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) + if not read: + newItem.setFont(font) + self.ui.tableWidgetInbox.setItem(0, 3, newItem) + self.ui.tableWidgetInbox.sortItems(3, Qt.DescendingOrder) + self.ui.tableWidgetInbox.keyPressEvent = self.tableWidgetInboxKeyPressEvent + # create application indicator def appIndicatorInit(self, app): self.tray = QSystemTrayIcon(QtGui.QIcon( @@ -2507,6 +2541,13 @@ class MyForm(QtGui.QMainWindow): self.popMenuSent.addAction(self.actionForceSend) self.popMenuSent.exec_(self.ui.tableWidgetSent.mapToGlobal(point)) + def inboxSearchLineEditPressed(self): + searchKeyword = self.ui.inboxSearchLineEdit.text().toUtf8().data() + searchOption = self.ui.inboxSearchOptionCB.currentText().toUtf8().data() + self.ui.inboxSearchLineEdit.setText(QString("")) + self.ui.textEditInboxMessage.setPlainText(QString("")) + self.loadInbox(searchOption, searchKeyword) + def tableWidgetInboxItemClicked(self): currentRow = self.ui.tableWidgetInbox.currentRow() if currentRow >= 0: diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index dbb33fb0..ff23fa82 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'bitmessageui.ui' # -# Created: Fri Jul 12 01:59:15 2013 +# Created: Fri Jul 12 04:16:52 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! @@ -57,17 +57,17 @@ class Ui_MainWindow(object): self.horizontalLayoutSearch = QtGui.QHBoxLayout() self.horizontalLayoutSearch.setContentsMargins(-1, 0, -1, -1) self.horizontalLayoutSearch.setObjectName(_fromUtf8("horizontalLayoutSearch")) - self.searchLineEdit = QtGui.QLineEdit(self.inbox) - self.searchLineEdit.setObjectName(_fromUtf8("searchLineEdit")) - self.horizontalLayoutSearch.addWidget(self.searchLineEdit) - self.searchOptionCB = QtGui.QComboBox(self.inbox) - self.searchOptionCB.setObjectName(_fromUtf8("searchOptionCB")) - self.searchOptionCB.addItem(_fromUtf8("")) - self.searchOptionCB.addItem(_fromUtf8("")) - self.searchOptionCB.addItem(_fromUtf8("")) - self.searchOptionCB.addItem(_fromUtf8("")) - self.searchOptionCB.addItem(_fromUtf8("")) - self.horizontalLayoutSearch.addWidget(self.searchOptionCB) + self.inboxSearchLineEdit = QtGui.QLineEdit(self.inbox) + self.inboxSearchLineEdit.setObjectName(_fromUtf8("inboxSearchLineEdit")) + self.horizontalLayoutSearch.addWidget(self.inboxSearchLineEdit) + self.inboxSearchOptionCB = QtGui.QComboBox(self.inbox) + self.inboxSearchOptionCB.setObjectName(_fromUtf8("inboxSearchOptionCB")) + self.inboxSearchOptionCB.addItem(_fromUtf8("")) + self.inboxSearchOptionCB.addItem(_fromUtf8("")) + self.inboxSearchOptionCB.addItem(_fromUtf8("")) + self.inboxSearchOptionCB.addItem(_fromUtf8("")) + self.inboxSearchOptionCB.addItem(_fromUtf8("")) + self.horizontalLayoutSearch.addWidget(self.inboxSearchOptionCB) self.verticalLayout_2.addLayout(self.horizontalLayoutSearch) self.tableWidgetInbox = QtGui.QTableWidget(self.inbox) self.tableWidgetInbox.setAlternatingRowColors(True) @@ -482,11 +482,11 @@ class Ui_MainWindow(object): def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Bitmessage", None)) - self.searchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) - self.searchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) - self.searchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) - self.searchOptionCB.setItemText(3, _translate("MainWindow", "Subject", None)) - self.searchOptionCB.setItemText(4, _translate("MainWindow", "Received", None)) + self.inboxSearchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) + self.inboxSearchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) + self.inboxSearchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) + self.inboxSearchOptionCB.setItemText(3, _translate("MainWindow", "Subject", None)) + self.inboxSearchOptionCB.setItemText(4, _translate("MainWindow", "Message", None)) self.tableWidgetInbox.setSortingEnabled(True) item = self.tableWidgetInbox.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "To", None)) diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index 65ad632d..2be3385d 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -83,10 +83,10 @@ 0 - + - + All @@ -109,7 +109,7 @@ - Received + Message From 997a8ff13ac5a311cece8f609de00b7c86447270 Mon Sep 17 00:00:00 2001 From: Rainulf Pineda Date: Fri, 12 Jul 2013 04:42:52 -0400 Subject: [PATCH 83/93] Sent search. --- src/bitmessageqt/__init__.py | 39 +++++++++++++++++--- src/bitmessageqt/bitmessageui.py | 26 +++++++++++-- src/bitmessageqt/bitmessageui.ui | 63 ++++++++++++++++++++++++++------ 3 files changed, 108 insertions(+), 20 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 8f3042a0..92209bbe 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -336,6 +336,10 @@ class MyForm(QtGui.QMainWindow): QtCore.QObject.connect(self.ui.inboxSearchLineEdit, QtCore.SIGNAL( "returnPressed()"), self.inboxSearchLineEditPressed) + # Initialize the sent search + QtCore.QObject.connect(self.ui.sentSearchLineEdit, QtCore.SIGNAL( + "returnPressed()"), self.sentSearchLineEditPressed) + # Initialize the Blacklist or Whitelist if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': self.loadBlackWhiteList() @@ -497,9 +501,29 @@ class MyForm(QtGui.QMainWindow): # Load Sent items from database def loadSent(self, where="", what=""): + what = "%" + what + "%" + if where == "To": + where = "toaddress" + elif where == "From": + where = "fromaddress" + elif where == "Subject": + where = "subject" + elif where == "Message": + where = "message" + else: + where = "toaddress || fromaddress || subject || message" + + sqlQuery = ''' + SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime + FROM sent WHERE folder="sent" AND %s LIKE "%s" + ORDER BY lastactiontime + ''' % (where, what) + + while self.ui.tableWidgetSent.rowCount() > 0: + self.ui.tableWidgetSent.removeRow(0) + shared.sqlLock.acquire() - shared.sqlSubmitQueue.put( - '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent where folder = 'sent' ORDER BY lastactiontime''') + shared.sqlSubmitQueue.put(sqlQuery) shared.sqlSubmitQueue.put('') queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() @@ -610,12 +634,10 @@ class MyForm(QtGui.QMainWindow): where = "fromaddress" elif where == "Subject": where = "subject" - elif where == "Received": - where = "received" elif where == "Message": where = "message" else: - where = "toaddress || fromaddress || subject || received || message" + where = "toaddress || fromaddress || subject || message" sqlQuery = ''' SELECT msgid, toaddress, fromaddress, subject, received, message, read @@ -2548,6 +2570,13 @@ class MyForm(QtGui.QMainWindow): self.ui.textEditInboxMessage.setPlainText(QString("")) self.loadInbox(searchOption, searchKeyword) + def sentSearchLineEditPressed(self): + searchKeyword = self.ui.sentSearchLineEdit.text().toUtf8().data() + searchOption = self.ui.sentSearchOptionCB.currentText().toUtf8().data() + self.ui.sentSearchLineEdit.setText(QString("")) + self.ui.textEditInboxMessage.setPlainText(QString("")) + self.loadSent(searchOption, searchKeyword) + def tableWidgetInboxItemClicked(self): currentRow = self.ui.tableWidgetInbox.currentRow() if currentRow >= 0: diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index ff23fa82..62466503 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'bitmessageui.ui' # -# Created: Fri Jul 12 04:16:52 2013 +# Created: Fri Jul 12 04:40:47 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! @@ -172,6 +172,21 @@ class Ui_MainWindow(object): self.sent.setObjectName(_fromUtf8("sent")) self.verticalLayout = QtGui.QVBoxLayout(self.sent) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) + self.horizontalLayout = QtGui.QHBoxLayout() + self.horizontalLayout.setContentsMargins(-1, 0, -1, -1) + self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) + self.sentSearchLineEdit = QtGui.QLineEdit(self.sent) + self.sentSearchLineEdit.setObjectName(_fromUtf8("sentSearchLineEdit")) + self.horizontalLayout.addWidget(self.sentSearchLineEdit) + self.sentSearchOptionCB = QtGui.QComboBox(self.sent) + self.sentSearchOptionCB.setObjectName(_fromUtf8("sentSearchOptionCB")) + self.sentSearchOptionCB.addItem(_fromUtf8("")) + self.sentSearchOptionCB.addItem(_fromUtf8("")) + self.sentSearchOptionCB.addItem(_fromUtf8("")) + self.sentSearchOptionCB.addItem(_fromUtf8("")) + self.sentSearchOptionCB.addItem(_fromUtf8("")) + self.horizontalLayout.addWidget(self.sentSearchOptionCB) + self.verticalLayout.addLayout(self.horizontalLayout) self.tableWidgetSent = QtGui.QTableWidget(self.sent) self.tableWidgetSent.setDragDropMode(QtGui.QAbstractItemView.DragDrop) self.tableWidgetSent.setAlternatingRowColors(True) @@ -407,7 +422,7 @@ class Ui_MainWindow(object): self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 20)) + self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) @@ -504,7 +519,7 @@ class Ui_MainWindow(object): self.textEditMessage.setHtml(_translate("MainWindow", "\n" "\n" +"\n" "


", None)) self.label.setText(_translate("MainWindow", "To:", None)) self.label_2.setText(_translate("MainWindow", "From:", None)) @@ -512,6 +527,11 @@ class Ui_MainWindow(object): self.pushButtonSend.setText(_translate("MainWindow", "Send", None)) self.labelSendBroadcastWarning.setText(_translate("MainWindow", "Be aware that broadcasts are only encrypted with your address. Anyone who knows your address can read them.", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.send), _translate("MainWindow", "Send", None)) + self.sentSearchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) + self.sentSearchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) + self.sentSearchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) + self.sentSearchOptionCB.setItemText(3, _translate("MainWindow", "Subject", None)) + self.sentSearchOptionCB.setItemText(4, _translate("MainWindow", "Message", None)) self.tableWidgetSent.setSortingEnabled(True) item = self.tableWidgetSent.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "To", None)) diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index 2be3385d..46ebd06a 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -14,7 +14,7 @@ Bitmessage - + :/newPrefix/images/can-icon-24px.png:/newPrefix/images/can-icon-24px.png @@ -70,7 +70,7 @@ - + :/newPrefix/images/inbox.png:/newPrefix/images/inbox.png @@ -193,7 +193,7 @@ - + :/newPrefix/images/send.png:/newPrefix/images/send.png @@ -262,7 +262,7 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> +</style></head><body style=" font-family:'Sans'; font-size:9pt; font-weight:400; font-style:normal;"> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2';"><br /></p></body></html> @@ -351,13 +351,52 @@ p, li { white-space: pre-wrap; }
- + :/newPrefix/images/sent.png:/newPrefix/images/sent.png Sent + + + + 0 + + + + + + + + + All + + + + + To + + + + + From + + + + + Subject + + + + + Message + + + + + + @@ -428,7 +467,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/identities.png:/newPrefix/images/identities.png @@ -528,7 +567,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/subscriptions.png:/newPrefix/images/subscriptions.png @@ -613,7 +652,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/addressbook.png:/newPrefix/images/addressbook.png @@ -695,7 +734,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/blacklist.png:/newPrefix/images/blacklist.png @@ -787,7 +826,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/networkstatus.png:/newPrefix/images/networkstatus.png @@ -806,7 +845,7 @@ p, li { white-space: pre-wrap; } - + :/newPrefix/images/redicon.png:/newPrefix/images/redicon.png @@ -973,7 +1012,7 @@ p, li { white-space: pre-wrap; } 0 0 795 - 20 + 25 From a3cdc28bbf156795f7ebbf04d2ee0e04a78440f7 Mon Sep 17 00:00:00 2001 From: Rainulf Pineda Date: Fri, 12 Jul 2013 05:02:21 -0400 Subject: [PATCH 84/93] Fixed crash on sql query. --- src/bitmessageqt/__init__.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 92209bbe..316f4205 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -515,16 +515,17 @@ class MyForm(QtGui.QMainWindow): sqlQuery = ''' SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime - FROM sent WHERE folder="sent" AND %s LIKE "%s" + FROM sent WHERE folder="sent" AND %s LIKE ? ORDER BY lastactiontime - ''' % (where, what) + ''' % (where,) while self.ui.tableWidgetSent.rowCount() > 0: self.ui.tableWidgetSent.removeRow(0) + t = (what,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put(sqlQuery) - shared.sqlSubmitQueue.put('') + shared.sqlSubmitQueue.put(t) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() for row in queryreturn: @@ -641,18 +642,19 @@ class MyForm(QtGui.QMainWindow): sqlQuery = ''' SELECT msgid, toaddress, fromaddress, subject, received, message, read - FROM inbox WHERE folder="inbox" AND %s LIKE "%s" + FROM inbox WHERE folder="inbox" AND %s LIKE ? ORDER BY received - ''' % (where, what) + ''' % (where,) while self.ui.tableWidgetInbox.rowCount() > 0: self.ui.tableWidgetInbox.removeRow(0) font = QFont() font.setBold(True) + t = (what,) shared.sqlLock.acquire() shared.sqlSubmitQueue.put(sqlQuery) - shared.sqlSubmitQueue.put('') + shared.sqlSubmitQueue.put(t) queryreturn = shared.sqlReturnQueue.get() shared.sqlLock.release() for row in queryreturn: From 10b23d0946c0b3b3ee4f9cd8a9d0b4e27d3c1e06 Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Fri, 12 Jul 2013 10:36:28 +0100 Subject: [PATCH 85/93] Packaging for multiple distros --- Makefile | 70 ++++---- arch.sh | 45 +++++ archpackage/PKGBUILD | 31 ++++ configure | 1 + debian.sh | 52 ++++-- debian/changelog | 4 +- debian/compat | 2 +- debian/control | 34 ++-- debian/copyright | 40 ++--- debian/manpages | 1 + debian/rules | 86 ++++----- desktop/icon14.xpm | 111 ++++++++++++ desktop/icon24.png | Bin 0 -> 1852 bytes desktop/pybitmessage.desktop | 27 +-- ebuild.sh | 33 ++++ ebuildpackage/pybitmessage-0.3.4-1.ebuild | 22 +++ generate.sh | 7 + man/pybitmessage.1.gz | Bin 0 -> 546 bytes puppy.sh | 66 +++++++ puppypackage/icon14.xpm | 111 ++++++++++++ puppypackage/pybitmessage-0.3.4.pet.specs | 1 + rpm.sh | 53 ++++++ rpmpackage/pybitmessage.spec | 207 ++++++++++++++++++++++ slack.sh | 48 +++++ slackpackage/doinst.sh | 4 + slackpackage/slack-desc | 19 ++ 26 files changed, 903 insertions(+), 172 deletions(-) mode change 100755 => 100644 Makefile create mode 100755 arch.sh create mode 100644 archpackage/PKGBUILD create mode 100755 configure create mode 100644 debian/manpages create mode 100644 desktop/icon14.xpm create mode 100644 desktop/icon24.png create mode 100755 ebuild.sh create mode 100755 ebuildpackage/pybitmessage-0.3.4-1.ebuild create mode 100755 generate.sh create mode 100644 man/pybitmessage.1.gz create mode 100755 puppy.sh create mode 100644 puppypackage/icon14.xpm create mode 100644 puppypackage/pybitmessage-0.3.4.pet.specs create mode 100755 rpm.sh create mode 100644 rpmpackage/pybitmessage.spec create mode 100755 slack.sh create mode 100755 slackpackage/doinst.sh create mode 100644 slackpackage/slack-desc diff --git a/Makefile b/Makefile old mode 100755 new mode 100644 index afb6744e..92b4e633 --- a/Makefile +++ b/Makefile @@ -1,43 +1,45 @@ APP=pybitmessage VERSION=0.3.4 -DEST_SHARE=${DESTDIR}/usr/share -DEST_APP=${DEST_SHARE}/${APP} +RELEASE=1 +ARCH_TYPE=`uname -m` all: - debug: - source: tar -cvzf ../${APP}_${VERSION}.orig.tar.gz ../${APP}-${VERSION} --exclude-vcs - install: - mkdir -m 755 -p ${DESTDIR}/usr/bin - mkdir -m 755 -p ${DEST_APP} - mkdir -m 755 -p ${DEST_SHARE}/applications - mkdir -m 755 -p ${DEST_APP}/images - mkdir -m 755 -p ${DEST_APP}/pyelliptic - mkdir -m 755 -p ${DEST_APP}/socks - mkdir -m 755 -p ${DEST_APP}/bitmessageqt - mkdir -m 755 -p ${DEST_APP}/translations - mkdir -m 755 -p ${DEST_SHARE}/pixmaps - mkdir -m 755 -p ${DEST_SHARE}/icons - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable/apps - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24 - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24/apps - - cp -r src/* ${DEST_APP} - install -m 755 debian/pybm ${DESTDIR}/usr/bin/${APP} - - install -m 644 desktop/${APP}.desktop ${DEST_SHARE}/applications/${APP}.desktop - install -m 644 src/images/can-icon-24px.png ${DEST_SHARE}/icons/hicolor/24x24/apps/${APP}.png - install -m 644 desktop/can-icon.svg ${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg - install -m 644 desktop/can-icon.svg ${DEST_SHARE}/pixmaps/${APP}.svg - + mkdir -p ${DESTDIR}/usr + mkdir -p ${DESTDIR}/usr/bin + mkdir -m 755 -p ${DESTDIR}/usr/share + mkdir -m 755 -p ${DESTDIR}/usr/share/man + mkdir -m 755 -p ${DESTDIR}/usr/share/man/man1 + install -m 644 man/${APP}.1.gz ${DESTDIR}/usr/share/man/man1 + mkdir -m 755 -p ${DESTDIR}/usr/share/${APP} + mkdir -m 755 -p ${DESTDIR}/usr/share/applications + mkdir -m 755 -p ${DESTDIR}/usr/share/pixmaps + mkdir -m 755 -p ${DESTDIR}/usr/share/icons + mkdir -m 755 -p ${DESTDIR}/usr/share/icons/hicolor + mkdir -m 755 -p ${DESTDIR}/usr/share/icons/hicolor/scalable + mkdir -m 755 -p ${DESTDIR}/usr/share/icons/hicolor/scalable/apps + mkdir -m 755 -p ${DESTDIR}/usr/share/icons/hicolor/24x24 + mkdir -m 755 -p ${DESTDIR}/usr/share/icons/hicolor/24x24/apps + install -m 644 desktop/${APP}.desktop ${DESTDIR}/usr/share/applications/${APP}.desktop + install -m 644 desktop/icon24.png ${DESTDIR}/usr/share/icons/hicolor/24x24/apps/${APP}.png + cp -rf src/* ${DESTDIR}/usr/share/${APP} + echo '#!/bin/sh' > ${DESTDIR}/usr/bin/${APP} + echo 'cd /usr/share/pybitmessage' >> ${DESTDIR}/usr/bin/${APP} + echo 'LD_LIBRARY_PATH="/opt/openssl-compat-bitcoin/lib/" exec python bitmessagemain.py' >> ${DESTDIR}/usr/bin/${APP} + chmod +x ${DESTDIR}/usr/bin/${APP} +uninstall: + rm -f /usr/share/man/man1/${APP}.1.gz + rm -rf /usr/share/${APP} + rm -f /usr/bin/${APP} + rm -f /usr/share/applications/${APP}.desktop + rm -f /usr/share/icons/hicolor/scalable/apps/${APP}.svg + /usr/share/pixmaps/${APP}.svg clean: - rm -rf debian/${APP} - rm -f ../${APP}_*.deb ../${APP}_*.asc ../${APP}_*.dsc ../${APP}*.changes - rm -f *.sh~ src/*.pyc src/socks/*.pyc src/pyelliptic/*.pyc - rm -f *.deb \#* \.#* debian/*.log debian/*.substvars - rm -f Makefile~ + rm -f ${APP} \#* \.#* gnuplot* *.png debian/*.substvars debian/*.log + rm -fr deb.* debian/${APP} rpmpackage/${ARCH_TYPE} + rm -f ../${APP}*.deb ../${APP}*.changes ../${APP}*.asc ../${APP}*.dsc + rm -f rpmpackage/*.src.rpm archpackage/*.gz + rm -f puppypackage/*.gz puppypackage/*.pet slackpackage/*.txz diff --git a/arch.sh b/arch.sh new file mode 100755 index 00000000..8917cef4 --- /dev/null +++ b/arch.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +APP=pybitmessage +PREV_VERSION=0.3.4 +VERSION=0.3.4 +RELEASE=1 +ARCH_TYPE=`uname -m` +CURRDIR=`pwd` +SOURCE=archpackage/${APP}-${VERSION}.tar.gz + +# Update version numbers automatically - so you don't have to +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile debian.sh rpm.sh puppy.sh ebuild.sh slack.sh +sed -i 's/Version: '${PREV_VERSION}'/Version: '${VERSION}'/g' rpmpackage/${APP}.spec +sed -i 's/Release: '${RELEASE}'/Release: '${RELEASE}'/g' rpmpackage/${APP}.spec +sed -i 's/pkgrel='${RELEASE}'/pkgrel='${RELEASE}'/g' archpackage/PKGBUILD +sed -i 's/pkgver='${PREV_VERSION}'/pkgver='${VERSION}'/g' archpackage/PKGBUILD +sed -i "s/-${PREV_VERSION}-/-${VERSION}-/g" puppypackage/*.specs +sed -i "s/|${PREV_VERSION}|/|${VERSION}|/g" puppypackage/*.specs +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' puppypackage/pinstall.sh puppypackage/puninstall.sh +sed -i 's/-'${PREV_VERSION}'.so/-'${VERSION}'.so/g' debian/*.links + + +# Create the source code +make clean +rm -f archpackage/*.gz + +# having the root directory called name-version seems essential +mv ../${APP} ../${APP}-${VERSION} +tar -cvzf ${SOURCE} ../${APP}-${VERSION} --exclude-vcs + +# rename the root directory without the version number +mv ../${APP}-${VERSION} ../${APP} + +# calculate the MD5 checksum +CHECKSM=$(md5sum ${SOURCE}) +sed -i "s/md5sums[^)]*)/md5sums=(${CHECKSM%% *})/g" archpackage/PKGBUILD + +cd archpackage + +# Create the package +makepkg + +# Move back to the original directory +cd ${CURRDIR} + diff --git a/archpackage/PKGBUILD b/archpackage/PKGBUILD new file mode 100644 index 00000000..a75d262a --- /dev/null +++ b/archpackage/PKGBUILD @@ -0,0 +1,31 @@ +# Maintainer: Bob Mottram (4096 bits) +pkgname=pybitmessage +pkgver=0.3.4 +pkgrel=1 +pkgdesc="Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide "non-content" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." +arch=('i686' 'x86_64') +url="https://github.com/Bitmessage/PyBitmessage" +license=('MIT') +groups=() +depends=() +makedepends=() +optdepends=() +provides=() +conflicts=() +replaces=() +backup=() +options=() +install= +changelog= +source=($pkgname-$pkgver.tar.gz) +noextract=() +md5sums=(56a8a225463e96b435b2a5b438006983) +build() { + cd "$srcdir/$pkgname-$pkgver" + ./configure --prefix=/usr + make +} +package() { + cd "$srcdir/$pkgname-$pkgver" + make DESTDIR="$pkgdir/" install +} diff --git a/configure b/configure new file mode 100755 index 00000000..0519ecba --- /dev/null +++ b/configure @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/debian.sh b/debian.sh index ac26380e..2d924251 100755 --- a/debian.sh +++ b/debian.sh @@ -1,32 +1,46 @@ -# To build a debian package first ensure that the code exists -# within a directory called pybitmessage-x.x.x (where the x's -# are the version number), make sure that the VERSION parameter -# within debian/rules and this script are correct, then run -# this script. - #!/bin/bash APP=pybitmessage -PREV_VERSION=0.3.3 +PREV_VERSION=0.3.4 VERSION=0.3.4 RELEASE=1 -ARCH_TYPE=all +ARCH_TYPE=`uname -m` +DIR=${APP}-${VERSION} -#update version numbers automatically - so you don't have to -sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile -sed -i 's/'''${PREV_VERSION}'''/'''${VERSION}'''/g' src/shared.py +if [ $ARCH_TYPE == "x86_64" ]; then + ARCH_TYPE="amd64" +fi +if [ $ARCH_TYPE == "i686" ]; then + ARCH_TYPE="i386" +fi + + +# Update version numbers automatically - so you don't have to +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile rpm.sh arch.sh puppy.sh ebuild.sh slack.sh +sed -i 's/Version: '${PREV_VERSION}'/Version: '${VERSION}'/g' rpmpackage/${APP}.spec +sed -i 's/Release: '${RELEASE}'/Release: '${RELEASE}'/g' rpmpackage/${APP}.spec +sed -i 's/pkgrel='${RELEASE}'/pkgrel='${RELEASE}'/g' archpackage/PKGBUILD +sed -i 's/pkgver='${PREV_VERSION}'/pkgver='${VERSION}'/g' archpackage/PKGBUILD +sed -i "s/-${PREV_VERSION}-/-${VERSION}-/g" puppypackage/*.specs +sed -i "s/|${PREV_VERSION}|/|${VERSION}|/g" puppypackage/*.specs +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' puppypackage/pinstall.sh puppypackage/puninstall.sh +sed -i 's/-'${PREV_VERSION}'.so/-'${VERSION}'.so/g' debian/*.links + +make clean +make + +# change the parent directory name to debian format +mv ../${APP} ../${DIR} # Create a source archive -make clean -# change the directory name to pybitmessage-version -mv ../PyBitmessage ../${APP}-${VERSION} make source # Build the package -dpkg-buildpackage -A +dpkg-buildpackage -F -# change the directory name back -mv ../${APP}-${VERSION} ../PyBitmessage - -gpg -ba ../${APP}_${VERSION}-${RELEASE}_${ARCH_TYPE}.deb +# sign files +gpg -ba ../${APP}_${VERSION}-1_${ARCH_TYPE}.deb gpg -ba ../${APP}_${VERSION}.orig.tar.gz + +# restore the parent directory name +mv ../${DIR} ../${APP} diff --git a/debian/changelog b/debian/changelog index 1d822cd1..b6e8adbf 100644 --- a/debian/changelog +++ b/debian/changelog @@ -18,7 +18,7 @@ pybitmessage (0.3.3-1) raring; urgency=low via Portage (Gentoo) * Fix message authentication bug - -- Bob Mottram (4096 bits) Sun, 30 June 2013 11:23:00 +0100 + -- Bob Mottram (4096 bits) Sat, 29 June 2013 11:23:00 +0100 pybitmessage (0.3.211-1) raring; urgency=low @@ -26,7 +26,7 @@ pybitmessage (0.3.211-1) raring; urgency=low as the multiprocessing module does not work well with pyinstaller's --onefile option. - -- Bob Mottram (4096 bits) Sun, 30 June 2013 11:23:00 +0100 + -- Bob Mottram (4096 bits) Fri, 28 June 2013 11:23:00 +0100 pybitmessage (0.3.2-1) raring; urgency=low diff --git a/debian/compat b/debian/compat index 45a4fb75..ec635144 100644 --- a/debian/compat +++ b/debian/compat @@ -1 +1 @@ -8 +9 diff --git a/debian/control b/debian/control index 2dd19194..de8f3a59 100644 --- a/debian/control +++ b/debian/control @@ -1,21 +1,21 @@ Source: pybitmessage -Section: contrib/comm Priority: extra -Maintainer: Jonathan Warren -Build-Depends: debhelper (>= 8.0.0), python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev, libmessaging-menu-dev -Standards-Version: 3.9.2 -Homepage: https://bitmessage.org/ -Vcs-Browser: https://github.com/Bitmessage/PyBitmessage -Vcs-Git: https://github.com/Bitmessage/PyBitmessage.git +Maintainer: Bob Mottram (4096 bits) +Build-Depends: debhelper (>= 9.0.0) +Standards-Version: 3.9.4 +Homepage: https://github.com/Bitmessage/PyBitmessage +Vcs-Git: https://github.com/fuzzgun/autocv.git Package: pybitmessage -Architecture: all -Depends: ${misc:Depends}, python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev, libmessaging-menu-dev -Description: Send encrypted messages to another person or to many subscribers - Bitmessage is a P2P communications protocol used to send encrypted messages - to another person or to many subscribers. It is decentralized and trustless, - meaning that you need-not inherently trust any entities like root certificate - authorities. It uses strong authentication which means that the sender of a - message cannot be spoofed, and it aims to hide "non-content" data, like the - sender and receiver of messages, from passive eavesdroppers like those - running warrantless wiretapping programs. +Section: mail +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends}, python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev +Suggests: libmessaging-menu-dev +Description: Send encrypted messages + Bitmessage is a P2P communications protocol used to send encrypted + messages to another person or to many subscribers. It is decentralized and + trustless, meaning that you need-not inherently trust any entities like + root certificate authorities. It uses strong authentication which means + that the sender of a message cannot be spoofed, and it aims to hide + "non-content" data, like the sender and receiver of messages, from passive + eavesdroppers like those running warrantless wiretapping programs. diff --git a/debian/copyright b/debian/copyright index 4c5f69f3..32f13f19 100644 --- a/debian/copyright +++ b/debian/copyright @@ -1,30 +1,30 @@ -Format: http://dep.debian.net/deps/dep5 -Upstream-Name: PyBitmessage -Source: https://github.com/Bitmessage/PyBitmessage +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: +Source: Files: * -Copyright: 2012 Jonathan Warren +Copyright: Copyright 2013 Bob Mottram (4096 bits) License: MIT Files: debian/* -Copyright: 2012 Jonathan Warren +Copyright: Copyright 2013 Bob Mottram (4096 bits) License: MIT License: MIT - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: . - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. . - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. \ No newline at end of file + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/manpages b/debian/manpages new file mode 100644 index 00000000..54af5648 --- /dev/null +++ b/debian/manpages @@ -0,0 +1 @@ +man/pybitmessage.1.gz diff --git a/debian/rules b/debian/rules index 2a7767b6..233679ca 100755 --- a/debian/rules +++ b/debian/rules @@ -1,66 +1,42 @@ #!/usr/bin/make -f -APP=pybitmessage -DESTDIR=${CURDIR}/debian/${APP} -DEST_SHARE=${DESTDIR}/usr/share -DEST_APP=${DEST_SHARE}/${APP} -build: build-stamp +APP=pybitmessage +build: build-stamp make build-arch: build-stamp build-indep: build-stamp build-stamp: - dh_testdir - touch build-stamp + dh_testdir + touch build-stamp + clean: - dh_testdir - dh_testroot - rm -f build-stamp - dh_clean -install: - dh_testdir - dh_testroot - dh_prep - dh_clean -k - dh_installdirs - - mkdir -m 755 -p ${DESTDIR}/usr/bin - mkdir -m 755 -p ${DEST_APP} - mkdir -m 755 -p ${DEST_SHARE}/applications - mkdir -m 755 -p ${DEST_APP}/images - mkdir -m 755 -p ${DEST_APP}/pyelliptic - mkdir -m 755 -p ${DEST_APP}/socks - mkdir -m 755 -p ${DEST_APP}/bitmessageqt - mkdir -m 755 -p ${DEST_APP}/translations - mkdir -m 755 -p ${DEST_SHARE}/pixmaps - mkdir -m 755 -p ${DEST_SHARE}/icons - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/scalable/apps - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24 - mkdir -m 755 -p ${DEST_SHARE}/icons/hicolor/24x24/apps - - cp -r src/* ${DEST_APP} - install -m 755 debian/pybm ${DESTDIR}/usr/bin/${APP} - - install -m 644 desktop/${APP}.desktop ${DEST_SHARE}/applications/${APP}.desktop - install -m 644 src/images/can-icon-24px.png ${DEST_SHARE}/icons/hicolor/24x24/apps/${APP}.png - install -m 644 desktop/can-icon.svg ${DEST_SHARE}/icons/hicolor/scalable/apps/${APP}.svg - install -m 644 desktop/can-icon.svg ${DEST_SHARE}/pixmaps/${APP}.svg + dh_testdir + dh_testroot + rm -f build-stamp + dh_clean +install: build clean + dh_testdir + dh_testroot + dh_prep + dh_installdirs + ${MAKE} install -B DESTDIR=${CURDIR}/debian/${APP} binary-indep: build install - dh_shlibdeps - dh_testdir - dh_testroot - dh_installchangelogs - dh_installdocs -# dh_installman - dh_link - dh_compress - dh_fixperms - dh_installdeb - dh_gencontrol - dh_md5sums - dh_builddeb + dh_testdir + dh_testroot + dh_installchangelogs + dh_installdocs + dh_installexamples + dh_installman + dh_link + dh_compress + dh_fixperms + dh_installdeb + dh_gencontrol + dh_md5sums + dh_builddeb + binary-arch: build install + binary: binary-indep binary-arch -.PHONY: build clean binary-indep binary install +.PHONY: build clean binary-indep binary-arch binary install diff --git a/desktop/icon14.xpm b/desktop/icon14.xpm new file mode 100644 index 00000000..6d50c8c7 --- /dev/null +++ b/desktop/icon14.xpm @@ -0,0 +1,111 @@ +/* XPM */ +static char * icon14_xpm[] = { +"14 14 94 2", +" c None", +". c #B9BABC", +"+ c #D2D3D4", +"@ c #BEBFC1", +"# c #CBCCCF", +"$ c #E0E3E1", +"% c #F6F8F8", +"& c #F3F3F3", +"* c #B9BABD", +"= c #C8C9CB", +"- c #DADCDB", +"; c #E6E8E7", +"> c #F7F7F7", +", c #FCFCFC", +"' c #F5F5F5", +") c #BCBDBF", +"! c #D3D5D5", +"~ c #E3E5E4", +"{ c #F1F2F2", +"] c #FDFDFD", +"^ c #F8F8F8", +"/ c #CBCCCC", +"( c #B2B3B6", +"_ c #B0B1B3", +": c #D3D4D6", +"< c #DFE0E0", +"[ c #EAEDEB", +"} c #FAF9F9", +"| c #DFE0DF", +"1 c #B9BBBD", +"2 c #C2C3C5", +"3 c #B7B8BC", +"4 c #CDCED0", +"5 c #DCDDDE", +"6 c #E7E9E7", +"7 c #F6F6F6", +"8 c #C0C1C2", +"9 c #DDDFDF", +"0 c #BCBCBF", +"a c #D7D9DA", +"b c #E2E4E3", +"c c #F0F2F1", +"d c #FAFAFA", +"e c #F9F9F9", +"f c #CCCDCD", +"g c #B6B7B9", +"h c #C7C8CA", +"i c #A6A7A9", +"j c #D3D4D5", +"k c #F2F5F3", +"l c #F1F2F1", +"m c #F6F8F7", +"n c #FCFBFC", +"o c #E8EAE9", +"p c #B6B7B8", +"q c #BFC0C2", +"r c #323138", +"s c #1D1D22", +"t c #111117", +"u c #4C4C51", +"v c #ECECED", +"w c #FFFFFF", +"x c #BBBDBD", +"y c #C9CACB", +"z c #333238", +"A c #313036", +"B c #27272C", +"C c #1E1F24", +"D c #16171D", +"E c #919193", +"F c #F2F3F3", +"G c #B4B5B7", +"H c #CDCFCF", +"I c #67666B", +"J c #37363C", +"K c #2C2B31", +"L c #2A292F", +"M c #16171C", +"N c #68696B", +"O c #C7C8C9", +"P c #CBCDCC", +"Q c #49474E", +"R c #39383E", +"S c #36353B", +"T c #333138", +"U c #28272D", +"V c #CED0D0", +"W c #67676C", +"X c #414046", +"Y c #424147", +"Z c #39383F", +"` c #8C8D8F", +" . c #6B6C70", +".. c #75757A", +" . + ", +" @ # $ % & ", +" * = - ; > , ' ", +" ) ! ~ { ] ^ / ( ", +" _ : < [ } , | 1 2 ", +" 3 4 5 6 7 , { 8 . 9 ", +" 2 0 a b c d e f g h ", +" i j k l m n o p q h ", +" r s t u v w ' x g y ", +" z A B C D E F G H ", +" I J A K L M N O P ", +" Q R R S T U V ", +" W X Y X Z ` ", +" ... "}; diff --git a/desktop/icon24.png b/desktop/icon24.png new file mode 100644 index 0000000000000000000000000000000000000000..30f7313eb378b69c4e2f6cb66264c2ae678059e1 GIT binary patch literal 1852 zcmV-C2gCS@P)M^!E?E!Z`=4*Xy`ht_>fhjLl+eV_hy>=-Ek(A(EP8wh@6>5>i{Jah=UrfpOJpyyEE@4x%__we9`O^8Gz zY+YB^0D>Su5CjlH;N;0u?*~Bu&N&bS0ppzGa8EB4rY4DVPDBKSF-HCU16P-HEJ7j{ zNB_V8#>OVLvurL0*LBHtT@Xo}Jb4<4WQ?)(U)V^qv$OC6A8)<&J1DB6+N!HAqgS40M1-^F1`!DUX8C&gnRGe@ zugOKk3q#X23}v$zA1@%4ZpGc13}Zxu2iAXy3X>BMLSomhm+{n7Pk?idful#^*Ezyr z?^5Ynsk5uAtC7-^+n#tfol2v%r3J6O`Z`vx?m{NB3ZCb|_3ZsV_dC<+bR%^l!h!ug z@VU>%#>bmZoH+5fD_6!g$w1(jJD&Yfx-GS5)rys1j5Ug#pWXb-IOmw2o?hS6(|2Sf zpMOr0oWEy8bh}FcG{zVdMbZCv^7OGpGT!ZY?yDjYR4SFe34j4u5I6t=RaNovCkHF@ zoiaipD2jq)GP(ESrQv7p6jU1RJ^w~D8qrNF1lzV@nHGW|z_EWH$MA4|HvlM%F)+q3 zSF1lXI(qr%k!S>tSt5A%%qNy7fY#@OJ=EhAw1( z_N}dtZ{57*k%%G? zyxTA|2q7B+k`g<9wZry251!{C8jT8 z-p;x=cW;j;6M^e_Sar{;s;=ulO|_=rc^-)9w)un*3;rOYd80A9^_8lsC>CeFcKY<0 z4{lZ}Ry-a%wttgbW>)Wx=%_7={5wQBW?I>Bfy4Z=_PG=NJe~Q9lP@w~J_0!8!Mi z9zFhP-S^kT<8fHF3CFQv7zRw!gk#&#H626*-}f;&HHG}>D5{mY;+HpXy5F+Q%Xe-M z0U*X0G)+UPbnTIkKRHlVHEm6MdpjbL2t3b)X_;^w2d-^HS2Yk3s?{on^CK7@$wLGZ zp64ZohO$2d01W`9rl;?qQ0VgL*oRY7S08R~Z--+$Fw77_rVcY?z%ng_LLsP%0zrgw zxr|)yA}WL9CMO3t=b?@zi(yy>Of!T~C+VOB*94LhM2&|}VG20s7@sU4HnuD?>4oOphsFb>PI zZUf%`%U?g-yLaC=7-Oi_YVf%apL0|y71Zl>Y~1)DcJ6!;YuDTZB0_HPA}(DTUI=X2 zCW^)4PlABI9SVie+1UxpvTpCezI`9Hzx&R+{}~^jXqkryAs~c+loA9&&G%88o5S~i zunk+bJl6RAN16Z-N~LQLgR%WmN-SO4fpAk3q?Bk*BpZN(hk5|U(0jP|^`65=ej%iQ zs;ZDuEGZ;^06r_>FlqtwW!jai!%a;Br5)J=X qQ5iHQ#>b literal 0 HcmV?d00001 diff --git a/desktop/pybitmessage.desktop b/desktop/pybitmessage.desktop index 2b1b6902..a97bd664 100644 --- a/desktop/pybitmessage.desktop +++ b/desktop/pybitmessage.desktop @@ -2,29 +2,8 @@ Type=Application Name=PyBitmessage GenericName=PyBitmessage -X-GNOME-FullName=PyBitmessage Secure Messaging -Comment=Send encrypted messages to another person or to many subscribers -Exec=pybitmessage %U +Comment=Send encrypted messages +Exec=pybitmessage %F Icon=pybitmessage Terminal=false -Categories=Network;Email;Application; -Keywords=Email;E-mail;Newsgroup;Messaging; -X-MessagingMenu-UsesChatSection=true -X-Ubuntu-Gettext-Domain=pybitmessage - -Actions=Send;Subscribe;AddressBook; - -[Desktop Action Send] -Name=Send -Exec=pybitmessage -s -OnlyShowIn=Unity; - -[Desktop Action Subscribe] -Name=Subscribe -Exec=pybitmessage -b -OnlyShowIn=Unity; - -[Desktop Action AddressBook] -Name=Address Book -Exec=pybitmessage -a -OnlyShowIn=Unity; +Categories=Office;Email; diff --git a/ebuild.sh b/ebuild.sh new file mode 100755 index 00000000..1a3d16e0 --- /dev/null +++ b/ebuild.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +APP=pybitmessage +PREV_VERSION=0.3.4 +VERSION=0.3.4 +RELEASE=1 +SOURCEDIR=. +ARCH_TYPE=`uname -m` +CURRDIR=`pwd` +SOURCE=~/ebuild/${APP}-${VERSION}.tar.gz + + +# Update version numbers automatically - so you don't have to +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile debian.sh rpm.sh arch.sh puppy.sh slack.sh +sed -i 's/Version: '${PREV_VERSION}'/Version: '${VERSION}'/g' rpmpackage/${APP}.spec +sed -i 's/Release: '${RELEASE}'/Release: '${RELEASE}'/g' rpmpackage/${APP}.spec +sed -i 's/pkgrel='${RELEASE}'/pkgrel='${RELEASE}'/g' archpackage/PKGBUILD +sed -i 's/pkgver='${PREV_VERSION}'/pkgver='${VERSION}'/g' archpackage/PKGBUILD +sed -i "s/-${PREV_VERSION}-/-${VERSION}-/g" puppypackage/*.specs +sed -i "s/|${PREV_VERSION}|/|${VERSION}|/g" puppypackage/*.specs +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' puppypackage/pinstall.sh puppypackage/puninstall.sh +sed -i 's/-'${PREV_VERSION}'.so/-'${VERSION}'.so/g' debian/*.links + +# create the source code in the SOURCES directory +make clean +mkdir -p ~/ebuild +rm -f ${SOURCE} +mv ../${APP} ../${APP}-${VERSION} +tar -cvzf ${SOURCE} ../${APP}-${VERSION} --exclude-vcs + +# rename the root directory without the version number +mv ../${APP}-${VERSION} ../${APP} + diff --git a/ebuildpackage/pybitmessage-0.3.4-1.ebuild b/ebuildpackage/pybitmessage-0.3.4-1.ebuild new file mode 100755 index 00000000..20f056e4 --- /dev/null +++ b/ebuildpackage/pybitmessage-0.3.4-1.ebuild @@ -0,0 +1,22 @@ +# $Header: $ + +EAPI=4 + +DESCRIPTION="Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide "non-content" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." +HOMEPAGE="https://github.com/Bitmessage/PyBitmessage" +SRC_URI="${PN}/${P}.tar.gz" +LICENSE="MIT" +SLOT="0" +KEYWORDS="x86" +RDEPEND="dev-libs/popt" +DEPEND="${RDEPEND}" + +src_configure() { + econf --with-popt +} + +src_install() { + emake DESTDIR="${D}" install + # Install README and (Debian) changelog + dodoc README.md debian/changelog +} diff --git a/generate.sh b/generate.sh new file mode 100755 index 00000000..92bda853 --- /dev/null +++ b/generate.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Generates packaging + +rm -f Makefile rpmpackage/*.spec + +packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl" diff --git a/man/pybitmessage.1.gz b/man/pybitmessage.1.gz new file mode 100644 index 0000000000000000000000000000000000000000..efa686a8c9831c74114a4f0a6e0f4d477bbbc078 GIT binary patch literal 546 zcmV+-0^R)|iwFq(6W>t)18{j_X>@I6b8}&5WiBxQrBY3g(?ATp=T}&{08*Q77lZ^t zh%QvLs9$Q@8<$BkZAP1nBipl8`1LqRt1f4xxy;yp&+pAk4hv}7%t>vT&Dp{f;^`EA zg$f=Yrtf2j^&HvK8-}&S_B<|G7uwa6eNPS1ou2L9S2$i9$b>o9xxRfq0dwL$owc1No zS$I;5Zhqy)ck5(YZ4ghk81)*QF68RojnWksVvl~DqZj3fp)g`b!;-IXyE#%f+{-|6 zvvdR}!WtUGtR=AK#d1N|boSmrkX3K+y;&DSWPI-+TpU?3P1C*W7oN$~oLnQY+@y!u zYBd`&5G_56sj5N0(+h=s`1`YpP_rRPZlmdZ4zpFd)v=lSPFBad5E$R|A-H!w9e<{A zw6_hCx)jbDFL_m-9S@7`UK5BJtWh)vHN5@s@aZFH>iHdf$uRpyn4$g*C*e5}{2C=0 kMadFMk%m7{CTAyQ$Px|g> ${APP}-${VERSION}-${RELEASE}.tar.gz +sync +mv -f ${APP}-${VERSION}-${RELEASE}.tar.gz ${APP}-${VERSION}-${RELEASE}.pet +sync +cd ${CURRDIR} + +# Remove the temporary build directory +rm -fr ${BUILDDIR} diff --git a/puppypackage/icon14.xpm b/puppypackage/icon14.xpm new file mode 100644 index 00000000..6d50c8c7 --- /dev/null +++ b/puppypackage/icon14.xpm @@ -0,0 +1,111 @@ +/* XPM */ +static char * icon14_xpm[] = { +"14 14 94 2", +" c None", +". c #B9BABC", +"+ c #D2D3D4", +"@ c #BEBFC1", +"# c #CBCCCF", +"$ c #E0E3E1", +"% c #F6F8F8", +"& c #F3F3F3", +"* c #B9BABD", +"= c #C8C9CB", +"- c #DADCDB", +"; c #E6E8E7", +"> c #F7F7F7", +", c #FCFCFC", +"' c #F5F5F5", +") c #BCBDBF", +"! c #D3D5D5", +"~ c #E3E5E4", +"{ c #F1F2F2", +"] c #FDFDFD", +"^ c #F8F8F8", +"/ c #CBCCCC", +"( c #B2B3B6", +"_ c #B0B1B3", +": c #D3D4D6", +"< c #DFE0E0", +"[ c #EAEDEB", +"} c #FAF9F9", +"| c #DFE0DF", +"1 c #B9BBBD", +"2 c #C2C3C5", +"3 c #B7B8BC", +"4 c #CDCED0", +"5 c #DCDDDE", +"6 c #E7E9E7", +"7 c #F6F6F6", +"8 c #C0C1C2", +"9 c #DDDFDF", +"0 c #BCBCBF", +"a c #D7D9DA", +"b c #E2E4E3", +"c c #F0F2F1", +"d c #FAFAFA", +"e c #F9F9F9", +"f c #CCCDCD", +"g c #B6B7B9", +"h c #C7C8CA", +"i c #A6A7A9", +"j c #D3D4D5", +"k c #F2F5F3", +"l c #F1F2F1", +"m c #F6F8F7", +"n c #FCFBFC", +"o c #E8EAE9", +"p c #B6B7B8", +"q c #BFC0C2", +"r c #323138", +"s c #1D1D22", +"t c #111117", +"u c #4C4C51", +"v c #ECECED", +"w c #FFFFFF", +"x c #BBBDBD", +"y c #C9CACB", +"z c #333238", +"A c #313036", +"B c #27272C", +"C c #1E1F24", +"D c #16171D", +"E c #919193", +"F c #F2F3F3", +"G c #B4B5B7", +"H c #CDCFCF", +"I c #67666B", +"J c #37363C", +"K c #2C2B31", +"L c #2A292F", +"M c #16171C", +"N c #68696B", +"O c #C7C8C9", +"P c #CBCDCC", +"Q c #49474E", +"R c #39383E", +"S c #36353B", +"T c #333138", +"U c #28272D", +"V c #CED0D0", +"W c #67676C", +"X c #414046", +"Y c #424147", +"Z c #39383F", +"` c #8C8D8F", +" . c #6B6C70", +".. c #75757A", +" . + ", +" @ # $ % & ", +" * = - ; > , ' ", +" ) ! ~ { ] ^ / ( ", +" _ : < [ } , | 1 2 ", +" 3 4 5 6 7 , { 8 . 9 ", +" 2 0 a b c d e f g h ", +" i j k l m n o p q h ", +" r s t u v w ' x g y ", +" z A B C D E F G H ", +" I J A K L M N O P ", +" Q R R S T U V ", +" W X Y X Z ` ", +" ... "}; diff --git a/puppypackage/pybitmessage-0.3.4.pet.specs b/puppypackage/pybitmessage-0.3.4.pet.specs new file mode 100644 index 00000000..81060a27 --- /dev/null +++ b/puppypackage/pybitmessage-0.3.4.pet.specs @@ -0,0 +1 @@ +pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|3.9M||pybitmessage-0.3.4-1.pet||Send encrypted messages|ubuntu|precise|5| diff --git a/rpm.sh b/rpm.sh new file mode 100755 index 00000000..8269ed9c --- /dev/null +++ b/rpm.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +APP=pybitmessage +PREV_VERSION=0.3.4 +VERSION=0.3.4 +RELEASE=1 +SOURCEDIR=. +ARCH_TYPE=`uname -m` +CURRDIR=`pwd` +SOURCE=~/rpmbuild/SOURCES/${APP}_${VERSION}.orig.tar.gz + + +# Update version numbers automatically - so you don't have to +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile debian.sh arch.sh puppy.sh ebuild.sh slack.sh +sed -i 's/Version: '${PREV_VERSION}'/Version: '${VERSION}'/g' rpmpackage/${APP}.spec +sed -i 's/Release: '${RELEASE}'/Release: '${RELEASE}'/g' rpmpackage/${APP}.spec +sed -i 's/pkgrel='${RELEASE}'/pkgrel='${RELEASE}'/g' archpackage/PKGBUILD +sed -i 's/pkgver='${PREV_VERSION}'/pkgver='${VERSION}'/g' archpackage/PKGBUILD +sed -i "s/-${PREV_VERSION}-/-${VERSION}-/g" puppypackage/*.specs +sed -i "s/|${PREV_VERSION}|/|${VERSION}|/g" puppypackage/*.specs +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' puppypackage/pinstall.sh puppypackage/puninstall.sh +sed -i 's/-'${PREV_VERSION}'.so/-'${VERSION}'.so/g' debian/*.links + +sudo yum groupinstall "Development Tools" +sudo yum install rpmdevtools + +# setup the rpmbuild directory tree +rpmdev-setuptree + +# create the source code in the SOURCES directory +make clean +mkdir -p ~/rpmbuild/SOURCES +rm -f ${SOURCE} + +# having the root directory called name-version seems essential +mv ../${APP} ../${APP}-${VERSION} +tar -cvzf ${SOURCE} ../${APP}-${VERSION} --exclude-vcs + +# rename the root directory without the version number +mv ../${APP}-${VERSION} ../${APP} + +# copy the spec file into the SPECS directory +cp -f rpmpackage/${APP}.spec ~/rpmbuild/SPECS + +# build +cd ~/rpmbuild/SPECS +rpmbuild -ba ${APP}.spec +cd ${CURRDIR} + +# Copy the results into the rpmpackage directory +mkdir -p rpmpackage/${ARCH_TYPE} +cp -r ~/rpmbuild/RPMS/${ARCH_TYPE}/${APP}* rpmpackage/${ARCH_TYPE} +cp -r ~/rpmbuild/SRPMS/${APP}* rpmpackage diff --git a/rpmpackage/pybitmessage.spec b/rpmpackage/pybitmessage.spec new file mode 100644 index 00000000..27485d73 --- /dev/null +++ b/rpmpackage/pybitmessage.spec @@ -0,0 +1,207 @@ +Name: pybitmessage +Version: 0.3.4 +Release: 1%{?dist} +Summary: Send encrypted messages +License: MIT +URL: https://github.com/Bitmessage/PyBitmessage +Packager: Bob Mottram (4096 bits) +Source0: http://yourdomainname.com/src/%{name}_%{version}.orig.tar.gz +Group: Office/Email + +Requires: python, PyQt4, openssl-compat-bitcoin-libs + + +%description +Bitmessage is a P2P communications protocol used to send encrypted messages +to another person or to many subscribers. It is decentralized and +trustless, meaning that you need-not inherently trust any entities like +root certificate authorities. It uses strong authentication which means +that the sender of a message cannot be spoofed, and it aims to hide +"non-content" data, like the sender and receiver of messages, from passive +eavesdroppers like those running warrantless wiretapping programs. + +%prep +%setup -q + +%build +%configure +make %{?_smp_mflags} + +%install +rm -rf %{buildroot} +mkdir -p %{buildroot} +mkdir -p %{buildroot}/etc +mkdir -p %{buildroot}/etc/%{name} +mkdir -p %{buildroot}/usr +mkdir -p %{buildroot}/usr/bin +mkdir -p %{buildroot}/usr/share +mkdir -p %{buildroot}/usr/share/man +mkdir -p %{buildroot}/usr/share/man/man1 +mkdir -p %{buildroot}/usr/share/%{name} +mkdir -p %{buildroot}/usr/share/applications +mkdir -p %{buildroot}/usr/share/icons +mkdir -p %{buildroot}/usr/share/icons/hicolor +mkdir -p %{buildroot}/usr/share/icons/hicolor/24x24 +mkdir -p %{buildroot}/usr/share/icons/hicolor/24x24/apps + +mkdir -p %{buildroot}/usr/share/pixmaps +mkdir -p %{buildroot}/usr/share/icons/hicolor/scalable +mkdir -p %{buildroot}/usr/share/icons/hicolor/scalable/apps +# Make install but to the RPM BUILDROOT directory +make install -B DESTDIR=%{buildroot} + +%files +%doc README.md LICENSE +%defattr(-,root,root,-) +%dir /usr/share/%{name} +%dir /usr/share/applications +%dir /usr/share/icons/hicolor +%dir /usr/share/icons/hicolor/24x24 +%dir /usr/share/icons/hicolor/24x24/apps +%dir /usr/share/pixmaps +%dir /usr/share/icons/hicolor/scalable +%dir /usr/share/icons/hicolor/scalable/apps +/usr/share/%{name}/* +%{_bindir}/* +%{_mandir}/man1/* +%attr(644,root,root) /usr/share/applications/%{name}.desktop +%attr(644,root,root) /usr/share/icons/hicolor/24x24/apps/%{name}.png + +%changelog +* Sun Jun 30 2013 Bob Mottram (4096 bits) - 0.3.4-1 +- Switched addr, msg, broadcast, and getpubkey message types + to 8 byte time. Last remaining type is pubkey. +- Added tooltips to show the full subject of messages +- Added Maximum Acceptable Difficulty fields in the settings +- Send out pubkey immediately after generating deterministic + addresses rather than waiting for a request + +* Sat Jun 29 2013 Bob Mottram (4096 bits) - 0.3.3-1 +- Remove inbox item from GUI when using API command trashMessage +- Add missing trailing semicolons to pybitmessage.desktop +- Ensure $(DESTDIR)/usr/bin exists +- Update Makefile to correct sandbox violations when built + via Portage (Gentoo) +- Fix message authentication bug + +* Fri Jun 28 2013 Bob Mottram (4096 bits) - 0.3.211-1 +- Removed multi-core proof of work + as the multiprocessing module does not work well with + pyinstaller's --onefile option. + +* Mon Jun 03 2013 Bob Mottram (4096 bits) - 0.3.2-1 +- Bugfix: Remove remaining references to the old myapp.trayIcon +- Refactored message status-related code. API function getStatus + now returns one of these strings: notfound, msgqueued, + broadcastqueued, broadcastsent, doingpubkeypow, awaitingpubkey, + doingmsgpow, msgsent, or ackreceived +- Moved proof of work to low-priority multi-threaded child + processes +- Added menu option to delete all trashed messages +- Added inv flooding attack mitigation +- On Linux, when selecting Show Bitmessage, do not maximize + automatically +- Store tray icons in bitmessage_icons_rc.py + +* Sat May 25 2013 Jonathan Warren (4096 bits) - 0.3.1-1 +- Added new API commands: getDeterministicAddress, + addSubscription, deleteSubscription +- TCP Connection timeout for non-fully-established connections + now 20 seconds +- Don't update the time we last communicated with a node unless + the connection is fully established. This will allow us to + forget about active but non-Bitmessage nodes which have made + it into our knownNodes file. +- Prevent incoming connection flooding from crashing + singleListener thread. Client will now only accept one + connection per remote node IP +- Bugfix: Worker thread crashed when doing a POW to send out + a v2 pubkey (bug introduced in 0.3.0) +- Wrap all sock.shutdown functions in error handlers +- Put all 'commit' commands within SQLLocks +- Bugfix: If address book label is blank, Bitmessage wouldn't + show message (bug introduced in 0.3.0) +- Messaging menu item selects the oldest unread message +- Standardize on 'Quit' rather than 'Exit' +- [OSX] Try to seek homebrew installation of OpenSSL +- Prevent multiple instances of the application from running +- Show 'Connected' or 'Connection Lost' indicators +- Use only 9 half-open connections on Windows but 32 for + everyone else +- Added appIndicator (a more functional tray icon) and Ubuntu + Messaging Menu integration +- Changed Debian install directory and run script name based + on Github issue #135 + +* Tue May 6 2013 Bob Mottram (4096 bits) - 0.3.0-1 +- Added new API function: getStatus +- Added error-handling around all sock.sendall() functions + in the receiveData thread so that if there is a problem + sending data, the threads will close gracefully +- Abandoned and removed the connectionsCount data structure; + use the connectedHostsList instead because it has proved to be + more accurate than trying to maintain the connectionsCount +- Added daemon mode. All UI code moved into a module and many + shared objects moved into shared.py +- Truncate display of very long messages to avoid freezing the UI +- Added encrypted broadcasts for v3 addresses or v2 addresses + after 2013-05-28 10:00 UTC +- No longer self.sock.close() from within receiveDataThreads, + let the sendDataThreads do it +- Swapped out the v2 announcements subscription address for a v3 + announcements subscription address +- Vacuum the messages.dat file once a month: will greatly reduce the file size +- Added a settings table in message.dat +- Implemented v3 addresses: + pubkey messages must now include two var_ints: nonce_trials_per_byte + and extra_bytes, and also be signed. When sending a message to a v3 + address, the sender must use these values in calculating its POW or + else the message will not be accepted by the receiver. +- Display a privacy warning when selecting 'Send Broadcast from this address' +- Added gitignore file +- Added code in preparation for a switch from 32-bit time to 64-bit time. + Nodes will now advertise themselves as using protocol version 2. +- Don't necessarily delete entries from the inventory after 2.5 days; + leave pubkeys there for 28 days so that we don't process the same ones + many times throughout a month. This was causing the 'pubkeys processed' + indicator on the 'Network Status' tab to not accurately reflect the + number of truly new addresses on the network. +- Use 32 threads for outgoing connections in order to connect quickly +- Fix typo when calling os.environ in the sys.platform=='darwin' case +- Allow the cancelling of a message which is in the process of being + sent by trashing it then restarting Bitmessage +- Bug fix: can't delete address from address book + +* Tue Apr 9 2013 Bob Mottram (4096 bits) - 0.2.8-1 +- Fixed Ubuntu & OS X issue: + Bitmessage wouldn't receive any objects from peers after restart. +- Inventory flush to disk when exiting program now vastly faster. +- Fixed address generation bug (kept Bitmessage from restarting). +- Improve deserialization of messages + before processing (a 'best practice'). +- Change to help Macs find OpenSSL the way Unix systems find it. +- Do not share or accept IPs which are in the private IP ranges. +- Added time-fuzzing + to the embedded time in pubkey and getpubkey messages. +- Added a knownNodes lock + to prevent an exception from sometimes occurring when saving + the data-structure to disk. +- Show unread messages in bold + and do not display new messages automatically. +- Support selecting multiple items + in the inbox, sent box, and address book. +- Use delete key to trash Inbox or Sent messages. +- Display richtext(HTML) messages + from senders in address book or subscriptions (although not + pseudo-mailing-lists; use new right-click option). +- Trim spaces + from the beginning and end of addresses when adding to + address book, subscriptions, and blacklist. +- Improved the display of the time for foreign language users. + +* Tue Apr 1 2013 Bob Mottram (4096 bits) - 0.2.7-1 +- Added debian packaging +- Script to generate debian packages +- SVG icon for Gnome shell, etc +- Source moved int src directory for debian standards compatibility +- Trailing carriage return on COPYING LICENSE and README.md diff --git a/slack.sh b/slack.sh new file mode 100755 index 00000000..cc71e1f3 --- /dev/null +++ b/slack.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +APP=pybitmessage +PREV_VERSION=0.3.4 +VERSION=0.3.4 +RELEASE=1 +ARCH_TYPE=`uname -m` +BUILDDIR=~/slackbuild +CURRDIR=`pwd` +PROJECTDIR=${BUILDDIR}/${APP}-${VERSION}-${RELEASE} + +# Update version numbers automatically - so you don't have to +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' Makefile debian.sh rpm.sh arch.sh puppy.sh ebuild.sh +sed -i 's/Version: '${PREV_VERSION}'/Version: '${VERSION}'/g' rpmpackage/${APP}.spec +sed -i 's/Release: '${RELEASE}'/Release: '${RELEASE}'/g' rpmpackage/${APP}.spec +sed -i 's/pkgrel='${RELEASE}'/pkgrel='${RELEASE}'/g' archpackage/PKGBUILD +sed -i 's/pkgver='${PREV_VERSION}'/pkgver='${VERSION}'/g' archpackage/PKGBUILD +sed -i "s/-${PREV_VERSION}-/-${VERSION}-/g" puppypackage/*.specs +sed -i "s/|${PREV_VERSION}|/|${VERSION}|/g" puppypackage/*.specs +sed -i 's/VERSION='${PREV_VERSION}'/VERSION='${VERSION}'/g' puppypackage/pinstall.sh puppypackage/puninstall.sh +sed -i 's/-'${PREV_VERSION}'.so/-'${VERSION}'.so/g' debian/*.links + + +# Make directories within which the project will be built +mkdir -p ${BUILDDIR} +mkdir -p ${PROJECTDIR} + +# Build the project +make clean +make +make install -B DESTDIR=${PROJECTDIR} + +# Copy the slack-desc and doinst.sh files into the build install directory +mkdir ${PROJECTDIR}/install +cp ${CURRDIR}/slackpackage/slack-desc ${PROJECTDIR}/install +cp ${CURRDIR}/slackpackage/doinst.sh ${PROJECTDIR}/install + +# Compress the build directory +cd ${BUILDDIR} +tar -c -f ${APP}-${VERSION}-${RELEASE}.tar . +sync +xz ${APP}-${VERSION}-${RELEASE}.tar +sync +mv ${APP}-${VERSION}-${RELEASE}.tar.xz ${CURRDIR}/slackpackage/${APP}-${VERSION}-${ARCH_TYPE}-${RELEASE}.txz +cd ${CURRDIR} + +# Remove the temporary build directory +rm -fr ${BUILDDIR} diff --git a/slackpackage/doinst.sh b/slackpackage/doinst.sh new file mode 100755 index 00000000..2d703395 --- /dev/null +++ b/slackpackage/doinst.sh @@ -0,0 +1,4 @@ +#!/bin/sh -e + +# This script is run after installation. +# Any additional configuration goes here. diff --git a/slackpackage/slack-desc b/slackpackage/slack-desc new file mode 100644 index 00000000..8705a13b --- /dev/null +++ b/slackpackage/slack-desc @@ -0,0 +1,19 @@ +# HOW TO EDIT THIS FILE: +# The "handy ruler" below makes it easier to edit a package description. Line +# up the first '|' above the ':' following the base package name, and the '|' on +# the right side marks the last column you can put a character in. You must make +# exactly 11 lines for the formatting to be correct. It's also customary to +# leave one space after the ':'. + + |-----handy-ruler--------------------------------------------------| +pybitmessage: pybitmessage (Send encrypted messages) +pybitmessage: +pybitmessage: Bitmessage is a P2P communications protocol used to send +pybitmessage: encrypted messages to another person or to many subscribers. It +pybitmessage: is decentralized and trustless, meaning that you need-not +pybitmessage: inherently trust any entities like root certificate authorities. +pybitmessage: It uses strong authentication which means that the sender of a +pybitmessage: message cannot be spoofed, and it aims to hide "non-content" +pybitmessage: data, like the sender and receiver of messages, from passive +pybitmessage: eavesdroppers like those running warrantless wiretapping +pybitmessage: programs. From fc5da5d3ff5c26e6ab17d70e3a121db0ac85eb05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerg=C3=B6=20Barany?= Date: Fri, 12 Jul 2013 12:16:34 +0200 Subject: [PATCH 86/93] Refactor type 2 message decoding, drop any extra lines from subject. This allows other clients to insert headers in extra lines of text between the Subject and Body fields of the message, as discussed on the 24x7 mailing list. The PyBitmessage client was never able to meaningfully display multi-line subjects, so this does not break anything. The extra lines are thrown away and never stored anywhere, so this also protects against watermarking attacks. --- src/class_receiveDataThread.py | 41 +++++++++++++++------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index ad5e7b34..e73f3d2b 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -528,13 +528,7 @@ class receiveDataThread(threading.Thread): print 'fromAddress:', fromAddress if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message + subject, body = self.decodeType2Message(message) elif messageEncodingType == 1: body = message subject = '' @@ -684,13 +678,7 @@ class receiveDataThread(threading.Thread): print 'fromAddress:', fromAddress if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message + subject, body = self.decodeType2Message(message) elif messageEncodingType == 1: body = message subject = '' @@ -1005,15 +993,7 @@ class receiveDataThread(threading.Thread): toLabel = toAddress if messageEncodingType == 2: - bodyPositionIndex = string.find(message, '\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - subject = subject[ - :500] # Only save and show the first 500 characters of the subject. Any more is probably an attak. - body = message[bodyPositionIndex + 6:] - else: - subject = '' - body = message + subject, body = self.decodeType2Message(message) elif messageEncodingType == 1: body = message subject = '' @@ -1086,6 +1066,21 @@ class receiveDataThread(threading.Thread): print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings) + def decodeType2Message(self, message): + bodyPositionIndex = string.find(message, '\nBody:') + if bodyPositionIndex > 1: + subject = message[8:bodyPositionIndex] + # Only save and show the first 500 characters of the subject. + # Any more is probably an attack. + subject = subject[:500] + body = message[bodyPositionIndex + 6:] + else: + subject = '' + body = message + # Throw away any extra lines (headers) after the subject. + if subject: + subject = subject.splitlines()[0] + return subject, body def isAckDataValid(self, ackData): if len(ackData) < 24: From 3364433765a9caea3001ba83cf554e5758ed7f73 Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Fri, 12 Jul 2013 12:07:55 +0100 Subject: [PATCH 87/93] Fixing the puppy script --- archpackage/PKGBUILD | 2 +- generate.sh | 2 +- puppy.sh | 2 +- puppypackage/pybitmessage-0.3.4.pet.specs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/archpackage/PKGBUILD b/archpackage/PKGBUILD index a75d262a..97beecd2 100644 --- a/archpackage/PKGBUILD +++ b/archpackage/PKGBUILD @@ -19,7 +19,7 @@ install= changelog= source=($pkgname-$pkgver.tar.gz) noextract=() -md5sums=(56a8a225463e96b435b2a5b438006983) +md5sums=() build() { cd "$srcdir/$pkgname-$pkgver" ./configure --prefix=/usr diff --git a/generate.sh b/generate.sh index 92bda853..9d792e1d 100755 --- a/generate.sh +++ b/generate.sh @@ -4,4 +4,4 @@ rm -f Makefile rpmpackage/*.spec -packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl" +packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" diff --git a/puppy.sh b/puppy.sh index 3fc2db14..dd54ecc9 100755 --- a/puppy.sh +++ b/puppy.sh @@ -44,7 +44,7 @@ cp ${PROJECTDIR}/usr/bin/* ${PROJECTDIR}/usr/local/bin/ cp ${CURRDIR}/puppypackage/${APP}-${VERSION}.pet.specs ${PROJECTDIR} # Copy the XPM mini icon into the build directory -cp ${CURRDIR}//home/motters/develop/pybitmessage/desktop/icon14.xpm ${PROJECTDIR}/pybitmessage.xpm +cp ${CURRDIR}/desktop/icon14.xpm ${PROJECTDIR}/${APP}.xpm # Compress the build directory cd ${BUILDDIR} diff --git a/puppypackage/pybitmessage-0.3.4.pet.specs b/puppypackage/pybitmessage-0.3.4.pet.specs index 81060a27..5c9b2a41 100644 --- a/puppypackage/pybitmessage-0.3.4.pet.specs +++ b/puppypackage/pybitmessage-0.3.4.pet.specs @@ -1 +1 @@ -pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|3.9M||pybitmessage-0.3.4-1.pet||Send encrypted messages|ubuntu|precise|5| +pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.1M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| From 28d1bfa645dd3d59eb660431aaa8f1f335e66134 Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Fri, 12 Jul 2013 14:03:11 +0100 Subject: [PATCH 88/93] Some Arch dependencies --- Makefile | 2 +- arch.sh | 5 ++++- archpackage/PKGBUILD | 2 +- generate.sh | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 92b4e633..e7577494 100644 --- a/Makefile +++ b/Makefile @@ -41,5 +41,5 @@ clean: rm -f ${APP} \#* \.#* gnuplot* *.png debian/*.substvars debian/*.log rm -fr deb.* debian/${APP} rpmpackage/${ARCH_TYPE} rm -f ../${APP}*.deb ../${APP}*.changes ../${APP}*.asc ../${APP}*.dsc - rm -f rpmpackage/*.src.rpm archpackage/*.gz + rm -f rpmpackage/*.src.rpm archpackage/*.gz archpackage/*.xz rm -f puppypackage/*.gz puppypackage/*.pet slackpackage/*.txz diff --git a/arch.sh b/arch.sh index 8917cef4..77332d09 100755 --- a/arch.sh +++ b/arch.sh @@ -38,7 +38,10 @@ sed -i "s/md5sums[^)]*)/md5sums=(${CHECKSM%% *})/g" archpackage/PKGBUILD cd archpackage # Create the package -makepkg +tar -c -f ${APP}-${VERSION}.pkg.tar . +sync +xz ${APP}-${VERSION}.pkg.tar +sync # Move back to the original directory cd ${CURRDIR} diff --git a/archpackage/PKGBUILD b/archpackage/PKGBUILD index 97beecd2..b7c9626f 100644 --- a/archpackage/PKGBUILD +++ b/archpackage/PKGBUILD @@ -7,7 +7,7 @@ arch=('i686' 'x86_64') url="https://github.com/Bitmessage/PyBitmessage" license=('MIT') groups=() -depends=() +depends=( 'python2' 'qt4' 'python2-pyqt4' 'python2-gevent' 'sqlite' 'openssl') makedepends=() optdepends=() provides=() diff --git a/generate.sh b/generate.sh index 9d792e1d..0b612765 100755 --- a/generate.sh +++ b/generate.sh @@ -4,4 +4,4 @@ rm -f Makefile rpmpackage/*.spec -packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" +packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" --dependsarch "python2, qt4, python2-pyqt4, python2-gevent, sqlite, openssl" From 33a41367b3cd401614798cb1a241e148c3ba862d Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Fri, 12 Jul 2013 14:09:10 +0100 Subject: [PATCH 89/93] Duplocated command in Makefile --- puppypackage/pybitmessage-0.3.4.pet.specs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/puppypackage/pybitmessage-0.3.4.pet.specs b/puppypackage/pybitmessage-0.3.4.pet.specs index 5c9b2a41..d9649f3c 100644 --- a/puppypackage/pybitmessage-0.3.4.pet.specs +++ b/puppypackage/pybitmessage-0.3.4.pet.specs @@ -1 +1 @@ -pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.1M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| +pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.2M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| From d3b76eb610bb835b24a833bb968cac53057014a1 Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Fri, 12 Jul 2013 18:09:59 +0100 Subject: [PATCH 90/93] python2-gevent is optional --- archpackage/PKGBUILD | 4 ++-- debian/control | 2 +- generate.sh | 2 +- puppypackage/pybitmessage-0.3.4.pet.specs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/archpackage/PKGBUILD b/archpackage/PKGBUILD index b7c9626f..79ee8ded 100644 --- a/archpackage/PKGBUILD +++ b/archpackage/PKGBUILD @@ -7,9 +7,9 @@ arch=('i686' 'x86_64') url="https://github.com/Bitmessage/PyBitmessage" license=('MIT') groups=() -depends=( 'python2' 'qt4' 'python2-pyqt4' 'python2-gevent' 'sqlite' 'openssl') +depends=('python2' 'qt4' 'python2-pyqt4' 'sqlite' 'openssl') makedepends=() -optdepends=() +optdepends=('python2-gevent') provides=() conflicts=() replaces=() diff --git a/debian/control b/debian/control index de8f3a59..e2d860d0 100644 --- a/debian/control +++ b/debian/control @@ -4,7 +4,7 @@ Maintainer: Bob Mottram (4096 bits) Build-Depends: debhelper (>= 9.0.0) Standards-Version: 3.9.4 Homepage: https://github.com/Bitmessage/PyBitmessage -Vcs-Git: https://github.com/fuzzgun/autocv.git +Vcs-Git: https://github.com/fuzzgun/libgpr.git Package: pybitmessage Section: mail diff --git a/generate.sh b/generate.sh index 0b612765..44aca136 100755 --- a/generate.sh +++ b/generate.sh @@ -4,4 +4,4 @@ rm -f Makefile rpmpackage/*.spec -packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" --dependsarch "python2, qt4, python2-pyqt4, python2-gevent, sqlite, openssl" +packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" --dependsarch "python2, qt4, python2-pyqt4, sqlite, openssl" --suggestsarch "python2-gevent" diff --git a/puppypackage/pybitmessage-0.3.4.pet.specs b/puppypackage/pybitmessage-0.3.4.pet.specs index d9649f3c..2d576f60 100644 --- a/puppypackage/pybitmessage-0.3.4.pet.specs +++ b/puppypackage/pybitmessage-0.3.4.pet.specs @@ -1 +1 @@ -pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.2M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| +pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.5M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| From d93d92336438bc165839c4089cfaa80c519db730 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Sat, 13 Jul 2013 20:35:06 -0400 Subject: [PATCH 91/93] Added some default text to the search textbox, also fixed bitmessage_icons.qrc after file move --- src/bitmessagemain.py | 2 +- src/bitmessageqt/bitmessage_icons.qrc | 32 +++++++++++++-------------- src/bitmessageqt/bitmessageui.py | 22 ++++++------------ src/bitmessageqt/bitmessageui.ui | 29 ++++++++++++------------ 4 files changed, 38 insertions(+), 47 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index e93fbd46..4ffc9f5b 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -14,7 +14,7 @@ try: from gevent import monkey monkey.patch_all() except ImportError as ex: - print "cannot find gevent" + print "Not using the gevent module as it was not found. No need to worry." import signal # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. # The next 3 are used for the API diff --git a/src/bitmessageqt/bitmessage_icons.qrc b/src/bitmessageqt/bitmessage_icons.qrc index a186b01b..bdd3fd07 100644 --- a/src/bitmessageqt/bitmessage_icons.qrc +++ b/src/bitmessageqt/bitmessage_icons.qrc @@ -1,20 +1,20 @@ - images/can-icon-24px-yellow.png - images/can-icon-24px-red.png - images/can-icon-24px-green.png - images/can-icon-24px.png - images/can-icon-16px.png - images/greenicon.png - images/redicon.png - images/yellowicon.png - images/addressbook.png - images/blacklist.png - images/identities.png - images/networkstatus.png - images/sent.png - images/subscriptions.png - images/send.png - images/inbox.png + ../images/can-icon-24px-yellow.png + ../images/can-icon-24px-red.png + ../images/can-icon-24px-green.png + ../images/can-icon-24px.png + ../images/can-icon-16px.png + ../images/greenicon.png + ../images/redicon.png + ../images/yellowicon.png + ../images/addressbook.png + ../images/blacklist.png + ../images/identities.png + ../images/networkstatus.png + ../images/sent.png + ../images/subscriptions.png + ../images/send.png + ../images/inbox.png diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index 62466503..1d04e5f1 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -2,8 +2,8 @@ # Form implementation generated from reading ui file 'bitmessageui.ui' # -# Created: Fri Jul 12 04:40:47 2013 -# by: PyQt4 UI code generator 4.10 +# Created: Sat Jul 13 20:23:44 2013 +# by: PyQt4 UI code generator 4.10.2 # # WARNING! All changes made in this file will be lost! @@ -422,7 +422,7 @@ class Ui_MainWindow(object): self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 25)) + self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 18)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) @@ -497,6 +497,7 @@ class Ui_MainWindow(object): def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Bitmessage", None)) + self.inboxSearchLineEdit.setPlaceholderText(_translate("MainWindow", "Search", None)) self.inboxSearchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) self.inboxSearchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) self.inboxSearchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) @@ -519,14 +520,15 @@ class Ui_MainWindow(object): self.textEditMessage.setHtml(_translate("MainWindow", "\n" "\n" -"


", None)) +"\n" +"


", None)) self.label.setText(_translate("MainWindow", "To:", None)) self.label_2.setText(_translate("MainWindow", "From:", None)) self.radioButtonBroadcast.setText(_translate("MainWindow", "Broadcast to everyone who is subscribed to your address", None)) self.pushButtonSend.setText(_translate("MainWindow", "Send", None)) self.labelSendBroadcastWarning.setText(_translate("MainWindow", "Be aware that broadcasts are only encrypted with your address. Anyone who knows your address can read them.", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.send), _translate("MainWindow", "Send", None)) + self.sentSearchLineEdit.setPlaceholderText(_translate("MainWindow", "Search", None)) self.sentSearchOptionCB.setItemText(0, _translate("MainWindow", "All", None)) self.sentSearchOptionCB.setItemText(1, _translate("MainWindow", "To", None)) self.sentSearchOptionCB.setItemText(2, _translate("MainWindow", "From", None)) @@ -599,13 +601,3 @@ class Ui_MainWindow(object): self.actionDeleteAllTrashedMessages.setText(_translate("MainWindow", "Delete all trashed messages", None)) import bitmessage_icons_rc - -if __name__ == "__main__": - import sys - app = QtGui.QApplication(sys.argv) - MainWindow = QtGui.QMainWindow() - ui = Ui_MainWindow() - ui.setupUi(MainWindow) - MainWindow.show() - sys.exit(app.exec_()) - diff --git a/src/bitmessageqt/bitmessageui.ui b/src/bitmessageqt/bitmessageui.ui index 46ebd06a..6c18cbe0 100644 --- a/src/bitmessageqt/bitmessageui.ui +++ b/src/bitmessageqt/bitmessageui.ui @@ -22,16 +22,7 @@ - - 0 - - - 0 - - - 0 - - + 0 @@ -83,7 +74,11 @@ 0 - + + + Search + + @@ -262,8 +257,8 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Sans'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2';"><br /></p></body></html> +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html>
@@ -364,7 +359,11 @@ p, li { white-space: pre-wrap; } 0 - + + + Search + + @@ -1012,7 +1011,7 @@ p, li { white-space: pre-wrap; } 0 0 795 - 25 + 18 From d04b8747c7ea3a9980a9c05ca0296d47a2d6059f Mon Sep 17 00:00:00 2001 From: fuzzgun Date: Sun, 14 Jul 2013 12:31:58 +0100 Subject: [PATCH 92/93] Use python2 within /usr/bin/pybitmessage #296 --- Makefile | 2 +- debian/control | 2 +- generate.sh | 2 +- puppypackage/pybitmessage-0.3.4.pet.specs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index e7577494..b9a85ff7 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ install: cp -rf src/* ${DESTDIR}/usr/share/${APP} echo '#!/bin/sh' > ${DESTDIR}/usr/bin/${APP} echo 'cd /usr/share/pybitmessage' >> ${DESTDIR}/usr/bin/${APP} - echo 'LD_LIBRARY_PATH="/opt/openssl-compat-bitcoin/lib/" exec python bitmessagemain.py' >> ${DESTDIR}/usr/bin/${APP} + echo 'LD_LIBRARY_PATH="/opt/openssl-compat-bitcoin/lib/" exec python2 bitmessagemain.py' >> ${DESTDIR}/usr/bin/${APP} chmod +x ${DESTDIR}/usr/bin/${APP} uninstall: rm -f /usr/share/man/man1/${APP}.1.gz diff --git a/debian/control b/debian/control index e2d860d0..01bd7d8c 100644 --- a/debian/control +++ b/debian/control @@ -4,7 +4,7 @@ Maintainer: Bob Mottram (4096 bits) Build-Depends: debhelper (>= 9.0.0) Standards-Version: 3.9.4 Homepage: https://github.com/Bitmessage/PyBitmessage -Vcs-Git: https://github.com/fuzzgun/libgpr.git +Vcs-Git: https://github.com/fuzzgun/fin.git Package: pybitmessage Section: mail diff --git a/generate.sh b/generate.sh index 44aca136..8909cf2f 100755 --- a/generate.sh +++ b/generate.sh @@ -4,4 +4,4 @@ rm -f Makefile rpmpackage/*.spec -packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" --dependsarch "python2, qt4, python2-pyqt4, sqlite, openssl" --suggestsarch "python2-gevent" +packagemonkey -n "PyBitmessage" --version "0.3.4" --dir "." -l "mit" -e "Bob Mottram (4096 bits) " --brief "Send encrypted messages" --desc "Bitmessage is a P2P communications protocol used to send encrypted messages to another person or to many subscribers. It is decentralized and trustless, meaning that you need-not inherently trust any entities like root certificate authorities. It uses strong authentication which means that the sender of a message cannot be spoofed, and it aims to hide \"non-content\" data, like the sender and receiver of messages, from passive eavesdroppers like those running warrantless wiretapping programs." --homepage "https://github.com/Bitmessage/PyBitmessage" --section "mail" --categories "Office/Email" --dependsdeb "python (>= 2.7.0), openssl, python-qt4, libqt4-dev (>= 4.8.0), python-qt4-dev, sqlite3, libsqlite3-dev" --dependsrpm "python, PyQt4, openssl-compat-bitcoin-libs" --mainscript "bitmessagemain.py" --librarypath "/opt/openssl-compat-bitcoin/lib/" --suggestsdeb "libmessaging-menu-dev" --dependspuppy "openssl, python-qt4, sqlite3, sqlite3-dev, python-openssl, python-sip" --dependsarch "python2, qt4, python2-pyqt4, sqlite, openssl" --suggestsarch "python2-gevent" --pythonversion 2 diff --git a/puppypackage/pybitmessage-0.3.4.pet.specs b/puppypackage/pybitmessage-0.3.4.pet.specs index 2d576f60..e346d0c9 100644 --- a/puppypackage/pybitmessage-0.3.4.pet.specs +++ b/puppypackage/pybitmessage-0.3.4.pet.specs @@ -1 +1 @@ -pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|4.5M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| +pybitmessage-0.3.4-1|PyBitmessage|0.3.4|1|Internet;mailnews;|5.1M||pybitmessage-0.3.4-1.pet|+openssl,+python-qt4,+sqlite3,+sqlite3-dev,+python-openssl,+python-sip|Send encrypted messages|ubuntu|precise|5| From 1bf39dbfd06102268f532ba54007251f7535b80a Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Sun, 14 Jul 2013 16:12:59 -0400 Subject: [PATCH 93/93] moved debug.log file to the config directory --- src/bitmessagemain.py | 5 +---- src/debug.py | 10 ++++++---- src/shared.py | 8 +++++--- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 4ffc9f5b..cfbfdd6c 100644 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -32,7 +32,6 @@ from class_singleListener import * from class_addressGenerator import * # Helper Functions -import helper_startup import helper_bootstrap import sys @@ -719,11 +718,9 @@ if __name__ == "__main__": signal.signal(signal.SIGINT, helper_generic.signal_handler) # signal.signal(signal.SIGINT, signal.SIG_DFL) - helper_startup.loadConfig() - helper_bootstrap.knownNodes() helper_bootstrap.dns() - + # Start the address generation thread addressGeneratorThread = addressGenerator() addressGeneratorThread.daemon = True # close the main program even if there are threads left diff --git a/src/debug.py b/src/debug.py index 14214686..034d3102 100644 --- a/src/debug.py +++ b/src/debug.py @@ -18,6 +18,7 @@ Use: `from debug import logger` to import this facility into whatever module you ''' import logging import logging.config +import shared # TODO(xj9): Get from a config file. log_level = 'DEBUG' @@ -40,9 +41,9 @@ logging.config.dictConfig({ 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'default', 'level': log_level, - 'filename': 'bm.log', - 'maxBytes': 1024, - 'backupCount': 0, + 'filename': shared.appdata + 'debug.log', + 'maxBytes': 2097152, # 2 MiB + 'backupCount': 1, } }, 'loggers': { @@ -65,4 +66,5 @@ logging.config.dictConfig({ }, }) # TODO (xj9): Get from a config file. -logger = logging.getLogger('console_only') +#logger = logging.getLogger('console_only') +logger = logging.getLogger('both') diff --git a/src/shared.py b/src/shared.py index c706038a..5abeeb96 100644 --- a/src/shared.py +++ b/src/shared.py @@ -21,7 +21,8 @@ import socket import random import highlevelcrypto import shared -from debug import logger +import helper_startup + config = ConfigParser.SafeConfigParser() myECCryptorObjects = {} @@ -63,8 +64,6 @@ ackdataForWhichImWatching = {} networkDefaultProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work. networkDefaultPayloadLengthExtraBytes = 14000 #To make sending short messages a little more difficult, this value is added to the payload length for use in calculating the proof of work target. - - def isInSqlInventory(hash): t = (hash,) shared.sqlLock.acquire() @@ -306,3 +305,6 @@ def fixPotentiallyInvalidUTF8Data(text): except: output = 'Part of the message is corrupt. The message cannot be displayed the normal way.\n\n' + repr(text) return output + +helper_startup.loadConfig() +from debug import logger \ No newline at end of file