diff --git a/about.py b/about.py index 2f69a950..bf48ac60 100644 --- a/about.py +++ b/about.py @@ -2,8 +2,8 @@ # Form implementation generated from reading ui file 'about.ui' # -# Created: Tue Dec 18 14:32:14 2012 -# by: PyQt4 UI code generator 4.9.4 +# Created: Mon Jan 21 22:32:55 2013 +# by: PyQt4 UI code generator 4.9.5 # # WARNING! All changes made in this file will be lost! @@ -17,9 +17,9 @@ except AttributeError: class Ui_aboutDialog(object): def setupUi(self, aboutDialog): aboutDialog.setObjectName(_fromUtf8("aboutDialog")) - aboutDialog.resize(360, 402) + aboutDialog.resize(360, 315) self.buttonBox = QtGui.QDialogButtonBox(aboutDialog) - self.buttonBox.setGeometry(QtCore.QRect(20, 360, 311, 32)) + self.buttonBox.setGeometry(QtCore.QRect(20, 280, 311, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) @@ -42,10 +42,6 @@ class Ui_aboutDialog(object): self.label_3.setGeometry(QtCore.QRect(20, 210, 331, 61)) self.label_3.setWordWrap(True) self.label_3.setObjectName(_fromUtf8("label_3")) - self.label_4 = QtGui.QLabel(aboutDialog) - self.label_4.setGeometry(QtCore.QRect(20, 280, 331, 81)) - self.label_4.setWordWrap(True) - self.label_4.setObjectName(_fromUtf8("label_4")) self.label_5 = QtGui.QLabel(aboutDialog) self.label_5.setGeometry(QtCore.QRect(10, 180, 341, 20)) self.label_5.setAlignment(QtCore.Qt.AlignCenter) @@ -61,7 +57,6 @@ class Ui_aboutDialog(object): self.label.setText(QtGui.QApplication.translate("aboutDialog", "PyBitmessage", None, QtGui.QApplication.UnicodeUTF8)) self.labelVersion.setText(QtGui.QApplication.translate("aboutDialog", "version ?", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("aboutDialog", "Copyright © 2012 Jonathan Warren", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("aboutDialog", "Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setText(QtGui.QApplication.translate("aboutDialog", "This product includes Python-RSA (http://stuvel.eu/rsa) originally written by Sybren A. Stüvel . It is licensed under the Apache 2.0 license: http://www.apache.org/licenses/LICENSE-2.0", None, QtGui.QApplication.UnicodeUTF8)) + self.label_3.setText(QtGui.QApplication.translate("aboutDialog", "

Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php

", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setText(QtGui.QApplication.translate("aboutDialog", "This is Beta software.", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/about.ui b/about.ui index 7903525d..0060bdc3 100644 --- a/about.ui +++ b/about.ui @@ -7,7 +7,7 @@ 0 0 360 - 402 + 315 @@ -17,7 +17,7 @@ 20 - 360 + 280 311 32 @@ -90,23 +90,7 @@ - Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php - - - true - - - - - - 20 - 280 - 331 - 81 - - - - This product includes Python-RSA (http://stuvel.eu/rsa) originally written by Sybren A. Stüvel <sybren@stuvel.eu>. It is licensed under the Apache 2.0 license: http://www.apache.org/licenses/LICENSE-2.0 + <html><head/><body><p>Distributed under the MIT/X11 software license, see the accompanying file license.txt or <a href="http://www.opensource.org/licenses/mit-license.php"><span style=" text-decoration: underline; color:#0000ff;">http://www.opensource.org/licenses/mit-license.php</span></a></p></body></html> true diff --git a/addresses.py b/addresses.py index 60768783..97d1ab95 100644 --- a/addresses.py +++ b/addresses.py @@ -95,6 +95,11 @@ def calculateInventoryHash(data): return sha2.digest()[0:32] def encodeAddress(version,stream,ripe): + if version >= 2: + if ripe[:2] == '\x00\x00': + ripe = ripe[2:] + elif ripe[:1] == '\x00': + ripe = ripe[1:] a = encodeVarint(version) + encodeVarint(stream) + ripe sha = hashlib.new('sha512') sha.update(a) @@ -152,7 +157,6 @@ def decodeAddress(address): #print 'sha after second hashing: ', sha.hexdigest() if checksum != sha.digest()[0:4]: - print 'checksum failed' status = 'checksumfailed' return status,0,0,0 #else: @@ -162,15 +166,27 @@ def decodeAddress(address): #print 'addressVersionNumber', addressVersionNumber #print 'bytesUsedByVersionNumber', bytesUsedByVersionNumber - if addressVersionNumber != 1: - print 'cannot decode version address version numbers this high' + if addressVersionNumber > 2: + print 'cannot decode address version numbers this high' + status = 'versiontoohigh' + return status,0,0,0 + elif addressVersionNumber == 0: + print 'cannot decode address version numbers of zero.' status = 'versiontoohigh' return status,0,0,0 - streamNumber, bytesUsedByStreamNumber = decodeVarint(data[bytesUsedByVersionNumber:10+bytesUsedByVersionNumber]) + streamNumber, bytesUsedByStreamNumber = decodeVarint(data[bytesUsedByVersionNumber:]) #print streamNumber status = 'success' - return status,addressVersionNumber,streamNumber,data[-24:-4] + if addressVersionNumber == 1: + return status,addressVersionNumber,streamNumber,data[-24:-4] + elif addressVersionNumber == 2: + if len(data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]) == 19: + return status,addressVersionNumber,streamNumber,'\x00'+data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4] + elif len(data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]) == 20: + return status,addressVersionNumber,streamNumber,data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4] + elif len(data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]) == 18: + return status,addressVersionNumber,streamNumber,'\x00\x00'+data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4] def addBMIfNotPresent(address): if address[:3] != 'BM-': @@ -274,3 +290,4 @@ if __name__ == "__main__": print 'addressVersionNumber', addressVersionNumber print 'streamNumber', streamNumber print 'length of data(the ripe hash):', len(data) + diff --git a/bitmessagemain.py b/bitmessagemain.py index 0fc5754d..b54c0690 100644 --- a/bitmessagemain.py +++ b/bitmessagemain.py @@ -5,13 +5,14 @@ #Right now, PyBitmessage only support connecting to stream 1. It doesn't yet contain logic to expand into further streams. -softwareVersion = '0.1.6' +softwareVersion = '0.2.0' verbose = 2 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. maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 #Equals two days and 12 hours maximumAgeOfNodesThatIAdvertiseToOthers = 10800 #Equals three hours - +storeConfigFilesInSameDirectoryAsProgram = False +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 sys try: @@ -25,6 +26,7 @@ import ConfigParser from bitmessageui import * from newaddressdialog import * from newsubscriptiondialog import * +from regenerateaddresses import * from settings import * from about import * from help import * @@ -48,6 +50,11 @@ from time import strftime, localtime import os import string import socks +#import pyelliptic +import highlevelcrypto +from pyelliptic.openssl import OpenSSL +import ctypes +from pyelliptic import arithmetic #For each stream to which we connect, one outgoingSynSender thread will exist and will create 8 connections with peers. class outgoingSynSender(QThread): @@ -131,7 +138,9 @@ class outgoingSynSender(QThread): sd.sendVersionMessage() except socks.GeneralProxyError, err: + printLock.acquire() print 'Could NOT connect to', HOST, 'during outgoing attempt.', err + printLock.release() PORT, timeLastSeen = knownNodes[self.streamNumber][HOST] if (int(time.time())-timeLastSeen) > 172800 and len(knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure. del knownNodes[self.streamNumber][HOST] @@ -150,7 +159,9 @@ class outgoingSynSender(QThread): print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. '+str(err) #self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"Problem: Bitmessage can not connect to the SOCKS server. "+str(err)) else: + printLock.acquire() print 'Could NOT connect to', HOST, 'during outgoing attempt.', err + printLock.release() PORT, timeLastSeen = knownNodes[self.streamNumber][HOST] if (int(time.time())-timeLastSeen) > 172800 and len(knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure. del knownNodes[self.streamNumber][HOST] @@ -182,11 +193,11 @@ class singleListener(QThread): while True: - #We don't want to accept incoming connections if the user is using a SOCKS proxy. If they eventually select proxy 'none' then this will start listening for connections. + #We don't want to accept incoming connections if the user is using a SOCKS proxy. If the user eventually select proxy 'none' then this will start listening for connections. while config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': time.sleep(10) a,(HOST,PORT) = sock.accept() - #Users are finding that if they run more than one node in the same network (thus with the same public IP), they can not connect with the second node. This is because this section of code won't accept the connection from the same IP. This problem will go away when the Bitmessage network grows behond being tiny but in the mean time, I'll comment out this code section. + #Users are finding that if they run more than one node in the same network (thus with the same public IP), they can not connect with the second node. This is because this section of code won't accept the connection from the same IP. This problem will go away when the Bitmessage network grows beyond being tiny but in the mean time I'll comment out this code section. """while HOST in connectedHostsList: print 'incoming connection is from a host in connectedHostsList (we are already connected to it). Ignoring it.' a.close() @@ -220,10 +231,10 @@ class receiveDataThread(QThread): self.streamNumber = streamNumber self.selfInitiatedConnectionList = selfInitiatedConnectionList self.selfInitiatedConnectionList.append(self) - self.payloadLength = 0 - self.receivedgetbiginv = False + self.payloadLength = 0 #This is the protocol payload length thus it doesn't include the 24 byte message header + self.receivedgetbiginv = False #Gets set to true once we receive a getbiginv message from our peer. An abusive peer might request it too much so we use this variable to check whether they have already asked for a big inv message. self.objectsThatWeHaveYetToGet = {} - connectedHostsList[self.HOST] = 0 + 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 the 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 @@ -239,7 +250,7 @@ class receiveDataThread(QThread): self.data = self.data + self.sock.recv(65536) except socket.timeout: printLock.acquire() - print 'Timeout occurred waiting for data. Closing thread.' + print 'Timeout occurred waiting for data. Closing receiveData thread.' printLock.release() break except Exception, err: @@ -250,7 +261,7 @@ class receiveDataThread(QThread): #print 'Received', repr(self.data) if self.data == "": printLock.acquire() - print 'Connection closed.' + print 'Connection closed. Closing receiveData thread.' printLock.release() break else: @@ -265,14 +276,19 @@ class receiveDataThread(QThread): try: self.selfInitiatedConnectionList.remove(self) - print 'removed self from ConnectionList' + printLock.acquire() + print 'removed self (a receiveDataThread) from ConnectionList' + printLock.release() except: pass - broadcastToSendDataQueues((self.streamNumber, 'shutdown', self.HOST)) + broadcastToSendDataQueues((0, 'shutdown', self.HOST)) if self.connectionIsOrWasFullyEstablished: #We don't want to decrement the number of connections and show the result if we never incremented it in the first place (which we only do if the connection is fully established- meaning that both nodes accepted each other's version packets.) connectionsCountLock.acquire() connectionsCount[self.streamNumber] -= 1 self.emit(SIGNAL("updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject)"),self.streamNumber,connectionsCount[self.streamNumber]) + printLock.acquire() + print 'Updating network status tab with current connections count:', connectionsCount[self.streamNumber] + printLock.release() connectionsCountLock.release() try: del connectedHostsList[self.HOST] @@ -343,13 +359,17 @@ class receiveDataThread(QThread): random.seed() objectHash, = random.sample(self.objectsThatWeHaveYetToGet, 1) if objectHash in inventory: + printLock.acquire() print 'Inventory (in memory) already has object listed in inv message.' + printLock.release() del self.objectsThatWeHaveYetToGet[objectHash] elif isInSqlInventory(objectHash): + printLock.acquire() print 'Inventory (SQL on disk) already has object listed in inv message.' + printLock.release() del self.objectsThatWeHaveYetToGet[objectHash] else: - print 'processData function making request for object:', repr(objectHash) + #print 'processData function making request for object:', objectHash.encode('hex') self.sendgetdata(objectHash) del self.objectsThatWeHaveYetToGet[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. break @@ -396,9 +416,11 @@ class receiveDataThread(QThread): print 'broadcasting addr from within connectionFullyEstablished function.' 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 addr message to this one peer. + self.sendaddr() #This is one large addr message to this one peer. if connectionsCount[self.streamNumber] > 150: + printLock.acquire() print 'We are connected to too many people. Closing connection.' + printLock.release() self.sock.close() return self.sendBigInv() @@ -421,18 +443,19 @@ class receiveDataThread(QThread): for row in queryreturn: hash, = row bigInvList[hash] = 0 - #print 'bigInvList:', bigInvList + #We also have messages in our inventory in memory (which is a python dictionary). Let's fetch those too. for hash, storedValue in inventory.items(): 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. - sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload) + self.sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload) payload = '' numberOfObjectsInInvMessage = 0 if numberOfObjectsInInvMessage > 0: @@ -445,7 +468,7 @@ class receiveDataThread(QThread): headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' headerData = headerData + pack('>L',len(payload)) headerData = headerData + hashlib.sha512(payload).digest()[:4] - print 'Sending inv message to just this one peer' + print 'Sending huge inv message to just this one peer' self.sock.send(headerData + payload) #We have received a broadcast message @@ -488,91 +511,163 @@ class receiveDataThread(QThread): return readPosition += broadcastVersionLength sendersAddressVersion, sendersAddressVersionLength = decodeVarint(self.data[readPosition:readPosition+9]) - if sendersAddressVersion <> 1: - #Cannot decode senderAddressVersion higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored. + if sendersAddressVersion == 0 or sendersAddressVersion >=3: + #Cannot decode senderAddressVersion higher than 2. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored. return readPosition += sendersAddressVersionLength - sendersStream, sendersStreamLength = decodeVarint(self.data[readPosition:readPosition+9]) - if sendersStream <= 0: - return - readPosition += sendersStreamLength - sendersHash = self.data[readPosition:readPosition+20] - if sendersHash not in broadcastSendersForWhichImWatching: - 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 - nLength, nLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) - if nLength < 1: - return - readPosition += nLengthLength - nString = self.data[readPosition:readPosition+nLength] - readPosition += nLength - eLength, eLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) - if eLength < 1: - return - readPosition += eLengthLength - eString = self.data[readPosition:readPosition+eLength] - #We are now ready to hash the public key and verify that its hash matches the hash claimed in the message - readPosition += eLength - sha = hashlib.new('sha512') - sha.update(nString+eString) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) - if ripe.digest() != sendersHash: - #The sender of this message lied. - return - - readPositionAtBeginningOfMessageEncodingType = readPosition - messageEncodingType, messageEncodingTypeLength = decodeVarint(self.data[readPosition:readPosition+9]) - if messageEncodingType == 0: - return - readPosition += messageEncodingTypeLength - messageLength, messageLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) - readPosition += messageLengthLength - message = self.data[readPosition:readPosition+messageLength] - readPosition += messageLength - signature = self.data[readPosition:readPosition+nLength] - print 'signature', repr(signature) - sendersPubkey = rsa.PublicKey(convertStringToInt(nString),convertStringToInt(eString)) - #print 'senders Pubkey', sendersPubkey - try: - #You may notice that this signature doesn't cover any information that identifies the RECEIVER of the message. This makes it vulnerable to a malicious receiver Bob forwarding the message from Alice to Charlie, making it look like Alice sent the message to Charlie. This will be fixed in the next version. - #See http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html - rsa.verify(self.data[readPositionAtBeginningOfMessageEncodingType:readPositionAtBeginningOfMessageEncodingType+messageEncodingTypeLength+messageLengthLength+messageLength],signature,sendersPubkey) - print 'verify passed' - except Exception, err: - print 'verify failed', err - return - #verify passed - fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest()) - print 'fromAddress:', fromAddress - - if messageEncodingType == 2: - bodyPositionIndex = string.find(message,'\nBody:') - if bodyPositionIndex > 1: - subject = message[8:bodyPositionIndex] - body = message[bodyPositionIndex+6:] - else: - subject = '' + if sendersAddressVersion == 2: + sendersStream, sendersStreamLength = decodeVarint(self.data[readPosition:readPosition+9]) + if sendersStream <= 0 or sendersStream <> self.streamNumber: + return + readPosition += sendersStreamLength + behaviorBitfield = self.data[readPosition:readPosition+4] + readPosition += 4 + sendersPubSigningKey = '\x04' + self.data[readPosition:readPosition+64] + readPosition += 64 + sendersPubEncryptionKey = '\x04' + self.data[readPosition:readPosition+64] + readPosition += 64 + sendersHash = self.data[readPosition:readPosition+20] + if sendersHash not in broadcastSendersForWhichImWatching: + 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(self.data[readPosition:readPosition+9]) + if messageEncodingType == 0: + return + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) + readPosition += messageLengthLength + message = self.data[readPosition:readPosition+messageLength] + readPosition += messageLength + readPositionAtBottomOfMessage = readPosition + signatureLength, signatureLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) + readPosition += signatureLengthLength + signature = self.data[readPosition:readPosition+signatureLength] + try: + highlevelcrypto.verify(self.data[36:readPositionAtBottomOfMessage],signature,sendersPubSigningKey.encode('hex')) + print 'ECDSA verify passed' + except Exception, err: + print 'ECDSA verify failed', err + return + #verify passed + fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest()) + 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 + elif messageEncodingType == 1: 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 = '' + 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: - sqlLock.acquire() - t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') - sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') - sqlSubmitQueue.put(t) - sqlReturnQueue.get() - sqlLock.release() - self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) + toAddress = '[Broadcast subscribers]' + if messageEncodingType <> 0: + sqlLock.acquire() + t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') + sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) + + + ########################################### + elif sendersAddressVersion == 1: + sendersStream, sendersStreamLength = decodeVarint(self.data[readPosition:readPosition+9]) + if sendersStream <= 0: + return + readPosition += sendersStreamLength + sendersHash = self.data[readPosition:readPosition+20] + if sendersHash not in broadcastSendersForWhichImWatching: + 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 + nLength, nLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) + if nLength < 1: + return + readPosition += nLengthLength + nString = self.data[readPosition:readPosition+nLength] + readPosition += nLength + eLength, eLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) + if eLength < 1: + return + readPosition += eLengthLength + eString = self.data[readPosition:readPosition+eLength] + #We are now ready to hash the public key and verify that its hash matches the hash claimed in the message + readPosition += eLength + sha = hashlib.new('sha512') + sha.update(nString+eString) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) + if ripe.digest() != sendersHash: + #The sender of this message lied. + return + + readPositionAtBeginningOfMessageEncodingType = readPosition + messageEncodingType, messageEncodingTypeLength = decodeVarint(self.data[readPosition:readPosition+9]) + if messageEncodingType == 0: + return + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint(self.data[readPosition:readPosition+9]) + readPosition += messageLengthLength + message = self.data[readPosition:readPosition+messageLength] + readPosition += messageLength + signature = self.data[readPosition:readPosition+nLength] + sendersPubkey = rsa.PublicKey(convertStringToInt(nString),convertStringToInt(eString)) + #print 'senders Pubkey', sendersPubkey + try: + rsa.verify(self.data[readPositionAtBeginningOfMessageEncodingType:readPositionAtBeginningOfMessageEncodingType+messageEncodingTypeLength+messageLengthLength+messageLength],signature,sendersPubkey) + print 'verify passed' + except Exception, err: + print 'verify failed', err + return + #verify passed + fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest()) + 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 + 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: + sqlLock.acquire() + t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') + sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) #We have received a msg message. def recmsg(self): @@ -590,13 +685,12 @@ class receiveDataThread(QThread): print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime return readPosition += 4 - inventoryHash = calculateInventoryHash(self.data[24:self.payloadLength+24]) - streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(self.data[readPosition:readPosition+9]) if streamNumberAsClaimedByMsg != self.streamNumber: print 'The stream number encoded in this msg (' + streamNumberAsClaimedByMsg + ') message does not match the stream number on which it was received. Ignoring it.' return readPosition += streamNumberAsClaimedByMsgLength + inventoryHash = calculateInventoryHash(self.data[24:self.payloadLength+24]) inventoryLock.acquire() if inventoryHash in inventory: print 'We have already received this msg message. Ignoring.' @@ -626,7 +720,7 @@ class receiveDataThread(QThread): sqlReturnQueue.get() sqlLock.release() self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),self.data[readPosition:24+self.payloadLength],'Acknowledgement of the message received just now.') - flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage soon. + flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage both soon and un-cleanly. return else: printLock.acquire() @@ -635,10 +729,199 @@ class receiveDataThread(QThread): 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 myECAddressHashes.items(): + try: + data = cryptorObject.decrypt(self.data[readPosition:self.payloadLength+24]) + 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, err: + pass + #print 'cryptorObject.decrypt Exception:', err + + if initialDecryptionSuccessful: + #This is a message bound for me. + flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage violently. + readPosition = 0 + messageVersion, messageVersionLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += messageVersionLength + if messageVersion != 1: + print 'Cannot understand message versions other than one. Ignoring message.' + return + sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += sendersAddressVersionNumberLength + if sendersAddressVersionNumber == 0: + print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.' + return + if sendersAddressVersionNumber >= 3: + print 'Sender\'s address version number', sendersAddressVersionNumber, ' not yet supported. Ignoring message.' + return + if len(data) < 170: + print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.' + return + sendersStreamNumber, sendersStreamNumberLength = decodeVarint(data[readPosition:readPosition+10]) + if sendersStreamNumber == 0: + print 'sender\'s stream number is 0. Ignoring message.' + return + readPosition += sendersStreamNumberLength + behaviorBitfield = data[readPosition:readPosition+4] + readPosition += 4 + pubSigningKey = '\x04' + data[readPosition:readPosition+64] + readPosition += 64 + pubEncryptionKey = '\x04' + data[readPosition:readPosition+64] + readPosition += 64 + endOfThePublicKeyPosition = readPosition #needed for when we store the pubkey in our database of pubkeys for later use. + if toRipe != data[readPosition:readPosition+20]: + 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://tools.ietf.org/html/draft-ietf-smime-sender-auth-00' + print 'your toRipe:', toRipe.encode('hex') + print 'embedded destination toRipe:', data[readPosition:readPosition+20].encode('hex') + printLock.release() + return + readPosition += 20 + messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += messageEncodingTypeLength + messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += messageLengthLength + message = data[readPosition:readPosition+messageLength] + #print 'First 150 characters of message:', repr(message[:150]) + readPosition += messageLength + ackLength, ackLengthLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += ackLengthLength + ackData = data[readPosition:readPosition+ackLength] + readPosition += ackLength + positionOfBottomOfAckData = readPosition #needed to mark the end of what is covered by the signature + signatureLength, signatureLengthLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += signatureLengthLength + signature = data[readPosition:readPosition+signatureLength] + + try: + highlevelcrypto.verify(data[:positionOfBottomOfAckData],signature,pubSigningKey.encode('hex')) + print 'ECDSA verify passed' + except Exception, err: + print 'ECDSA verify failed', err + return + + printLock.acquire() + print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:',calculateTestnetAddressFromPubkey(pubSigningKey),'. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' + printLock.release() + #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. + #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(),False,'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+data[messageVersionLength:endOfThePublicKeyPosition],int(time.time())+2419200) #after one month we may remove this pub key from our database. (2419200 = a month) + sqlLock.acquire() + sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + + blockMessage = False #Gets set to True if the user shouldn't see the message according to black or white lists. + fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()) + if config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist + t = (fromAddress,) + sqlLock.acquire() + sqlSubmitQueue.put('''SELECT label, enabled FROM blacklist where address=?''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + for row in queryreturn: + label, enabled = row + if enabled: + print 'Message ignored because address is in blacklist.' + blockMessage = True + else: #We're using a whitelist + t = (fromAddress,) + sqlLock.acquire() + sqlSubmitQueue.put('''SELECT label, enabled FROM whitelist where address=?''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + if queryreturn == []: + print 'Message ignored because address not in whitelist.' + blockMessage = True + for row in queryreturn: #It could be in the whitelist but disabled. Let's check. + label, enabled = row + if not enabled: + print 'Message ignored because address in whitelist but not enabled.' + blockMessage = True + + if not blockMessage: + print 'fromAddress:', fromAddress + print 'First 150 characters of message:', repr(message[:150]) + + #Look up the destination address (my address) based on the destination ripe hash. + #I realize that I could have a data structure devoted to this task, or maintain an indexed table + #in the sql database, but I would prefer to minimize the number of data structures this program + #uses. Searching linearly through the user's short list of addresses doesn't take very long anyway. + configSections = config.sections() + for addressInKeysFile in configSections: + if addressInKeysFile <> 'bitmessagesettings': + status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) + if hash == key: + toAddress = addressInKeysFile + toLabel = config.get(addressInKeysFile, 'label') + if toLabel == '': + toLabel = addressInKeysFile + + 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. 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 = '' + print 'within recmsg, inventoryHash is', inventoryHash.encode('hex') + if messageEncodingType <> 0: + sqlLock.acquire() + t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') + sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) + #Now let's send the acknowledgement. We'll need to make sure that our client will properly process the ackData; if the packet is malformed, we could clear out self.data and an attacker could use that behavior to determine that we were capable of decoding this message. + ackDataValidThusFar = True + if len(ackData) < 24: + print 'The length of ackData is unreasonably short. Not sending ackData.' + ackDataValidThusFar = False + elif ackData[0:4] != '\xe9\xbe\xb4\xd9': + print 'Ackdata magic bytes were wrong. Not sending ackData.' + ackDataValidThusFar = False + if ackDataValidThusFar: + 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.' + ackDataValidThusFar = False + if ackDataValidThusFar: + print 'ackData is valid. Will process it.' + #self.data = self.data[:self.payloadLength+24] + ackData + self.data[self.payloadLength+24:] + 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. + #print 'self.data after:', repr(self.data) + + + #This section is for my RSA keys (version 1 addresses). If we don't have any version 1 addresses, then it won't matter. + initialDecryptionSuccessful = False infile = cStringIO.StringIO(self.data[readPosition:self.payloadLength+24]) outfile = cStringIO.StringIO() - #print 'len(myAddressHashes.items()):', len(myAddressHashes.items()) - for key, value in myAddressHashes.items(): + #print 'len(myRSAAddressHashes.items()):', len(myRSAAddressHashes.items()) + for key, value in myRSAAddressHashes.items(): try: decrypt_bigfile(infile, outfile, value) #The initial decryption passed though there is a small chance that the message isn't actually for me. We'll need to check that the 20 zeros are present. @@ -669,190 +952,160 @@ class receiveDataThread(QThread): if sendersAddressVersionNumber == 1: readPosition += sendersAddressVersionNumberLength sendersStreamNumber, sendersStreamNumberLength = decodeVarint(data[readPosition:readPosition+10]) - readPosition += sendersStreamNumberLength + if sendersStreamNumber == 0: + print 'sendersStreamNumber = 0. Ignoring message' + else: + readPosition += sendersStreamNumberLength - sendersNLength, sendersNLengthLength = decodeVarint(data[readPosition:readPosition+10]) - readPosition += sendersNLengthLength - sendersN = data[readPosition:readPosition+sendersNLength] - readPosition += sendersNLength - sendersELength, sendersELengthLength = decodeVarint(data[readPosition:readPosition+10]) - readPosition += sendersELengthLength - sendersE = data[readPosition:readPosition+sendersELength] - readPosition += sendersELength - endOfThePublicKeyPosition = readPosition + sendersNLength, sendersNLengthLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += sendersNLengthLength + sendersN = data[readPosition:readPosition+sendersNLength] + readPosition += sendersNLength + sendersELength, sendersELengthLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += sendersELengthLength + sendersE = data[readPosition:readPosition+sendersELength] + readPosition += sendersELength + endOfThePublicKeyPosition = readPosition + messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+10]) + readPosition += messageEncodingTypeLength + print 'Message Encoding Type:', messageEncodingType + messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+10]) + print 'message length:', messageLength + readPosition += messageLengthLength + message = data[readPosition:readPosition+messageLength] + #print 'First 150 characters of message:', repr(message[:150]) + readPosition += messageLength + ackLength, ackLengthLength = decodeVarint(data[readPosition:readPosition+10]) + #print 'ackLength:', ackLength + readPosition += ackLengthLength + ackData = data[readPosition:readPosition+ackLength] + readPosition += ackLength + payloadSigniture = data[readPosition:readPosition+sendersNLength] #We're using the length of the sender's n because it should match the signiture size. + sendersPubkey = rsa.PublicKey(convertStringToInt(sendersN),convertStringToInt(sendersE)) + print 'sender\'s Pubkey', sendersPubkey - messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+10]) - readPosition += messageEncodingTypeLength - print 'Message Encoding Type:', messageEncodingType - messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+10]) - print 'message length:', messageLength - readPosition += messageLengthLength - message = data[readPosition:readPosition+messageLength] - #print 'First 150 characters of message:', repr(message[:150]) - readPosition += messageLength - ackLength, ackLengthLength = decodeVarint(data[readPosition:readPosition+10]) - #print 'ackLength:', ackLength - readPosition += ackLengthLength - ackData = data[readPosition:readPosition+ackLength] - readPosition += ackLength - payloadSigniture = data[readPosition:readPosition+sendersNLength] #We're using the length of the sender's n because it should match the signiture size. - sendersPubkey = rsa.PublicKey(convertStringToInt(sendersN),convertStringToInt(sendersE)) - print 'sender\'s Pubkey', sendersPubkey - - #Check the cryptographic signiture - verifyPassed = False - try: - rsa.verify(data[:-len(payloadSigniture)],payloadSigniture, sendersPubkey) - print 'verify passed' - verifyPassed = True - except Exception, err: - print 'verify failed', err - if verifyPassed: - #Let's calculate the fromAddress. - sha = hashlib.new('sha512') - sha.update(sendersN+sendersE) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) + #Check the cryptographic signiture + verifyPassed = False + try: + rsa.verify(data[:-len(payloadSigniture)],payloadSigniture, sendersPubkey) + print 'verify passed' + verifyPassed = True + except Exception, err: + print 'verify failed', err + if verifyPassed: + #calculate the fromRipe. + sha = hashlib.new('sha512') + sha.update(sendersN+sendersE) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) - #Let's store the public key in case we want to reply to this person. - #We don't have the correct nonce in order to 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(),False,'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+data[20+messageVersionLength:endOfThePublicKeyPosition],int(time.time())+2419200) #after one month we may remove this pub key from our database. (2419200 = a month) - sqlLock.acquire() - sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') - sqlSubmitQueue.put(t) - sqlReturnQueue.get() - sqlLock.release() - - blockMessage = False #Gets set to True if the user shouldn't see the message according to black or white lists. - fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()) - if config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist - t = (fromAddress,) + #Let's store the public key in case we want to reply to this person. + #We don't have the correct nonce in order to 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(),False,'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+data[20+messageVersionLength:endOfThePublicKeyPosition],int(time.time())+2419200) #after one month we may remove this pub key from our database. (2419200 = a month) sqlLock.acquire() - sqlSubmitQueue.put('''SELECT label, enabled FROM blacklist where address=?''') + sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - sqlLock.release() - for row in queryreturn: - label, enabled = row - if enabled: - print 'Message ignored because address is in blacklist.' - blockMessage = True - else: #We're using a whitelist - t = (fromAddress,) - sqlLock.acquire() - sqlSubmitQueue.put('''SELECT label, enabled FROM whitelist where address=?''') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - sqlLock.release() - if queryreturn == []: - print 'Message ignored because address not in whitelist.' - blockMessage = True - for row in queryreturn: #It could be in the whitelist but disabled. Let's check. - label, enabled = row - if not enabled: - print 'Message ignored because address in whitelist but not enabled.' - blockMessage = True + sqlReturnQueue.get() + sqlLock.release() - if not blockMessage: - print 'fromAddress:', fromAddress - print 'First 150 characters of message:', repr(message[:150]) - - #Look up the destination address (my address) based on the destination ripe hash. - #I realize that I could have a data structure devoted to this task, or maintain an indexed table - #in the sql database, but I would prefer to minimize the number of data structures this program - #uses. Searching linearly through the user's short list of addresses doesn't take very long anyway. - configSections = config.sections() - for addressInKeysFile in configSections: - if addressInKeysFile <> 'bitmessagesettings': - status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) - if hash == key: - toAddress = addressInKeysFile - toLabel = config.get(addressInKeysFile, 'label') - if toLabel == '': - toLabel = addressInKeysFile - - 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. 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 = '' - print 'within recmsg, inventoryHash is', repr(inventoryHash) - if messageEncodingType <> 0: + blockMessage = False #Gets set to True if the user shouldn't see the message according to black or white lists. + fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()) + if config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist + t = (fromAddress,) sqlLock.acquire() - t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') - sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') + sqlSubmitQueue.put('''SELECT label, enabled FROM blacklist where address=?''') sqlSubmitQueue.put(t) - sqlReturnQueue.get() + queryreturn = sqlReturnQueue.get() sqlLock.release() - self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) - #Now let's send the acknowledgement - #POW, = unpack('>Q',hashlib.sha512(hashlib.sha512(ackData[24:]).digest()).digest()[4:12]) - #if POW <= 2**64 / ((len(ackData[24:])+payloadLengthExtraBytes) * averageProofOfWorkNonceTrialsPerByte): - #print 'The POW is strong enough that this ackdataPayload will be accepted by the Bitmessage network.' - #Currently PyBitmessage only supports sending a message with the acknowledgement in the form of a msg message. But future versions, and other clients, could send any object and this software will relay them. This can be used to relay identifying information, like your public key, through another Bitmessage host in case you believe that your Internet connection is being individually watched. You may pick a random address, hope its owner is online, and send a message with encoding type 0 so that they ignore the message but send your acknowledgement data over the network. If you send and receive many messages, it would also be clever to take someone else's acknowledgement data and use it for your own. Assuming that your message is delivered successfully, both will be acknowledged simultaneously (though if it is not delivered successfully, you will be in a pickle.) - #print 'self.data before:', repr(self.data) - #We'll need to make sure that our client will properly process the ackData; if the packet is malformed, we could clear out self.data and an attacker could use that behavior to determine that we were capable of decoding this message. - ackDataValidThusFar = True - if len(ackData) < 24: - print 'The length of ackData is unreasonably short. Not sending ackData.' - ackDataValidThusFar = False - if ackData[0:4] != '\xe9\xbe\xb4\xd9': - print 'Ackdata magic bytes were wrong. Not sending ackData.' - ackDataValidThusFar = False - if ackDataValidThusFar: - 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.' - ackDataValidThusFar = False - if ackDataValidThusFar: - print 'ackData is valid. Will process it.' - #self.data = self.data[:self.payloadLength+24] + ackData + self.data[self.payloadLength+24:] - 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. - #print 'self.data after:', repr(self.data) - '''if ackData[4:16] == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00': - inventoryHash = calculateInventoryHash(ackData[24:]) - #objectType = 'msg' - #inventory[inventoryHash] = (objectType, self.streamNumber, ackData[24:], embeddedTime) #We should probably be storing the embeddedTime of the ackData, not the embeddedTime of the original incoming msg message, but this is probably close enough. - #print 'sending the inv for the msg which is actually an acknowledgement (within sendmsg function)' - #self.broadcastinv(inventoryHash) - self.data[:payloadLength+24] + ackData + self.data[payloadLength+24:] - elif ackData[4:16] == 'getpubkey\x00\x00\x00': - #objectType = 'getpubkey' - #inventory[inventoryHash] = (objectType, self.streamNumber, ackData[24:], embeddedTime) #We should probably be storing the embeddedTime of the ackData, not the embeddedTime of the original incoming msg message, but this is probably close enough. - #print 'sending the inv for the getpubkey which is actually an acknowledgement (within sendmsg function)' - self.data[:payloadLength+24] + ackData + self.data[payloadLength+24:] - elif ackData[4:16] == 'pubkey\x00\x00\x00\x00\x00\x00': - #objectType = 'pubkey' - #inventory[inventoryHash] = (objectType, self.streamNumber, ackData[24:], embeddedTime) #We should probably be storing the embeddedTime of the ackData, not the embeddedTime of the original incoming msg message, but this is probably close enough. - #print 'sending the inv for a pubkey which is actually an acknowledgement (within sendmsg function)' - self.data[:payloadLength+24] + ackData + self.data[payloadLength+24:] - elif ackData[4:16] == 'broadcast\x00\x00\x00': - #objectType = 'broadcast' - #inventory[inventoryHash] = (objectType, self.streamNumber, ackData[24:], embeddedTime) #We should probably be storing the embeddedTime of the ackData, not the embeddedTime of the original incoming msg message, but this is probably close enough. - #print 'sending the inv for a broadcast which is actually an acknowledgement (within sendmsg function)' - self.data[:payloadLength+24] + ackData + self.data[payloadLength+24:]''' - #else: - #print 'ACK POW not strong enough to be accepted by the Bitmessage network.' + for row in queryreturn: + label, enabled = row + if enabled: + print 'Message ignored because address is in blacklist.' + blockMessage = True + else: #We're using a whitelist + t = (fromAddress,) + sqlLock.acquire() + sqlSubmitQueue.put('''SELECT label, enabled FROM whitelist where address=?''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + if queryreturn == []: + print 'Message ignored because address not in whitelist.' + blockMessage = True + for row in queryreturn: #It could be in the whitelist but disabled. Let's check. + label, enabled = row + if not enabled: + print 'Message ignored because address in whitelist but not enabled.' + blockMessage = True + if not blockMessage: + print 'fromAddress:', fromAddress + print 'First 150 characters of message:', repr(message[:150]) + + #Look up the destination address (my address) based on the destination ripe hash. + #I realize that I could have a data structure devoted to this task, or maintain an indexed table + #in the sql database, but I would prefer to minimize the number of data structures this program + #uses. Searching linearly through the user's short list of addresses doesn't take very long anyway. + configSections = config.sections() + for addressInKeysFile in configSections: + if addressInKeysFile <> 'bitmessagesettings': + status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) + if hash == key: + toAddress = addressInKeysFile + toLabel = config.get(addressInKeysFile, 'label') + if toLabel == '': + toLabel = addressInKeysFile + break + + 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. 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 = '' + print 'within recmsg, inventoryHash is', repr(inventoryHash) + if messageEncodingType <> 0: + sqlLock.acquire() + t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox') + sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body) + #Now let us worry about the acknowledgement data + #We'll need to make sure that our client will properly process the ackData; if the packet is malformed, it might cause us to clear out self.data and an attacker could use that behavior to determine that we decoded this message. + ackDataValidThusFar = True + if len(ackData) < 24: + print 'The length of ackData is unreasonably short. Not sending ackData.' + ackDataValidThusFar = False + if ackData[0:4] != '\xe9\xbe\xb4\xd9': + print 'Ackdata magic bytes were wrong. Not sending ackData.' + ackDataValidThusFar = False + if ackDataValidThusFar: + ackDataPayloadLength, = unpack('>L',ackData[16:20]) + if len(ackData)-24 != ackDataPayloadLength: #This ackData includes the protocol header which is not counted in the payload length. + print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.' + ackDataValidThusFar = False + if ackDataValidThusFar: + 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. else: print 'This program cannot decode messages from addresses with versions higher than 1. Ignoring.' statusbar = 'This program cannot decode messages from addresses with versions higher than 1. Ignoring it.' self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) else: - print 'Error: Cannot decode incoming msg versions higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.' - statusbar = 'Error: Cannot decode incoming msg versions higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.' + statusbar = 'Error: Cannot decode incoming msg versions higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage. Ignoring message.' self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) else: printLock.acquire() @@ -863,6 +1116,8 @@ class receiveDataThread(QThread): #We have received a pubkey def recpubkey(self): + if self.payloadLength < 32: #sanity check + return #We must check to make sure the proof of work is sufficient. if not self.isProofOfWorkSufficient(): print 'Proof of work in pubkey message insufficient.' @@ -879,54 +1134,102 @@ class receiveDataThread(QThread): inventoryLock.release() return + readPosition = 24 #for the message header + readPosition += 8 #for the nonce + #bitfieldBehaviors = self.data[readPosition:readPosition+4] The bitfieldBehaviors used to be here + embeddedTime = self.data[readPosition:readPosition+4] + readPosition += 4 #for the time + addressVersion, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) + readPosition += varintLength + streamNumber, varintLength = decodeVarint(self.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 + objectType = 'pubkey' inventory[inventoryHash] = (objectType, self.streamNumber, self.data[24:self.payloadLength+24], int(time.time())) inventoryLock.release() self.broadcastinv(inventoryHash) self.emit(SIGNAL("incrementNumberOfPubkeysProcessed()")) - readPosition = 24 #for the message header - readPosition += 8 #for the nonce - bitfieldBehaviors = self.data[readPosition:readPosition+4] - readPosition += 4 #for the bitfield of behaviors and features - addressVersion, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) - if addressVersion >= 2: - print 'This version of Bitmessgae cannot handle version', addressVersion,'addresses.' + if addressVersion == 0: + print 'Within recpubkey, addressVersion of zero doesn\'t make sense.' return - readPosition += varintLength - streamNumber, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) - readPosition += varintLength - #ripe = self.data[readPosition:readPosition+20] - #readPosition += 20 #for the ripe hash - nLength, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) - readPosition += varintLength - nString = self.data[readPosition:readPosition+nLength] - readPosition += nLength - eLength, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) - readPosition += varintLength - eString = self.data[readPosition:readPosition+eLength] - readPosition += eLength + if addressVersion >= 3: + printLock.acquire() + print 'This version of Bitmessage cannot handle version', addressVersion,'addresses.' + printLock.release() + return + if addressVersion == 2: + if self.payloadLength < 146: #sanity check. This is the minimum possible length. + print 'payloadLength less than 146. Sanity check failed.' + return + bitfieldBehaviors = self.data[readPosition:readPosition+4] + readPosition += 4 + publicSigningKey = self.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 = self.data[readPosition:readPosition+64] + if len(publicEncryptionKey) < 64: + print 'publicEncryptionKey length less than 64. Sanity check failed.' + return + sha = hashlib.new('sha512') + print 'recpubkey hashing this data to make the ripe:', repr('\x04'+publicSigningKey+'\x04'+publicEncryptionKey) + sha.update('\x04'+publicSigningKey+'\x04'+publicEncryptionKey) + ripeHasher = hashlib.new('ripemd160') + ripeHasher.update(sha.digest()) + ripe = ripeHasher.digest() - sha = hashlib.new('sha512') - sha.update(nString+eString) - ripeHasher = hashlib.new('ripemd160') - ripeHasher.update(sha.digest()) - ripe = ripeHasher.digest() + printLock.acquire() + print 'within recpubkey, addressVersion', addressVersion + print 'streamNumber', streamNumber + print 'ripe', ripe.encode('hex') + print 'publicSigningKey in hex:', publicSigningKey.encode('hex') + print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex') + printLock.release() - print 'within recpubkey, addressVersion', addressVersion - print 'streamNumber', streamNumber - print 'ripe', repr(ripe) - print 'n=', convertStringToInt(nString) - print 'e=', convertStringToInt(eString) + t = (ripe,True,self.data[24:24+self.payloadLength],int(time.time())+604800) #after one week we may remove this pub key from our database. + sqlLock.acquire() + sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + printLock.acquire() + print 'added foreign pubkey into our database' + printLock.release() + workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) - t = (ripe,True,self.data[24:24+self.payloadLength],int(time.time())+604800) #after one week we may remove this pub key from our database. - sqlLock.acquire() - sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') - sqlSubmitQueue.put(t) - sqlReturnQueue.get() - sqlLock.release() - print 'added foreign pubkey into our database' - workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) + elif addressVersion == 1: + nLength, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) + readPosition += varintLength + nString = self.data[readPosition:readPosition+nLength] + readPosition += nLength + eLength, varintLength = decodeVarint(self.data[readPosition:readPosition+10]) + readPosition += varintLength + eString = self.data[readPosition:readPosition+eLength] + readPosition += eLength + + sha = hashlib.new('sha512') + sha.update(nString+eString) + ripeHasher = hashlib.new('ripemd160') + ripeHasher.update(sha.digest()) + ripe = ripeHasher.digest() + + print 'within recpubkey, addressVersion', addressVersion + print 'streamNumber', streamNumber + print 'ripe', repr(ripe) + print 'n=', convertStringToInt(nString) + print 'e=', convertStringToInt(eString) + + t = (ripe,True,self.data[24:24+self.payloadLength],int(time.time())+604800) #after one week we may remove this pub key from our database. + sqlLock.acquire() + sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + sqlSubmitQueue.put(t) + sqlReturnQueue.get() + sqlLock.release() + print 'added foreign pubkey into our database' + workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) #We have received a getpubkey message def recgetpubkey(self): @@ -965,22 +1268,45 @@ class receiveDataThread(QThread): #This getpubkey request is valid so far. Forward to peers. broadcastToSendDataQueues((self.streamNumber,'send',self.data[:self.payloadLength+24])) - - if addressVersionNumber > 1: - print 'The addressVersionNumber of the pubkey is too high. Can\'t understand. Ignoring it.' + if addressVersionNumber == 0: + print 'The addressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.' return - if self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength] in myAddressHashes: - print 'Found getpubkey requested hash in my list of hashes.' - #check to see whether we have already calculated the nonce and transmitted this key before - sqlLock.acquire()#released at the bottom of this payload generation section - t = (self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],) #this prevents SQL injection - sqlSubmitQueue.put('SELECT * FROM pubkeys WHERE hash=?') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - #print 'queryreturn', queryreturn + elif addressVersionNumber > 2: + print 'The addressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.' + return + print 'the hash requested in this getpubkey request is:', self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength].encode('hex') - if queryreturn == []: - print 'pubkey request is for me but the pubkey is not in our database of pubkeys. Making it.' + sqlLock.acquire() + t = (self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],) #this prevents SQL injection + sqlSubmitQueue.put('''SELECT hash, transmitdata, time FROM pubkeys WHERE hash=? AND havecorrectnonce=1''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + if queryreturn != []: + for row in queryreturn: + hash, payload, timeLastRequested = row + if timeLastRequested < int(time.time())+604800: #if the last time anyone asked about this hash was this week, extend the time. + sqlLock.acquire() + t = (int(time.time())+604800,hash) + sqlSubmitQueue.put('''UPDATE pubkeys set time=? WHERE hash=?''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + + inventoryHash = calculateInventoryHash(payload) + objectType = 'pubkey' + inventory[inventoryHash] = (objectType, self.streamNumber, payload, int(time.time())) + self.broadcastinv(inventoryHash) + else: #the pubkey is not in our database of pubkeys. Let's check if the requested key is ours (which would mean we should do the POW, put it in the pubkey table, and broadcast out the pubkey. + + if self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength] in myECAddressHashes: #if this address hash is one of mine + 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.' + myAddress = encodeAddress(addressVersionNumber,streamNumber,self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength]) + workerQueue.put(('doPOWForMyV2Pubkey',myAddress)) + + + elif self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength] in myRSAAddressHashes: + print 'Found getpubkey requested hash in my list of RSA hashes.' payload = '\x00\x00\x00\x01' #bitfield of features supported by me (see the wiki). payload += self.data[36:36+addressVersionLength+streamNumberLength] #print int(config.get(encodeAddress(addressVersionNumber,streamNumber,self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength]), 'n')) @@ -999,63 +1325,23 @@ class receiveDataThread(QThread): while trialValue > target: nonce += 1 trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) - #trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + payload).digest()).digest()[4:12]) print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce payload = pack('>Q',nonce) + payload t = (self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],True,payload,int(time.time())+1209600) #after two weeks (1,209,600 seconds), we may remove our own pub key from our database. It will be regenerated and put back in the database if it is requested. + sqlLock.acquire() sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') sqlSubmitQueue.put(t) queryreturn = sqlReturnQueue.get() - - #Now that we have the full pubkey message ready either from making it just now or making it earlier, we can send it out. - t = (self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],) #this prevents SQL injection - sqlSubmitQueue.put('''SELECT * FROM pubkeys WHERE hash=? AND havecorrectnonce=1''') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - if queryreturn == []: - sys.stderr.write('Error: pubkey which we just put in our pubkey database suddenly is not there. Is the database malfunctioning?') sqlLock.release() - return - for row in queryreturn: - hash, havecorrectnonce, payload, timeLastRequested = row - if timeLastRequested < int(time.time())+604800: #if the last time anyone asked about this hash was this week, extend the time. - t = (int(time.time())+604800,hash) - sqlSubmitQueue.put('''UPDATE pubkeys set time=? WHERE hash=?''') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - - sqlLock.release() - - inventoryHash = calculateInventoryHash(payload) - objectType = 'pubkey' - inventory[inventoryHash] = (objectType, self.streamNumber, payload, int(time.time())) - self.broadcastinv(inventoryHash) - - else: - print 'Hash in getpubkey request is not for any of my keys.' - #..but lets see if we have it stored from when it came in from someone else. - t = (self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],) #this prevents SQL injection - sqlLock.acquire() - sqlSubmitQueue.put('''SELECT hash, transmitdata, time FROM pubkeys WHERE hash=? AND havecorrectnonce=1''') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - sqlLock.release() - print 'queryreturn', queryreturn - if queryreturn <> []: - print 'we have the public key. sending it.' - #We have it. Let's send it. - for row in queryreturn: - hash, transmitdata, timeLastRequested = row - if timeLastRequested < int(time.time())+604800: #if the last time anyone asked about this hash was this week, extend the time. - t = (int(time.time())+604800,hash) - sqlSubmitQueue.put('''UPDATE pubkeys set time=? WHERE hash=? ''') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - inventoryHash = calculateInventoryHash(transmitdata) + inventoryHash = calculateInventoryHash(payload) objectType = 'pubkey' - inventory[inventoryHash] = (objectType, self.streamNumber, transmitdata, int(time.time())) + inventory[inventoryHash] = (objectType, self.streamNumber, payload, int(time.time())) self.broadcastinv(inventoryHash) + else: + printLock.acquire() + print 'This getpubkey request is not for any of my keys.' + printLock.release() #We have received an inv message @@ -1078,7 +1364,7 @@ class receiveDataThread(QThread): #Send a getdata message to our peer to request the object with the given hash def sendgetdata(self,hash): - print 'sending getdata with hash', repr(hash) + 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 = headerData + 'getdata\x00\x00\x00\x00\x00' @@ -1093,7 +1379,9 @@ class receiveDataThread(QThread): try: for i in range(value): hash = self.data[24+lengthOfVarint+(i*32):56+lengthOfVarint+(i*32)] - print 'getdata request for item:', repr(hash), 'length', len(hash) + printLock.acquire() + print 'received getdata request for item:', hash.encode('hex') + printLock.release() #print 'inventory is', inventory if hash in inventory: objectType, streamNumber, payload, receivedTime = inventory[hash] @@ -1157,15 +1445,13 @@ class receiveDataThread(QThread): #Send an inv message with just one hash to all of our peers def broadcastinv(self,hash): - print 'sending inv' - #payload = '\x01' + pack('>H',objectType) + hash payload = '\x01' + hash headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' headerData = headerData + pack('>L',len(payload)) headerData = headerData + hashlib.sha512(payload).digest()[:4] printLock.acquire() - print 'broadcasting inv with hash:', repr(hash) + print 'broadcasting inv with hash:', hash.encode('hex') printLock.release() broadcastToSendDataQueues((self.streamNumber, 'send', headerData + payload)) @@ -1270,7 +1556,7 @@ class receiveDataThread(QThread): if verbose >= 2: printLock.acquire() - print 'Broadcasting addr with # of entries:', numberOfAddressesInAddrMessage + print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' printLock.release() broadcastToSendDataQueues((self.streamNumber, 'send', datatosend)) @@ -1338,7 +1624,7 @@ class receiveDataThread(QThread): if verbose >= 2: printLock.acquire() - print 'Sending addr with # of entries:', numberOfAddressesInAddrMessage + print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' printLock.release() self.sock.send(datatosend) @@ -1357,12 +1643,15 @@ class receiveDataThread(QThread): #print 'self.data[96:104]', repr(self.data[96:104]) #print 'eightBytesOfRandomDataUsedToDetectConnectionsToSelf', repr(eightBytesOfRandomDataUsedToDetectConnectionsToSelf) useragentLength, lengthOfUseragentVarint = decodeVarint(self.data[104:108]) - readPosition = 104 + lengthOfUseragentVarint + useragentLength - #Note that PyBitmessage curreutnly currentl supports a single stream per connection. + readPosition = 104 + lengthOfUseragentVarint + useragent = self.data[readPosition:readPosition+useragentLength] + readPosition += useragentLength numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint(self.data[readPosition:]) readPosition += lengthOfNumberOfStreamsInVersionMessage self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint(self.data[readPosition:]) - print 'Remote node stream number:', self.streamNumber + printLock.acquire() + print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber + printLock.release() #If this was an incoming connection, then the sendData thread doesn't know the stream. We have to set it. if not self.initiatedConnection: broadcastToSendDataQueues((0,'setStreamNumber',(self.HOST,self.streamNumber))) @@ -1429,14 +1718,16 @@ class receiveDataThread(QThread): datatosend = datatosend + payload printLock.acquire() - print 'Sending version packet: ', repr(datatosend) + print 'Sending version message' printLock.release() self.sock.send(datatosend) #self.versionSent = 1 #Sends a verack message def sendverack(self): + printLock.acquire() print 'Sending verack' + printLock.release() 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') #cf 83 e1 35 self.verackSent = True @@ -1458,7 +1749,7 @@ class sendDataThread(QThread): self.streamNumber = streamNumber self.lastTimeISentData = int(time.time()) #If this value increases beyond five minutes ago, we'll send a pong message to keep the connection alive. printLock.acquire() - print 'The streamNumber of this sendDataThread at setup() is', self.streamNumber, self + print 'The streamNumber of this sendDataThread (ID:', id(self),') at setup() is', self.streamNumber printLock.release() def sendVersionMessage(self): @@ -1527,9 +1818,10 @@ class sendDataThread(QThread): self.streamNumber = specifiedStreamNumber elif command == 'send': try: - #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, 5)) + #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. + if self.mailbox.qsize() < 20: + random.seed() + time.sleep(random.randrange(0, 10)) self.sock.sendall(data) self.lastTimeISentData = int(time.time()) except: @@ -1601,6 +1893,84 @@ def convertIntToString(n): def convertStringToInt(s): return int(s.encode('hex'), 16) +def decodeWalletImportFormat(WIFstring): + fullString = arithmetic.changebase(WIFstring,58,256) + privkey = fullString[:-4] + if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]: + sys.stderr.write('Major problem! When trying to decode one of your private keys, the checksum failed. Here is the PRIVATE key: %s\n' % str(WIFstring)) + return "" + else: + #checksum passed + if privkey[0] == '\x80': + return privkey[1:] + else: + sys.stderr.write('Major problem! When trying to decode one of your private keys, the checksum passed but the key doesn\'t begin with hex 80. Here is the PRIVATE key: %s\n' % str(WIFstring)) + return "" + +def reloadMyAddressHashes(): + printLock.acquire() + print 'reloading keys from keys.dat file' + printLock.release() + myRSAAddressHashes.clear() + #myPrivateKeys.clear() + configSections = config.sections() + for addressInKeysFile in configSections: + if addressInKeysFile <> 'bitmessagesettings': + isEnabled = config.getboolean(addressInKeysFile, 'enabled') + if isEnabled: + status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) + if addressVersionNumber == 2: + privEncryptionKey = decodeWalletImportFormat(config.get(addressInKeysFile, 'privencryptionkey')).encode('hex') #returns a simple 32 bytes of information encoded in 64 Hex characters, or null if there was an error + if len(privEncryptionKey) == 64:#It is 32 bytes encoded as 64 hex characters + myECAddressHashes[hash] = highlevelcrypto.makeCryptor(privEncryptionKey) + elif addressVersionNumber == 1: + n = config.getint(addressInKeysFile, 'n') + e = config.getint(addressInKeysFile, 'e') + d = config.getint(addressInKeysFile, 'd') + p = config.getint(addressInKeysFile, 'p') + q = config.getint(addressInKeysFile, 'q') + myRSAAddressHashes[hash] = rsa.PrivateKey(n,e,d,p,q) + +#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 + + #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(QThread): def __init__(self, parent = None): @@ -1787,7 +2157,7 @@ class singleWorker(QThread): #We'll need to request the pub key because we don't have it. if not toRipe in neededPubkeys: neededPubkeys[toRipe] = 0 - print 'requesting pubkey:', repr(toRipe) + print 'requesting pubkey:', toRipe.encode('hex') self.requestPubKey(toAddressVersionNumber,toStreamNumber,toRipe) else: print 'We have already requested this pubkey (the ripe hash is in neededPubkeys). We will re-request again soon.' @@ -1799,7 +2169,8 @@ class singleWorker(QThread): print 'Within WorkerThread, processing sendbroadcast command.' fromAddress,subject,message = data self.sendBroadcast() - + elif command == 'doPOWForMyV2Pubkey': + self.doPOWForMyV2Pubkey(data) elif command == 'newpubkey': toAddressVersion,toStreamNumber,toRipe = data if toRipe in neededPubkeys: @@ -1807,10 +2178,66 @@ class singleWorker(QThread): del neededPubkeys[toRipe] self.sendMsg(toRipe) else: - print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', repr(toRipe) + print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', toRipe.encode('hex') workerQueue.task_done() + def doPOWForMyV2Pubkey(self,myAddress): #This function also broadcasts out the pubkey message once it is done with the POW + status,addressVersionNumber,streamNumber,hash = decodeAddress(myAddress) + payload = pack('>I',(int(time.time())+random.randrange(-300, 300))) #the current time plus or minus five minutes + payload += encodeVarint(2) #Address version number + payload += encodeVarint(streamNumber) + payload += '\x00\x00\x00\x01' #bitfield of features supported by me (see the wiki). + + privSigningKeyBase58 = config.get(myAddress, 'privsigningkey') + privEncryptionKeyBase58 = config.get(myAddress, 'privencryptionkey') + + privSigningKeyHex = decodeWalletImportFormat(privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') + pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') + pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') + + #print 'within recgetpubkey' + #print 'pubSigningKey in hex:', pubSigningKey.encode('hex') + #print 'pubEncryptionKey in hex:', pubEncryptionKey.encode('hex') + + payload += pubSigningKey[1:] + payload += pubEncryptionKey[1:] + + #Time to do the POW for this pubkey message + nonce = 0 + trialValue = 99999999999999999999 + target = 2**64 / ((len(payload)+payloadLengthExtraBytes+8) * averageProofOfWorkNonceTrialsPerByte) + print '(For pubkey message) Doing proof of work...' + initialHash = hashlib.sha512(payload).digest() + while trialValue > target: + nonce += 1 + trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) + #trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + payload).digest()).digest()[4:12]) + print '(For pubkey message) Found proof of work', trialValue, 'Nonce:', nonce + + payload = pack('>Q',nonce) + payload + t = (hash,True,payload,int(time.time())+1209600) #after two weeks (1,209,600 seconds), we may remove our own pub key from our database. It will be regenerated and put back in the database if it is requested. + sqlLock.acquire() + sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + + inventoryHash = calculateInventoryHash(payload) + objectType = 'pubkey' + inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) + + payload = '\x01' + inventoryHash + headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. + headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' + headerData = headerData + pack('>L',len(payload)) + headerData = headerData + hashlib.sha512(payload).digest()[:4] + printLock.acquire() + print 'broadcasting inv with hash:', inventoryHash.encode('hex') + printLock.release() + broadcastToSendDataQueues((streamNumber, 'send', headerData + payload)) + def sendBroadcast(self): sqlLock.acquire() t = ('broadcastpending',) @@ -1822,72 +2249,137 @@ class singleWorker(QThread): #print 'within sendMsg, row is:', row #msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status = row fromaddress, subject, body, ackdata = row - messageToTransmit = '\x02' - messageToTransmit += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding. - messageToTransmit += 'Subject:' + subject + '\n' + 'Body:' + body - - #We need the all the integers for our private key in order to sign our message, and we need our public key to send with the message. - n = config.getint(fromaddress, 'n') - e = config.getint(fromaddress, 'e') - d = config.getint(fromaddress, 'd') - p = config.getint(fromaddress, 'p') - q = config.getint(fromaddress, 'q') - nString = convertIntToString(n) - eString = convertIntToString(e) - myPubkey = rsa.PublicKey(n,e) - myPrivatekey = rsa.PrivateKey(n,e,d,p,q) status,addressVersionNumber,streamNumber,ripe = decodeAddress(fromaddress) - - #The payload of the broadcast message starts with a POW, but that will be added later. - payload = pack('>I',(int(time.time()))) - payload += encodeVarint(1) #broadcast version - payload += encodeVarint(addressVersionNumber) - payload += encodeVarint(streamNumber) - payload += ripe - payload += encodeVarint(len(nString)) - payload += nString - payload += encodeVarint(len(eString)) - payload += eString - payload += messageToTransmit - signature = rsa.sign(messageToTransmit,myPrivatekey,'SHA-512') - print 'signature', repr(signature) - payload += signature + if addressVersionNumber == 2: + #We need to convert our private keys to public keys in order to include them. + privSigningKeyBase58 = config.get(fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = config.get(fromaddress, 'privencryptionkey') - print 'nString', repr(nString) - print 'eString', repr(eString) + privSigningKeyHex = decodeWalletImportFormat(privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') - nonce = 0 - trialValue = 99999999999999999999 - target = 2**64 / ((len(payload)+payloadLengthExtraBytes+8) * averageProofOfWorkNonceTrialsPerByte) - print '(For broadcast message) Doing proof of work...' - initialHash = hashlib.sha512(payload).digest() - while trialValue > target: - nonce += 1 - trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) - print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce + 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('>I',(int(time.time()))) + 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 + + nonce = 0 + trialValue = 99999999999999999999 + target = 2**64 / ((len(payload)+payloadLengthExtraBytes+8) * averageProofOfWorkNonceTrialsPerByte) + print '(For broadcast message) Doing proof of work...' + initialHash = hashlib.sha512(payload).digest() + while trialValue > target: + nonce += 1 + trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) + print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce - payload = pack('>Q',nonce) + payload + payload = pack('>Q',nonce) + payload - inventoryHash = calculateInventoryHash(payload) - objectType = 'broadcast' - inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) - print 'sending inv (within sendBroadcast function)' - payload = '\x01' + inventoryHash - headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. - headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' - headerData = headerData + pack('>L',len(payload)) #payload length. Note that we add an extra 8 for the nonce. - headerData = headerData + hashlib.sha512(payload).digest()[:4] - broadcastToSendDataQueues((streamNumber, 'send', headerData + payload)) + inventoryHash = calculateInventoryHash(payload) + objectType = 'broadcast' + inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) + print 'sending inv (within sendBroadcast function)' + payload = '\x01' + inventoryHash + headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. + headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' + headerData = headerData + pack('>L',len(payload)) #payload length. Note that we add an extra 8 for the nonce. + headerData = headerData + hashlib.sha512(payload).digest()[:4] + broadcastToSendDataQueues((streamNumber, 'send', headerData + payload)) - self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),ackdata,'Broadcast sent at '+strftime(config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time())))) + self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),ackdata,'Broadcast sent at '+strftime(config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time())))) - #Update the status of the message in the 'sent' table to have a 'broadcastsent' status - sqlLock.acquire() - t = ('broadcastsent',int(time.time()),fromaddress, subject, body,'broadcastpending') - sqlSubmitQueue.put('UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?') - sqlSubmitQueue.put(t) - queryreturn = sqlReturnQueue.get() - sqlLock.release() + #Update the status of the message in the 'sent' table to have a 'broadcastsent' status + sqlLock.acquire() + t = ('broadcastsent',int(time.time()),fromaddress, subject, body,'broadcastpending') + sqlSubmitQueue.put('UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + + elif addressVersionNumber == 1: #This whole section can be taken out soon because we aren't supporting v1 addresses for much longer. + messageToTransmit = '\x02' #message encoding type + messageToTransmit += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding. + messageToTransmit += 'Subject:' + subject + '\n' + 'Body:' + body + + #We need the all the integers for our private key in order to sign our message, and we need our public key to send with the message. + n = config.getint(fromaddress, 'n') + e = config.getint(fromaddress, 'e') + d = config.getint(fromaddress, 'd') + p = config.getint(fromaddress, 'p') + q = config.getint(fromaddress, 'q') + nString = convertIntToString(n) + eString = convertIntToString(e) + #myPubkey = rsa.PublicKey(n,e) + myPrivatekey = rsa.PrivateKey(n,e,d,p,q) + + #The payload of the broadcast message starts with a POW, but that will be added later. + payload = pack('>I',(int(time.time()))) + payload += encodeVarint(1) #broadcast version + payload += encodeVarint(addressVersionNumber) + payload += encodeVarint(streamNumber) + payload += ripe + payload += encodeVarint(len(nString)) + payload += nString + payload += encodeVarint(len(eString)) + payload += eString + payload += messageToTransmit + signature = rsa.sign(messageToTransmit,myPrivatekey,'SHA-512') + #print 'signature', signature.encode('hex') + payload += signature + + #print 'nString', repr(nString) + #print 'eString', repr(eString) + + nonce = 0 + trialValue = 99999999999999999999 + target = 2**64 / ((len(payload)+payloadLengthExtraBytes+8) * averageProofOfWorkNonceTrialsPerByte) + print '(For broadcast message) Doing proof of work...' + initialHash = hashlib.sha512(payload).digest() + while trialValue > target: + nonce += 1 + trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) + print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce + + payload = pack('>Q',nonce) + payload + + inventoryHash = calculateInventoryHash(payload) + objectType = 'broadcast' + inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) + print 'sending inv (within sendBroadcast function)' + payload = '\x01' + inventoryHash + headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. + headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' + headerData = headerData + pack('>L',len(payload)) #payload length. Note that we add an extra 8 for the nonce. + headerData = headerData + hashlib.sha512(payload).digest()[:4] + broadcastToSendDataQueues((streamNumber, 'send', headerData + payload)) + + self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),ackdata,'Broadcast sent at '+strftime(config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time())))) + + #Update the status of the message in the 'sent' table to have a 'broadcastsent' status + sqlLock.acquire() + t = ('broadcastsent',int(time.time()),fromaddress, subject, body,'broadcastpending') + sqlSubmitQueue.put('UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?') + sqlSubmitQueue.put(t) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + else: + printLock.acquire() + print 'In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version' + printLock.release() def sendMsg(self,toRipe): sqlLock.acquire() @@ -1904,74 +2396,139 @@ class singleWorker(QThread): for row in queryreturn: toaddress, fromaddress, subject, message, ackdata = row ackdataForWhichImWatching[ackdata] = 0 - status,addressVersionNumber,toStreamNumber,hash = decodeAddress(toaddress) - #if hash == toRipe: + toStatus,toAddressVersionNumber,toStreamNumber,toHash = decodeAddress(toaddress) + fromStatus,fromAddressVersionNumber,fromStreamNumber,fromHash = decodeAddress(fromaddress) self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),ackdata,'Doing work necessary to send the message.') printLock.acquire() - print 'Found the necessary message that needs to be sent with this pubkey.' + print 'Found a message in our database that needs to be sent with this pubkey.' print 'First 150 characters of message:', message[:150] printLock.release() - payload = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' #this run of nulls allows the true message receiver to identify his message - payload += '\x01' #Message version. - payload += '\x00\x00\x00\x01' - fromStatus,fromAddressVersionNumber,fromStreamNumber,fromHash = decodeAddress(fromaddress) - payload += encodeVarint(fromAddressVersionNumber) - payload += encodeVarint(fromStreamNumber) - sendersN = convertIntToString(config.getint(fromaddress, 'n')) - payload += encodeVarint(len(sendersN)) - payload += sendersN + if fromAddressVersionNumber == 2: + payload = '\x01' #Message version. + payload += encodeVarint(fromAddressVersionNumber) + payload += encodeVarint(fromStreamNumber) + payload += '\x00\x00\x00\x01' - sendersE = convertIntToString(config.getint(fromaddress, 'e')) - payload += encodeVarint(len(sendersE)) - payload += sendersE + #We need to convert our private keys to public keys in order to include them. + privSigningKeyBase58 = config.get(fromaddress, 'privsigningkey') + privEncryptionKeyBase58 = config.get(fromaddress, 'privencryptionkey') - payload += '\x02' #Type 2 is simple UTF-8 message encoding. - messageToTransmit = 'Subject:' + subject + '\n' + 'Body:' + message - payload += encodeVarint(len(messageToTransmit)) - payload += messageToTransmit + privSigningKeyHex = decodeWalletImportFormat(privSigningKeyBase58).encode('hex') + privEncryptionKeyHex = decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') - #Later, if anyone impliments clients that don't send the ack_data, then we should probably check here to make sure that the receiver will make use of this ack_data and not attach it if not. - fullAckPayload = self.generateFullAckMessage(ackdata,toStreamNumber) - payload += encodeVarint(len(fullAckPayload)) - payload += fullAckPayload - sendersPrivKey = rsa.PrivateKey(config.getint(fromaddress, 'n'),config.getint(fromaddress, 'e'),config.getint(fromaddress, 'd'),config.getint(fromaddress, 'p'),config.getint(fromaddress, 'q')) + pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') + pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') - payload += rsa.sign(payload,sendersPrivKey,'SHA-512') + payload += pubSigningKey[1:] + payload += pubEncryptionKey[1:] - sqlLock.acquire() - sqlSubmitQueue.put('SELECT * FROM pubkeys WHERE hash=?') - sqlSubmitQueue.put((toRipe,)) - queryreturn = sqlReturnQueue.get() - sqlLock.release() + payload += toHash + payload += '\x02' #Type 2 is simple UTF-8 message encoding. + messageToTransmit = 'Subject:' + subject + '\n' + 'Body:' + message + payload += encodeVarint(len(messageToTransmit)) + payload += messageToTransmit + fullAckPayload = self.generateFullAckMessage(ackdata,toStreamNumber) + payload += encodeVarint(len(fullAckPayload)) + payload += fullAckPayload + signature = highlevelcrypto.sign(payload,privSigningKeyHex) + payload += encodeVarint(len(signature)) + payload += signature - for row in queryreturn: - hash, havecorrectnonce, pubkeyPayload, timeLastRequested = row + elif fromAddressVersionNumber == 1: + payload = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' #this run of nulls allows the true message receiver to identify his message + payload += '\x01' #Message version. + payload += '\x00\x00\x00\x01' + + payload += encodeVarint(fromAddressVersionNumber) + payload += encodeVarint(fromStreamNumber) - readPosition = 8 #to bypass the nonce - bitfieldBehaviors = pubkeyPayload[8:12] - readPosition += 4 #to bypass the bitfield of behaviors - addressVersion, addressVersionLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) - readPosition += addressVersionLength - streamNumber, streamNumberLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) - readPosition += streamNumberLength - nLength, nLengthLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) - readPosition += nLengthLength - n = convertStringToInt(pubkeyPayload[readPosition:readPosition+nLength]) - readPosition += nLength - eLength, eLengthLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) - readPosition += eLengthLength - e = convertStringToInt(pubkeyPayload[readPosition:readPosition+eLength]) - receiversPubkey = rsa.PublicKey(n,e) + try: + sendersN = convertIntToString(config.getint(fromaddress, 'n')) + except: + printLock.acquire() + print 'Error: Could not find', fromaddress, 'in our keys.dat file. You must have deleted it. Aborting the send.' + printLock.release() + return + payload += encodeVarint(len(sendersN)) + payload += sendersN - infile = cStringIO.StringIO(payload) - outfile = cStringIO.StringIO() - #print 'Encrypting using public key:', receiversPubkey - encrypt_bigfile(infile,outfile,receiversPubkey) + sendersE = convertIntToString(config.getint(fromaddress, 'e')) + payload += encodeVarint(len(sendersE)) + payload += sendersE - encrypted = outfile.getvalue() - infile.close() - outfile.close() + payload += '\x02' #Type 2 is simple UTF-8 message encoding. + messageToTransmit = 'Subject:' + subject + '\n' + 'Body:' + message + payload += encodeVarint(len(messageToTransmit)) + payload += messageToTransmit + + #Later, if anyone impliments clients that don't send the ack_data, then we should probably check here to make sure that the receiver will make use of this ack_data and not attach it if not. + fullAckPayload = self.generateFullAckMessage(ackdata,toStreamNumber) + payload += encodeVarint(len(fullAckPayload)) + payload += fullAckPayload + sendersPrivKey = rsa.PrivateKey(config.getint(fromaddress, 'n'),config.getint(fromaddress, 'e'),config.getint(fromaddress, 'd'),config.getint(fromaddress, 'p'),config.getint(fromaddress, 'q')) + + payload += rsa.sign(payload,sendersPrivKey,'SHA-512') + + #We have assembled the data that will be encrypted. Now let us fetch the recipient's public key out of our database and do the encryption. + + if toAddressVersionNumber == 2: + sqlLock.acquire() + sqlSubmitQueue.put('SELECT * FROM pubkeys WHERE hash=?') + sqlSubmitQueue.put((toRipe,)) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + + for row in queryreturn: + hash, havecorrectnonce, pubkeyPayload, timeLastRequested = row + + readPosition = 8 #to bypass the nonce + readPosition += 4 #to bypass the embedded time + 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 + encrypted = highlevelcrypto.encrypt(payload,"04"+pubEncryptionKeyBase256.encode('hex')) + + elif toAddressVersionNumber == 1: + sqlLock.acquire() + sqlSubmitQueue.put('SELECT * FROM pubkeys WHERE hash=?') + sqlSubmitQueue.put((toRipe,)) + queryreturn = sqlReturnQueue.get() + sqlLock.release() + + for row in queryreturn: + hash, havecorrectnonce, pubkeyPayload, timeLastRequested = row + + readPosition = 8 #to bypass the nonce + behaviorBitfield = pubkeyPayload[8:12] + readPosition += 4 #to bypass the bitfield of behaviors + addressVersion, addressVersionLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) + readPosition += addressVersionLength + streamNumber, streamNumberLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) + readPosition += streamNumberLength + nLength, nLengthLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) + readPosition += nLengthLength + n = convertStringToInt(pubkeyPayload[readPosition:readPosition+nLength]) + readPosition += nLength + eLength, eLengthLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) + readPosition += eLengthLength + e = convertStringToInt(pubkeyPayload[readPosition:readPosition+eLength]) + receiversPubkey = rsa.PublicKey(n,e) + + infile = cStringIO.StringIO(payload) + outfile = cStringIO.StringIO() + #print 'Encrypting using public key:', receiversPubkey + encrypt_bigfile(infile,outfile,receiversPubkey) + + encrypted = outfile.getvalue() + infile.close() + outfile.close() nonce = 0 trialValue = 99999999999999999999 @@ -1997,9 +2554,9 @@ class singleWorker(QThread): print 'sending inv (within sendmsg function)' payload = '\x01' + inventoryHash headerData = '\xe9\xbe\xb4\xd9' #magic bits, slighly different from Bitcoin's magic bits. - headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' - headerData = headerData + pack('>L',len(payload)) #payload length. Note that we add an extra 8 for the nonce. - headerData = headerData + hashlib.sha512(payload).digest()[:4] + headerData += 'inv\x00\x00\x00\x00\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] broadcastToSendDataQueues((toStreamNumber, 'send', headerData + payload)) #Update the status of the message in the 'sent' table to have a 'sent' status @@ -2023,6 +2580,7 @@ class singleWorker(QThread): payload += encodeVarint(addressVersionNumber) payload += encodeVarint(streamNumber) payload += ripe + print 'making request for pubkey with ripe:', ripe.encode('hex') nonce = 0 trialValue = 99999999999999999999 #print 'trial value', trialValue @@ -2084,43 +2642,206 @@ class addressGenerator(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) - def setup(self,streamNumber,label): + def setup(self,addressVersionNumber,streamNumber,label="(no label)",numberOfAddressesToMake=1,deterministicPassphrase="",eighteenByteRipe=False): + self.addressVersionNumber = addressVersionNumber self.streamNumber = streamNumber self.label = label + self.numberOfAddressesToMake = numberOfAddressesToMake + self.deterministicPassphrase = deterministicPassphrase + self.eighteenByteRipe = eighteenByteRipe def run(self): - statusbar = 'Generating new ' + str(config.getint('bitmessagesettings', 'bitstrength')) + ' bit RSA key. This takes a minute on average. If you want to generate multiple addresses now, you can; they will queue.' - self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) - (pubkey, privkey) = rsa.newkeys(config.getint('bitmessagesettings', 'bitstrength')) - print privkey['n'] - print privkey['e'] - print privkey['d'] - print privkey['p'] - print privkey['q'] + if self.addressVersionNumber == 2: - sha = hashlib.new('sha512') - #sha.update(str(pubkey.n)+str(pubkey.e)) - sha.update(convertIntToString(pubkey.n)+convertIntToString(pubkey.e)) - ripe = hashlib.new('ripemd160') - ripe.update(sha.digest()) - address = encodeAddress(1,self.streamNumber,ripe.digest()) + if self.deterministicPassphrase == "": + statusbar = 'Generating one new address' + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) + #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 + while True: + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 + potentialPrivSigningKey = OpenSSL.rand(32) + potentialPrivEncryptionKey = OpenSSL.rand(32) + potentialPubSigningKey = self.pointMult(potentialPrivSigningKey) + potentialPubEncryptionKey = self.pointMult(potentialPrivEncryptionKey) + #print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') + #print 'potentialPubEncryptionKey', potentialPubEncryptionKey.encode('hex') - self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Finished generating address. Writing to keys.dat') - config.add_section(address) - config.set(address,'label',self.label) - config.set(address,'enabled','true') - config.set(address,'decoy','false') - config.set(address,'n',str(privkey['n'])) - config.set(address,'e',str(privkey['e'])) - config.set(address,'d',str(privkey['d'])) - config.set(address,'p',str(privkey['p'])) - config.set(address,'q',str(privkey['q'])) - with open(appdata + 'keys.dat', 'wb') as configfile: - config.write(configfile) + 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 self.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.' + if ripe.digest()[:2] == '\x00\x00': + address = encodeAddress(2,self.streamNumber,ripe.digest()[2:]) + elif ripe.digest()[:1] == '\x00': + address = encodeAddress(2,self.streamNumber,ripe.digest()[1:]) + #self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Finished generating address. Writing to keys.dat') - self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Done generating address') - self.emit(SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.label,address,str(self.streamNumber)) + #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 + + config.add_section(address) + print 'self.label', self.label + config.set(address,'label',self.label) + config.set(address,'enabled','true') + config.set(address,'decoy','false') + config.set(address,'privSigningKey',privSigningKeyWIF) + config.set(address,'privEncryptionKey',privEncryptionKeyWIF) + with open(appdata + 'keys.dat', 'wb') as configfile: + config.write(configfile) + + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Done generating address') + self.emit(SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.label,address,str(self.streamNumber)) + reloadMyAddressHashes() + + else: #There is something in the deterministicPassphrase variable thus we are going to do this deterministically. + statusbar = 'Generating '+str(self.numberOfAddressesToMake) + ' new addresses.' + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) + signingKeyNonce = 0 + encryptionKeyNonce = 1 + for i in range(self.numberOfAddressesToMake): + #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 + while True: + numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 + potentialPrivSigningKey = hashlib.sha512(self.deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] + potentialPrivEncryptionKey = hashlib.sha512(self.deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] + potentialPubSigningKey = self.pointMult(potentialPrivSigningKey) + potentialPubEncryptionKey = self.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 self.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.' + if ripe.digest()[:2] == '\x00\x00': + address = encodeAddress(2,self.streamNumber,ripe.digest()[2:]) + elif ripe.digest()[:1] == '\x00': + address = encodeAddress(2,self.streamNumber,ripe.digest()[1:]) + #self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Finished generating address. Writing to keys.dat') + + #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: + config.add_section(address) + print 'self.label', self.label + config.set(address,'label',self.label) + config.set(address,'enabled','true') + config.set(address,'decoy','false') + config.set(address,'privSigningKey',privSigningKeyWIF) + config.set(address,'privEncryptionKey',privEncryptionKeyWIF) + with open(appdata + 'keys.dat', 'wb') as configfile: + config.write(configfile) + + self.emit(SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.label,address,str(self.streamNumber)) + except: + print address,'already exists. Not adding it again.' + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Done generating address') + reloadMyAddressHashes() + + elif self.addressVersionNumber == 1: + statusbar = 'Generating new ' + str(config.getint('bitmessagesettings', 'bitstrength')) + ' bit RSA key. This takes a minute on average. If you want to generate multiple addresses now, you can; they will queue.' + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),statusbar) + (pubkey, privkey) = rsa.newkeys(config.getint('bitmessagesettings', 'bitstrength')) + print privkey['n'] + print privkey['e'] + print privkey['d'] + print privkey['p'] + print privkey['q'] + + sha = hashlib.new('sha512') + #sha.update(str(pubkey.n)+str(pubkey.e)) + sha.update(convertIntToString(pubkey.n)+convertIntToString(pubkey.e)) + ripe = hashlib.new('ripemd160') + ripe.update(sha.digest()) + address = encodeAddress(1,self.streamNumber,ripe.digest()) + + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Finished generating address. Writing to keys.dat') + config.add_section(address) + config.set(address,'label',self.label) + config.set(address,'enabled','true') + config.set(address,'decoy','false') + config.set(address,'n',str(privkey['n'])) + config.set(address,'e',str(privkey['e'])) + config.set(address,'d',str(privkey['d'])) + config.set(address,'p',str(privkey['p'])) + config.set(address,'q',str(privkey['q'])) + with open(appdata + 'keys.dat', 'wb') as configfile: + config.write(configfile) + + self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),'Done generating address') + self.emit(SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.label,address,str(self.streamNumber)) + reloadMyAddressHashes() + + #Does an EC point multiplication which basically turns a private key into a public key + def pointMult(self,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 class iconGlossaryDialog(QtGui.QDialog): def __init__(self,parent): @@ -2148,6 +2869,14 @@ class aboutDialog(QtGui.QDialog): self.parent = parent self.ui.labelVersion.setText('version ' + softwareVersion) +class regenerateAddressesDialog(QtGui.QDialog): + def __init__(self,parent): + QtGui.QWidget.__init__(self, parent) + self.ui = Ui_regenerateAddressesDialog() + self.ui.setupUi(self) + self.parent = parent + QtGui.QWidget.resize(self,QtGui.QWidget.sizeHint(self)) + class settingsDialog(QtGui.QDialog): def __init__(self,parent): QtGui.QWidget.__init__(self, parent) @@ -2166,6 +2895,8 @@ class settingsDialog(QtGui.QDialog): self.ui.labelSettingsNote.setText('Options have been disabled because they either arn\'t applicable or because they haven\'t yet been implimented for your operating system.') elif 'linux' in sys.platform: self.ui.checkBoxStartOnLogon.setDisabled(True) + self.ui.checkBoxMinimizeToTray.setDisabled(True) + self.ui.checkBoxStartInTray.setDisabled(True) self.ui.labelSettingsNote.setText('Options have been disabled because they either arn\'t applicable or because they haven\'t yet been implimented for your operating system.') #On the Network settings tab: self.ui.lineEditTCPPort.setText(str(config.get('bitmessagesettings', 'port'))) @@ -2231,8 +2962,8 @@ class NewSubscriptionDialog(QtGui.QDialog): class NewAddressDialog(QtGui.QDialog): def __init__(self, parent): QtGui.QWidget.__init__(self, parent) - self.ui = Ui_NewAddressDialog() #Jonathan changed this line - self.ui.setupUi(self) #Jonathan left this line alone + self.ui = Ui_NewAddressDialog() + self.ui.setupUi(self) self.parent = parent row = 1 while self.parent.ui.tableWidgetYourIdentities.item(row-1,1): @@ -2240,16 +2971,30 @@ class NewAddressDialog(QtGui.QDialog): #print self.parent.ui.tableWidgetYourIdentities.item(row-1,1).text() self.ui.comboBoxExisting.addItem(self.parent.ui.tableWidgetYourIdentities.item(row-1,1).text()) row += 1 - #QtGui.QWidget.resize(self,QtGui.QWidget.sizeHint(self)) - + self.ui.groupBoxDeterministic.setHidden(True) + QtGui.QWidget.resize(self,QtGui.QWidget.sizeHint(self)) class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) - self.ui = Ui_MainWindow() #Jonathan changed this line - self.ui.setupUi(self) #Jonathan left this line alone + self.ui = Ui_MainWindow() + self.ui.setupUi(self) + #Ask the user if we may delete their old version 1 addresses if they have any. + configSections = config.sections() + for addressInKeysFile in configSections: + if addressInKeysFile <> 'bitmessagesettings': + status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) + if addressVersionNumber == 1: + displayMsg = "One of your addresses, "+addressInKeysFile+", is an old version 1 address. Version 1 addresses are no longer supported. May we delete it now?" + reply = QtGui.QMessageBox.question(self, 'Message',displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) + if reply == QtGui.QMessageBox.Yes: + config.remove_section(addressInKeysFile) + with open(appdata + 'keys.dat', 'wb') as configfile: + config.write(configfile) + + #Configure Bitmessage to start on startup (or remove the configuration) based on the setting in the keys.dat file if 'win32' in sys.platform or 'win64' in sys.platform: #Auto-startup for Windows RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" @@ -2278,6 +3023,8 @@ class MyForm(QtGui.QMainWindow): #FILE MENU and other buttons QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.close) QtCore.QObject.connect(self.ui.actionManageKeys, QtCore.SIGNAL("triggered()"), self.click_actionManageKeys) + QtCore.QObject.connect(self.ui.actionRegenerateDeterministicAddresses, QtCore.SIGNAL("triggered()"), self.click_actionRegenerateDeterministicAddresses) + QtCore.QObject.connect(self.ui.actionManageKeys, QtCore.SIGNAL("triggered()"), self.click_actionManageKeys) QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL("clicked()"), self.click_NewAddressDialog) QtCore.QObject.connect(self.ui.comboBoxSendFrom, QtCore.SIGNAL("activated(int)"),self.redrawLabelFrom) QtCore.QObject.connect(self.ui.pushButtonAddAddressBook, QtCore.SIGNAL("clicked()"), self.click_pushButtonAddAddressBook) @@ -2384,7 +3131,7 @@ class MyForm(QtGui.QMainWindow): self.sqlLookup = sqlThread() self.sqlLookup.start() - self.reloadMyAddressHashes() + reloadMyAddressHashes() self.reloadBroadcastSendersForWhichImWatching() @@ -2541,7 +3288,7 @@ class MyForm(QtGui.QMainWindow): queryreturn = sqlReturnQueue.get() for row in queryreturn: ackdata, = row - print 'Watching for ackdata', repr(ackdata) + print 'Watching for ackdata', ackdata.encode('hex') ackdataForWhichImWatching[ackdata] = 0 QtCore.QObject.connect(self.ui.tableWidgetYourIdentities, QtCore.SIGNAL("itemChanged(QTableWidgetItem *)"), self.tableWidgetYourIdentitiesItemChanged) @@ -2592,6 +3339,21 @@ class MyForm(QtGui.QMainWindow): self.openKeysFile() else: pass + + def click_actionRegenerateDeterministicAddresses(self): + self.regenerateAddressesDialogInstance = regenerateAddressesDialog(self) + if self.regenerateAddressesDialogInstance.exec_(): + if self.regenerateAddressesDialogInstance.ui.lineEditPassphrase.text() == "": + QMessageBox.about(self, "bad passphrase", "You must type your passphrase. If you don\'t have one then this is not the form for you.") + else: + streamNumberForAddress = int(self.regenerateAddressesDialogInstance.ui.lineEditStreamNumber.text()) + addressVersionNumber = int(self.regenerateAddressesDialogInstance.ui.lineEditAddressVersionNumber.text()) + self.addressGenerator = addressGenerator() + self.addressGenerator.setup(addressVersionNumber,streamNumberForAddress,"unused address",self.regenerateAddressesDialogInstance.ui.spinBoxNumberOfAddressesToMake.value(),self.regenerateAddressesDialogInstance.ui.lineEditPassphrase.text().toUtf8(),self.regenerateAddressesDialogInstance.ui.checkBoxEighteenByteRipe.isChecked()) + QtCore.QObject.connect(self.addressGenerator, SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) + QtCore.QObject.connect(self.addressGenerator, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar) + self.addressGenerator.start() + self.ui.tabWidget.setCurrentIndex(3) def openKeysFile(self): if 'linux' in sys.platform: @@ -2760,7 +3522,7 @@ class MyForm(QtGui.QMainWindow): for row in queryreturn: toLabel, = row self.ui.tableWidgetSent.item(i,0).setText(unicode(toLabel,'utf-8')) - + def click_pushButtonSend(self): self.statusBar().showMessage('') toAddresses = str(self.ui.lineEditTo.text()) @@ -2774,7 +3536,9 @@ class MyForm(QtGui.QMainWindow): if toAddress <> '': status,addressVersionNumber,streamNumber,ripe = decodeAddress(toAddress) if status <> 'success': - print 'Status bar!', 'Error: Could not decode', toAddress, ':', status + printLock.acquire() + print 'Status bar:', 'Error: Could not decode', toAddress, ':', status + printLock.release() if status == 'missingbm': self.statusBar().showMessage('Error: Bitmessage addresses start with BM- Please check ' + toAddress) if status == 'checksumfailed': @@ -2784,17 +3548,22 @@ class MyForm(QtGui.QMainWindow): if status == 'versiontoohigh': self.statusBar().showMessage('Error: The address version in '+ toAddress+ ' is too high. Either you need to upgrade your Bitmessage software or your acquaintance is being clever.') elif fromAddress == '': - print 'Status bar!', 'Error: you must specify a From address.' self.statusBar().showMessage('Error: You must specify a From address. If you don''t have one, go to the ''Your Identities'' tab.') else: toAddress = addBMIfNotPresent(toAddress) + if addressVersionNumber > 2 or addressVersionNumber == 0: + QMessageBox.about(self, "Address version number", "Concerning the address "+toAddress+", Bitmessage cannot understand address version numbers of "+str(addressVersionNumber)+". Perhaps upgrade Bitmessage to the latest version.") + continue + if streamNumber > 1 or streamNumber == 0: + QMessageBox.about(self, "Stream number", "Concerning the address "+toAddress+", Bitmessage cannot handle stream numbers of "+str(streamNumber)+". Perhaps upgrade Bitmessage to the latest version.") + continue self.statusBar().showMessage('') - if connectionsCount[streamNumber] == 0: - self.statusBar().showMessage('Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.') - ackdata = '' - for i in range(4): #This will make 32 bytes of random data. - random.seed() - ackdata += pack('>Q',random.randrange(1, 18446744073709551615)) + try: + if connectionsCount[streamNumber] == 0: + self.statusBar().showMessage('Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.') + except: + self.statusBar().showMessage('Warning: The address uses a stream number currently not supported by this Bitmessage version. Perhaps upgrade.') + ackdata = OpenSSL.rand(32) sqlLock.acquire() t = ('',toAddress,ripe,fromAddress,subject,message,ackdata,int(time.time()),'findingpubkey',1,1,'sent') sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?)''') @@ -2852,15 +3621,11 @@ class MyForm(QtGui.QMainWindow): self.statusBar().showMessage('Your \'To\' field is empty.') else: #User selected 'Broadcast' if fromAddress == '': - print 'Status bar!', 'Error: you must specify a From address.' self.statusBar().showMessage('Error: You must specify a From address. If you don\'t have one, go to the \'Your Identities\' tab.') else: self.statusBar().showMessage('') - ackdata = '' #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. - for i in range(4): #This will make 32 bytes of random data. - random.seed() - ackdata += pack('>Q',random.randrange(1, 18446744073709551615)) + ackdata = OpenSSL.rand(32) toAddress = '[Broadcast subscribers]' ripe = '' sqlLock.acquire() @@ -2906,7 +3671,6 @@ class MyForm(QtGui.QMainWindow): self.ui.tabWidget.setCurrentIndex(2) - def click_pushButtonLoadFromAddressBook(self): self.ui.tabWidget.setCurrentIndex(5) for i in range(4): @@ -3225,31 +3989,36 @@ class MyForm(QtGui.QMainWindow): def click_NewAddressDialog(self): - print 'click_buttondialog' self.dialog = NewAddressDialog(self) - # For Modal dialogs if self.dialog.exec_(): - self.dialog.ui.buttonBox.enabled = False - if self.dialog.ui.radioButtonMostAvailable.isChecked(): - #self.generateAndStoreAnAddress(1) - streamNumberForAddress = 1 - + #self.dialog.ui.buttonBox.enabled = False + if self.dialog.ui.radioButtonRandomAddress.isChecked(): + if self.dialog.ui.radioButtonMostAvailable.isChecked(): + streamNumberForAddress = 1 + else: + #User selected 'Use the same stream as an existing address.' + streamNumberForAddress = addressStream(self.dialog.ui.comboBoxExisting.currentText()) + self.addressGenerator = addressGenerator() + self.addressGenerator.setup(2,streamNumberForAddress,str(self.dialog.ui.newaddresslabel.text().toUtf8()),1,"",self.dialog.ui.checkBoxEighteenByteRipe.isChecked()) + QtCore.QObject.connect(self.addressGenerator, SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) + QtCore.QObject.connect(self.addressGenerator, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar) + self.addressGenerator.start() else: - #User selected 'Use the same stream as an existing address.' - streamNumberForAddress = addressStream(self.dialog.ui.comboBoxExisting.currentText()) - - self.addressGenerator = addressGenerator() - self.addressGenerator.setup(streamNumberForAddress,str(self.dialog.ui.newaddresslabel.text().toUtf8())) - - QtCore.QObject.connect(self.addressGenerator, SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) - QtCore.QObject.connect(self.addressGenerator, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar) - - - self.addressGenerator.start() + if self.dialog.ui.lineEditPassphrase.text() != self.dialog.ui.lineEditPassphraseAgain.text(): + QMessageBox.about(self, "Passphrase mismatch", "The passphrase you entered twice doesn\'t match. Try again.") + elif self.dialog.ui.lineEditPassphrase.text() == "": + QMessageBox.about(self, "Choose a passphrase", "You really do need a passphrase.") + else: + streamNumberForAddress = 1 #this will eventually have to be replaced by logic to determine the most available stream number. + self.addressGenerator = addressGenerator() + self.addressGenerator.setup(2,streamNumberForAddress,"unused address",self.dialog.ui.spinBoxNumberOfAddressesToMake.value(),self.dialog.ui.lineEditPassphrase.text().toUtf8(),self.dialog.ui.checkBoxEighteenByteRipe.isChecked()) + QtCore.QObject.connect(self.addressGenerator, SIGNAL("writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) + QtCore.QObject.connect(self.addressGenerator, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar) + self.addressGenerator.start() else: - print 'rejected' + print 'new address dialog box rejected' def closeEvent(self, event): broadcastToSendDataQueues((0, 'shutdown', 'all')) @@ -3290,11 +4059,16 @@ class MyForm(QtGui.QMainWindow): currentInboxRow = self.ui.tableWidgetInbox.currentRow() toAddressAtCurrentInboxRow = str(self.ui.tableWidgetInbox.item(currentInboxRow,0).data(Qt.UserRole).toPyObject()) fromAddressAtCurrentInboxRow = str(self.ui.tableWidgetInbox.item(currentInboxRow,1).data(Qt.UserRole).toPyObject()) - if not config.get(toAddressAtCurrentInboxRow,'enabled'): - self.statusBar().showMessage('Error: The address from which you are trying to send is disabled. Enable it from the \'Your Identities\' tab first.') - return + + + if toAddressAtCurrentInboxRow == '[Broadcast subscribers]': + self.ui.labelFrom.setText('') + else: + if not config.get(toAddressAtCurrentInboxRow,'enabled'): + self.statusBar().showMessage('Error: The address from which you are trying to send is disabled. Enable it from the \'Your Identities\' tab first.') + return + self.ui.labelFrom.setText(toAddressAtCurrentInboxRow) self.ui.lineEditTo.setText(str(fromAddressAtCurrentInboxRow)) - self.ui.labelFrom.setText(toAddressAtCurrentInboxRow) self.ui.comboBoxSendFrom.setCurrentIndex(0) #self.ui.comboBoxSendFrom.setEditText(str(self.ui.tableWidgetInbox.item(currentInboxRow,0).text)) self.ui.textEditMessage.setText('\n\n------------------------------------------------------\n'+self.ui.tableWidgetInbox.item(currentInboxRow,2).data(Qt.UserRole).toPyObject()) @@ -3419,7 +4193,7 @@ class MyForm(QtGui.QMainWindow): self.ui.tableWidgetYourIdentities.item(currentRow,0).setTextColor(QtGui.QColor(0,0,0)) self.ui.tableWidgetYourIdentities.item(currentRow,1).setTextColor(QtGui.QColor(0,0,0)) self.ui.tableWidgetYourIdentities.item(currentRow,2).setTextColor(QtGui.QColor(0,0,0)) - self.reloadMyAddressHashes() + reloadMyAddressHashes() def on_action_YourIdentitiesDisable(self): currentRow = self.ui.tableWidgetYourIdentities.currentRow() addressAtCurrentRow = self.ui.tableWidgetYourIdentities.item(currentRow,1).text() @@ -3429,7 +4203,7 @@ class MyForm(QtGui.QMainWindow): self.ui.tableWidgetYourIdentities.item(currentRow,2).setTextColor(QtGui.QColor(128,128,128)) with open(appdata + 'keys.dat', 'wb') as configfile: config.write(configfile) - self.reloadMyAddressHashes() + reloadMyAddressHashes() def on_action_YourIdentitiesClipboard(self): currentRow = self.ui.tableWidgetYourIdentities.currentRow() addressAtCurrentRow = self.ui.tableWidgetYourIdentities.item(currentRow,1).text() @@ -3501,29 +4275,13 @@ class MyForm(QtGui.QMainWindow): newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled ) self.ui.tableWidgetYourIdentities.setItem(0, 2, newItem) self.rerenderComboBoxSendFrom() - self.reloadMyAddressHashes() def updateStatusBar(self,data): - print 'Status bar!', data + printLock.acquire() + print 'Status bar:', data + printLock.release() self.statusBar().showMessage(data) - def reloadMyAddressHashes(self): - print 'reloading my address hashes' - myAddressHashes.clear() - #myPrivateKeys.clear() - configSections = config.sections() - for addressInKeysFile in configSections: - if addressInKeysFile <> 'bitmessagesettings': - isEnabled = config.getboolean(addressInKeysFile, 'enabled') - if isEnabled: - status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) - n = config.getint(addressInKeysFile, 'n') - e = config.getint(addressInKeysFile, 'e') - d = config.getint(addressInKeysFile, 'd') - p = config.getint(addressInKeysFile, 'p') - q = config.getint(addressInKeysFile, 'q') - myAddressHashes[hash] = rsa.PrivateKey(n,e,d,p,q) - def reloadBroadcastSendersForWhichImWatching(self): broadcastSendersForWhichImWatching.clear() sqlLock.acquire() @@ -3543,7 +4301,8 @@ class myTableWidgetItem(QTableWidgetItem): sendDataQueues = [] #each sendData thread puts its queue in this list. -myAddressHashes = {} +myRSAAddressHashes = {} +myECAddressHashes = {} #myPrivateKeys = {} inventory = {} #of objects (like msg payloads and pubkey payloads) Does not include protocol headers (the first 24 bytes of each packet). workerQueue = Queue.Queue() @@ -3565,6 +4324,10 @@ neededPubkeys = {} averageProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work. payloadLengthExtraBytes = 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. +if useVeryEasyProofOfWorkForTesting: + averageProofOfWorkNonceTrialsPerByte = averageProofOfWorkNonceTrialsPerByte / 10 + payloadLengthExtraBytes = payloadLengthExtraBytes / 10 + if __name__ == "__main__": #sqlite_version = sqlite3.sqlite_version_info # Check the Major version, the first element in the array @@ -3572,22 +4335,25 @@ 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 sys.exit() - APPNAME = "PyBitmessage" - from os import path, environ - if sys.platform == 'darwin': - if "HOME" in environ: - appdata = path.join(os.environ["HOME"], "Library/Application support/", APPNAME) + '/' + if not storeConfigFilesInSameDirectoryAsProgram: + APPNAME = "PyBitmessage" + from os import path, environ + if sys.platform == 'darwin': + if "HOME" in environ: + appdata = 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() + + elif 'win32' in sys.platform or 'win64' in sys.platform: + appdata = path.join(environ['APPDATA'], APPNAME) + '\\' else: - print 'Could not find home folder, please report this message and your OS X version to the BitMessage Github.' - sys.exit() + appdata = path.expanduser(path.join("~", "." + APPNAME + "/")) - elif 'win32' in sys.platform or 'win64' in sys.platform: - appdata = path.join(environ['APPDATA'], APPNAME) + '\\' + if not os.path.exists(appdata): + os.makedirs(appdata) else: - appdata = path.expanduser(path.join("~", "." + APPNAME + "/")) - - if not os.path.exists(appdata): - os.makedirs(appdata) + appdata = "" config = ConfigParser.SafeConfigParser() config.read(appdata + 'keys.dat') @@ -3603,7 +4369,10 @@ if __name__ == "__main__": config.set('bitmessagesettings','timeformat','%%a, %%d %%b %%Y %%I:%%M %%p') config.set('bitmessagesettings','blackwhitelist','black') config.set('bitmessagesettings','startonlogon','false') - config.set('bitmessagesettings','minimizetotray','true') + if 'linux' in sys.platform: + config.set('bitmessagesettings','minimizetotray','false')#This isn't implimented yet and when True on Ubuntu causes Bitmessage to disappear while running when minimized. + else: + config.set('bitmessagesettings','minimizetotray','true') config.set('bitmessagesettings','showtraynotifications','true') config.set('bitmessagesettings','startintray','false') @@ -3654,7 +4423,7 @@ if __name__ == "__main__": knownNodes[1][item[4][0]] = (8444,int(time.time())) except: print 'bootstrap8444.bitmessage.org DNS bootstrapping failed.' - + app = QtGui.QApplication(sys.argv) app.setStyleSheet("QStatusBar::item { border: 0px solid black }") myapp = MyForm() diff --git a/bitmessageui.py b/bitmessageui.py index f4513e11..9e8c0d69 100644 --- a/bitmessageui.py +++ b/bitmessageui.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'bitmessageui.ui' # -# Created: Tue Dec 18 14:32:02 2012 +# Created: Thu Jan 24 15:29:31 2013 # by: PyQt4 UI code generator 4.9.4 # # WARNING! All changes made in this file will be lost! @@ -403,7 +403,10 @@ class Ui_MainWindow(object): self.actionAbout.setObjectName(_fromUtf8("actionAbout")) self.actionSettings = QtGui.QAction(MainWindow) self.actionSettings.setObjectName(_fromUtf8("actionSettings")) + self.actionRegenerateDeterministicAddresses = QtGui.QAction(MainWindow) + self.actionRegenerateDeterministicAddresses.setObjectName(_fromUtf8("actionRegenerateDeterministicAddresses")) self.menuFile.addAction(self.actionManageKeys) + self.menuFile.addAction(self.actionRegenerateDeterministicAddresses) self.menuFile.addAction(self.actionExit) self.menuSettings.addAction(self.actionSettings) self.menuHelp.addAction(self.actionHelp) @@ -506,5 +509,6 @@ class Ui_MainWindow(object): self.actionHelp.setText(QtGui.QApplication.translate("MainWindow", "Help", None, QtGui.QApplication.UnicodeUTF8)) self.actionAbout.setText(QtGui.QApplication.translate("MainWindow", "About", None, QtGui.QApplication.UnicodeUTF8)) self.actionSettings.setText(QtGui.QApplication.translate("MainWindow", "Settings", None, QtGui.QApplication.UnicodeUTF8)) + self.actionRegenerateDeterministicAddresses.setText(QtGui.QApplication.translate("MainWindow", "Regenerate deterministic addresses", None, QtGui.QApplication.UnicodeUTF8)) import bitmessage_icons_rc diff --git a/bitmessageui.ui b/bitmessageui.ui index f644535b..19e94529 100644 --- a/bitmessageui.ui +++ b/bitmessageui.ui @@ -933,6 +933,7 @@ p, li { white-space: pre-wrap; } File + @@ -996,6 +997,11 @@ p, li { white-space: pre-wrap; } Settings + + + Regenerate deterministic addresses + + diff --git a/highlevelcrypto.py b/highlevelcrypto.py new file mode 100644 index 00000000..22f44ed3 --- /dev/null +++ b/highlevelcrypto.py @@ -0,0 +1,33 @@ +import pyelliptic +from pyelliptic import arithmetic as a +def makeCryptor(privkey): + privkey_bin = '\x02\xca\x00 '+a.changebase(privkey,16,256,minlen=32) + pubkey = a.changebase(a.privtopub(privkey),16,256,minlen=65)[1:] + pubkey_bin = '\x02\xca\x00 '+pubkey[:32]+'\x00 '+pubkey[32:] + cryptor = pyelliptic.ECC(curve='secp256k1',privkey=privkey_bin,pubkey=pubkey_bin) + return cryptor +def hexToPubkey(pubkey): + pubkey_raw = a.changebase(pubkey[2:],16,256,minlen=64) + pubkey_bin = '\x02\xca\x00 '+pubkey_raw[:32]+'\x00 '+pubkey_raw[32:] + return pubkey_bin +def makePubCryptor(pubkey): + pubkey_bin = hexToPubkey(pubkey) + return pyelliptic.ECC(curve='secp256k1',pubkey=pubkey_bin) +# Converts hex private key into hex public key +def privToPub(privkey): + return a.privtopub(privkey) +# Encrypts message with hex public key +def encrypt(msg,hexPubkey): + return pyelliptic.ECC(curve='secp256k1').encrypt(msg,hexToPubkey(hexPubkey)) +# Decrypts message with hex private key +def decrypt(msg,hexPrivkey): + return makeCryptor(hexPrivkey).decrypt(msg) +# Decrypts message with an existing pyelliptic.ECC.ECC object +def decryptFast(msg,cryptor): + return cryptor.decrypt(msg) +# Signs with hex private key +def sign(msg,hexPrivkey): + return makeCryptor(hexPrivkey).sign(msg) +# Verifies with hex public key +def verify(msg,sig,hexPubkey): + return makePubCryptor(hexPubkey).verify(sig,msg) diff --git a/newaddressdialog.py b/newaddressdialog.py index 053c83fa..e7c1ad71 100644 --- a/newaddressdialog.py +++ b/newaddressdialog.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'newaddressdialog.ui' # -# Created: Wed Dec 19 15:55:07 2012 +# Created: Fri Jan 25 13:05:18 2013 # by: PyQt4 UI code generator 4.9.4 # # WARNING! All changes made in this file will be lost! @@ -17,57 +17,168 @@ except AttributeError: class Ui_NewAddressDialog(object): def setupUi(self, NewAddressDialog): NewAddressDialog.setObjectName(_fromUtf8("NewAddressDialog")) - NewAddressDialog.resize(383, 258) - self.buttonBox = QtGui.QDialogButtonBox(NewAddressDialog) - self.buttonBox.setGeometry(QtCore.QRect(160, 220, 201, 32)) - self.buttonBox.setOrientation(QtCore.Qt.Horizontal) - self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) - self.buttonBox.setObjectName(_fromUtf8("buttonBox")) + NewAddressDialog.resize(723, 704) + self.formLayout = QtGui.QFormLayout(NewAddressDialog) + self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout.setObjectName(_fromUtf8("formLayout")) self.label = QtGui.QLabel(NewAddressDialog) - self.label.setGeometry(QtCore.QRect(10, 0, 361, 41)) self.label.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft) self.label.setWordWrap(True) self.label.setObjectName(_fromUtf8("label")) - self.label_2 = QtGui.QLabel(NewAddressDialog) - self.label_2.setGeometry(QtCore.QRect(20, 50, 301, 20)) + self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.label) + self.label_5 = QtGui.QLabel(NewAddressDialog) + self.label_5.setWordWrap(True) + self.label_5.setObjectName(_fromUtf8("label_5")) + self.formLayout.setWidget(2, QtGui.QFormLayout.SpanningRole, self.label_5) + self.line = QtGui.QFrame(NewAddressDialog) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.line.sizePolicy().hasHeightForWidth()) + self.line.setSizePolicy(sizePolicy) + self.line.setMinimumSize(QtCore.QSize(100, 2)) + self.line.setFrameShape(QtGui.QFrame.HLine) + self.line.setFrameShadow(QtGui.QFrame.Sunken) + self.line.setObjectName(_fromUtf8("line")) + self.formLayout.setWidget(4, QtGui.QFormLayout.SpanningRole, self.line) + self.radioButtonRandomAddress = QtGui.QRadioButton(NewAddressDialog) + self.radioButtonRandomAddress.setChecked(True) + self.radioButtonRandomAddress.setObjectName(_fromUtf8("radioButtonRandomAddress")) + self.buttonGroup = QtGui.QButtonGroup(NewAddressDialog) + self.buttonGroup.setObjectName(_fromUtf8("buttonGroup")) + self.buttonGroup.addButton(self.radioButtonRandomAddress) + self.formLayout.setWidget(5, QtGui.QFormLayout.SpanningRole, self.radioButtonRandomAddress) + self.radioButtonDeterministicAddress = QtGui.QRadioButton(NewAddressDialog) + self.radioButtonDeterministicAddress.setObjectName(_fromUtf8("radioButtonDeterministicAddress")) + self.buttonGroup.addButton(self.radioButtonDeterministicAddress) + self.formLayout.setWidget(6, QtGui.QFormLayout.LabelRole, self.radioButtonDeterministicAddress) + self.checkBoxEighteenByteRipe = QtGui.QCheckBox(NewAddressDialog) + self.checkBoxEighteenByteRipe.setObjectName(_fromUtf8("checkBoxEighteenByteRipe")) + self.formLayout.setWidget(9, QtGui.QFormLayout.SpanningRole, self.checkBoxEighteenByteRipe) + self.groupBoxDeterministic = QtGui.QGroupBox(NewAddressDialog) + self.groupBoxDeterministic.setObjectName(_fromUtf8("groupBoxDeterministic")) + self.gridLayout = QtGui.QGridLayout(self.groupBoxDeterministic) + self.gridLayout.setObjectName(_fromUtf8("gridLayout")) + self.label_9 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_9.setObjectName(_fromUtf8("label_9")) + self.gridLayout.addWidget(self.label_9, 6, 0, 1, 1) + self.label_8 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_8.setObjectName(_fromUtf8("label_8")) + self.gridLayout.addWidget(self.label_8, 5, 0, 1, 3) + self.spinBoxNumberOfAddressesToMake = QtGui.QSpinBox(self.groupBoxDeterministic) + self.spinBoxNumberOfAddressesToMake.setMinimum(1) + self.spinBoxNumberOfAddressesToMake.setProperty("value", 8) + self.spinBoxNumberOfAddressesToMake.setObjectName(_fromUtf8("spinBoxNumberOfAddressesToMake")) + self.gridLayout.addWidget(self.spinBoxNumberOfAddressesToMake, 4, 3, 1, 1) + self.label_6 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_6.setObjectName(_fromUtf8("label_6")) + self.gridLayout.addWidget(self.label_6, 0, 0, 1, 1) + self.label_11 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_11.setObjectName(_fromUtf8("label_11")) + self.gridLayout.addWidget(self.label_11, 4, 0, 1, 3) + spacerItem = QtGui.QSpacerItem(73, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout.addItem(spacerItem, 6, 1, 1, 1) + self.label_10 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_10.setObjectName(_fromUtf8("label_10")) + self.gridLayout.addWidget(self.label_10, 6, 2, 1, 1) + spacerItem1 = QtGui.QSpacerItem(42, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout.addItem(spacerItem1, 6, 3, 1, 1) + self.label_7 = QtGui.QLabel(self.groupBoxDeterministic) + self.label_7.setObjectName(_fromUtf8("label_7")) + self.gridLayout.addWidget(self.label_7, 2, 0, 1, 1) + self.lineEditPassphraseAgain = QtGui.QLineEdit(self.groupBoxDeterministic) + self.lineEditPassphraseAgain.setEchoMode(QtGui.QLineEdit.Password) + self.lineEditPassphraseAgain.setObjectName(_fromUtf8("lineEditPassphraseAgain")) + self.gridLayout.addWidget(self.lineEditPassphraseAgain, 3, 0, 1, 4) + self.lineEditPassphrase = QtGui.QLineEdit(self.groupBoxDeterministic) + self.lineEditPassphrase.setInputMethodHints(QtCore.Qt.ImhHiddenText|QtCore.Qt.ImhNoAutoUppercase|QtCore.Qt.ImhNoPredictiveText) + self.lineEditPassphrase.setEchoMode(QtGui.QLineEdit.Password) + self.lineEditPassphrase.setObjectName(_fromUtf8("lineEditPassphrase")) + self.gridLayout.addWidget(self.lineEditPassphrase, 1, 0, 1, 4) + self.formLayout.setWidget(8, QtGui.QFormLayout.LabelRole, self.groupBoxDeterministic) + self.groupBox = QtGui.QGroupBox(NewAddressDialog) + self.groupBox.setObjectName(_fromUtf8("groupBox")) + self.gridLayout_2 = QtGui.QGridLayout(self.groupBox) + self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) + self.label_2 = QtGui.QLabel(self.groupBox) self.label_2.setObjectName(_fromUtf8("label_2")) - self.newaddresslabel = QtGui.QLineEdit(NewAddressDialog) - self.newaddresslabel.setGeometry(QtCore.QRect(20, 70, 351, 20)) + self.gridLayout_2.addWidget(self.label_2, 0, 0, 1, 2) + self.newaddresslabel = QtGui.QLineEdit(self.groupBox) self.newaddresslabel.setObjectName(_fromUtf8("newaddresslabel")) - self.radioButtonMostAvailable = QtGui.QRadioButton(NewAddressDialog) - self.radioButtonMostAvailable.setGeometry(QtCore.QRect(20, 110, 401, 16)) + self.gridLayout_2.addWidget(self.newaddresslabel, 1, 0, 1, 2) + self.radioButtonMostAvailable = QtGui.QRadioButton(self.groupBox) self.radioButtonMostAvailable.setChecked(True) self.radioButtonMostAvailable.setObjectName(_fromUtf8("radioButtonMostAvailable")) - self.radioButtonExisting = QtGui.QRadioButton(NewAddressDialog) - self.radioButtonExisting.setGeometry(QtCore.QRect(20, 150, 351, 18)) - self.radioButtonExisting.setChecked(False) - self.radioButtonExisting.setObjectName(_fromUtf8("radioButtonExisting")) - self.label_3 = QtGui.QLabel(NewAddressDialog) - self.label_3.setGeometry(QtCore.QRect(35, 127, 351, 20)) + self.gridLayout_2.addWidget(self.radioButtonMostAvailable, 2, 0, 1, 2) + self.label_3 = QtGui.QLabel(self.groupBox) self.label_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.label_3.setObjectName(_fromUtf8("label_3")) - self.label_4 = QtGui.QLabel(NewAddressDialog) - self.label_4.setGeometry(QtCore.QRect(37, 167, 351, 21)) + self.gridLayout_2.addWidget(self.label_3, 3, 1, 1, 1) + self.radioButtonExisting = QtGui.QRadioButton(self.groupBox) + self.radioButtonExisting.setChecked(False) + self.radioButtonExisting.setObjectName(_fromUtf8("radioButtonExisting")) + self.gridLayout_2.addWidget(self.radioButtonExisting, 4, 0, 1, 2) + self.label_4 = QtGui.QLabel(self.groupBox) self.label_4.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.label_4.setObjectName(_fromUtf8("label_4")) - self.comboBoxExisting = QtGui.QComboBox(NewAddressDialog) + self.gridLayout_2.addWidget(self.label_4, 5, 1, 1, 1) + spacerItem2 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout_2.addItem(spacerItem2, 6, 0, 1, 1) + self.comboBoxExisting = QtGui.QComboBox(self.groupBox) self.comboBoxExisting.setEnabled(False) - self.comboBoxExisting.setGeometry(QtCore.QRect(40, 190, 331, 22)) self.comboBoxExisting.setEditable(True) self.comboBoxExisting.setObjectName(_fromUtf8("comboBoxExisting")) + self.gridLayout_2.addWidget(self.comboBoxExisting, 6, 1, 1, 1) + self.formLayout.setWidget(7, QtGui.QFormLayout.LabelRole, self.groupBox) + self.buttonBox = QtGui.QDialogButtonBox(NewAddressDialog) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.buttonBox.sizePolicy().hasHeightForWidth()) + self.buttonBox.setSizePolicy(sizePolicy) + self.buttonBox.setMinimumSize(QtCore.QSize(160, 0)) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) + self.buttonBox.setObjectName(_fromUtf8("buttonBox")) + self.formLayout.setWidget(10, QtGui.QFormLayout.SpanningRole, self.buttonBox) self.retranslateUi(NewAddressDialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), NewAddressDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), NewAddressDialog.reject) QtCore.QObject.connect(self.radioButtonExisting, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.comboBoxExisting.setEnabled) + QtCore.QObject.connect(self.radioButtonDeterministicAddress, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.groupBoxDeterministic.setShown) + QtCore.QObject.connect(self.radioButtonRandomAddress, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.groupBox.setShown) QtCore.QMetaObject.connectSlotsByName(NewAddressDialog) + NewAddressDialog.setTabOrder(self.radioButtonRandomAddress, self.radioButtonDeterministicAddress) + NewAddressDialog.setTabOrder(self.radioButtonDeterministicAddress, self.newaddresslabel) + NewAddressDialog.setTabOrder(self.newaddresslabel, self.radioButtonMostAvailable) + NewAddressDialog.setTabOrder(self.radioButtonMostAvailable, self.radioButtonExisting) + NewAddressDialog.setTabOrder(self.radioButtonExisting, self.comboBoxExisting) + NewAddressDialog.setTabOrder(self.comboBoxExisting, self.lineEditPassphrase) + NewAddressDialog.setTabOrder(self.lineEditPassphrase, self.lineEditPassphraseAgain) + NewAddressDialog.setTabOrder(self.lineEditPassphraseAgain, self.spinBoxNumberOfAddressesToMake) + NewAddressDialog.setTabOrder(self.spinBoxNumberOfAddressesToMake, self.checkBoxEighteenByteRipe) + NewAddressDialog.setTabOrder(self.checkBoxEighteenByteRipe, self.buttonBox) def retranslateUi(self, NewAddressDialog): NewAddressDialog.setWindowTitle(QtGui.QApplication.translate("NewAddressDialog", "Create new Address", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("NewAddressDialog", "Here you may generate as many addresses as you like. Indeed, creating and abandoning addresses is encouraged.", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setText(QtGui.QApplication.translate("NewAddressDialog", "Here you may generate as many addresses as you like. Indeed, creating and abandoning addresses is encouraged. You may generate addresses by using either random numbers or by using a passphrase. If you use a passphrase, the address is called a \"deterministic\" address.\n" +"The \'Random Number\' option is selected by default but deterministic addresses have several pros and cons:", None, QtGui.QApplication.UnicodeUTF8)) + self.label_5.setText(QtGui.QApplication.translate("NewAddressDialog", "

Pros:
You can recreate your addresses on any computer from memory.
You need-not worry about backing up your keys.dat file as long as you can remember your passphrase.
Cons:
You must remember (or write down) your passphrase if you expect to be able to recreate your keys if they are lost.
You must remember the address version number and the stream number along with your passphrase.
If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you.

", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonRandomAddress.setText(QtGui.QApplication.translate("NewAddressDialog", "Use a random number generator to make an address", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonDeterministicAddress.setText(QtGui.QApplication.translate("NewAddressDialog", "Use a passpharase to make addresses", None, QtGui.QApplication.UnicodeUTF8)) + self.checkBoxEighteenByteRipe.setText(QtGui.QApplication.translate("NewAddressDialog", "Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBoxDeterministic.setTitle(QtGui.QApplication.translate("NewAddressDialog", "Make deterministic addresses", None, QtGui.QApplication.UnicodeUTF8)) + self.label_9.setText(QtGui.QApplication.translate("NewAddressDialog", "Address version number: 2", None, QtGui.QApplication.UnicodeUTF8)) + self.label_8.setText(QtGui.QApplication.translate("NewAddressDialog", "In addition to your passphrase, you must remember these numbers:", None, QtGui.QApplication.UnicodeUTF8)) + self.label_6.setText(QtGui.QApplication.translate("NewAddressDialog", "Passphrase", None, QtGui.QApplication.UnicodeUTF8)) + self.label_11.setText(QtGui.QApplication.translate("NewAddressDialog", "Number of addresses to make based on your passphrase:", None, QtGui.QApplication.UnicodeUTF8)) + self.label_10.setText(QtGui.QApplication.translate("NewAddressDialog", "Stream number: 1", None, QtGui.QApplication.UnicodeUTF8)) + self.label_7.setText(QtGui.QApplication.translate("NewAddressDialog", "Retype passphrase", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox.setTitle(QtGui.QApplication.translate("NewAddressDialog", "Randomly generate address", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("NewAddressDialog", "Label (not shown to anyone except you)", None, QtGui.QApplication.UnicodeUTF8)) self.radioButtonMostAvailable.setText(QtGui.QApplication.translate("NewAddressDialog", "Use the most available stream", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButtonExisting.setText(QtGui.QApplication.translate("NewAddressDialog", "Use the same stream as an existing address", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("NewAddressDialog", " (best if this is the first of many addresses you will create)", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonExisting.setText(QtGui.QApplication.translate("NewAddressDialog", "Use the same stream as an existing address", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setText(QtGui.QApplication.translate("NewAddressDialog", "(saves you some bandwidth and processing power)", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/newaddressdialog.ui b/newaddressdialog.ui index c53340ec..7f9e13af 100644 --- a/newaddressdialog.ui +++ b/newaddressdialog.ui @@ -6,152 +6,321 @@ 0 0 - 383 - 258 + 723 + 704 Create new Address - - - - 160 - 220 - 201 - 32 - + + + QFormLayout::AllNonFixedFieldsGrow - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 0 - 361 - 41 - - - - Here you may generate as many addresses as you like. Indeed, creating and abandoning addresses is encouraged. - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - true - - - - - - 20 - 50 - 301 - 20 - - - - Label (not shown to anyone except you) - - - - - - 20 - 70 - 351 - 20 - - - - - - - 20 - 110 - 401 - 16 - - - - Use the most available stream - - - true - - - - - - 20 - 150 - 351 - 18 - - - - Use the same stream as an existing address - - - false - - - - - - 35 - 127 - 351 - 20 - - - - (best if this is the first of many addresses you will create) - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - 37 - 167 - 351 - 21 - - - - (saves you some bandwidth and processing power) - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - false - - - - 40 - 190 - 331 - 22 - - - - true - - + + + + Here you may generate as many addresses as you like. Indeed, creating and abandoning addresses is encouraged. You may generate addresses by using either random numbers or by using a passphrase. If you use a passphrase, the address is called a "deterministic" address. +The 'Random Number' option is selected by default but deterministic addresses have several pros and cons: + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + true + + + + + + + <html><head/><body><p><span style=" font-weight:600;">Pros:<br/></span>You can recreate your addresses on any computer from memory. <br/>You need-not worry about backing up your keys.dat file as long as you can remember your passphrase. <br/><span style=" font-weight:600;">Cons:<br/></span>You must remember (or write down) your passphrase if you expect to be able to recreate your keys if they are lost. <br/>You must remember the address version number and the stream number along with your passphrase. <br/>If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you.</p></body></html> + + + true + + + + + + + + 0 + 0 + + + + + 100 + 2 + + + + Qt::Horizontal + + + + + + + Use a random number generator to make an address + + + true + + + buttonGroup + + + + + + + Use a passpharase to make addresses + + + buttonGroup + + + + + + + Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter + + + + + + + Make deterministic addresses + + + + + + Address version number: 2 + + + + + + + In addition to your passphrase, you must remember these numbers: + + + + + + + 1 + + + 8 + + + + + + + Passphrase + + + + + + + Number of addresses to make based on your passphrase: + + + + + + + Qt::Horizontal + + + + 73 + 20 + + + + + + + + Stream number: 1 + + + + + + + Qt::Horizontal + + + + 42 + 20 + + + + + + + + Retype passphrase + + + + + + + QLineEdit::Password + + + + + + + Qt::ImhHiddenText|Qt::ImhNoAutoUppercase|Qt::ImhNoPredictiveText + + + QLineEdit::Password + + + + + + + + + + Randomly generate address + + + + + + Label (not shown to anyone except you) + + + + + + + + + + Use the most available stream + + + true + + + + + + + (best if this is the first of many addresses you will create) + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + + + + Use the same stream as an existing address + + + false + + + + + + + (saves you some bandwidth and processing power) + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + + + + Qt::Horizontal + + + + 13 + 20 + + + + + + + + false + + + true + + + + + comboBoxExisting + label_3 + radioButtonExisting + newaddresslabel + label_4 + radioButtonMostAvailable + label_2 + horizontalSpacer_3 + + + + + + + 0 + 0 + + + + + 160 + 0 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + radioButtonRandomAddress + radioButtonDeterministicAddress + newaddresslabel + radioButtonMostAvailable + radioButtonExisting + comboBoxExisting + lineEditPassphrase + lineEditPassphraseAgain + spinBoxNumberOfAddressesToMake + checkBoxEighteenByteRipe + buttonBox + @@ -161,8 +330,8 @@ accept() - 360 - 234 + 580 + 644 157 @@ -177,8 +346,8 @@ reject() - 360 - 240 + 580 + 650 286 @@ -193,14 +362,49 @@ setEnabled(bool) - 30 - 158 + 60 + 349 - 99 - 199 + 148 + 394 + + + + + radioButtonDeterministicAddress + toggled(bool) + groupBoxDeterministic + setShown(bool) + + + 92 + 213 + + + 277 + 601 + + + + + radioButtonRandomAddress + toggled(bool) + groupBox + setShown(bool) + + + 72 + 189 + + + 68 + 268 + + + diff --git a/pyelliptic/LICENSE b/pyelliptic/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/pyelliptic/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/pyelliptic/README.md b/pyelliptic/README.md new file mode 100644 index 00000000..587b1445 --- /dev/null +++ b/pyelliptic/README.md @@ -0,0 +1,67 @@ +# PyElliptic + +PyElliptic is a high level wrapper for the cryptographic library : OpenSSL. +Under the GNU General Public License + +Python3 compatible. For GNU/Linux and Windows. +Require OpenSSL + +## Features + +### Asymmetric cryptography using Elliptic Curve Cryptography (ECC) + +* Key agreement : ECDH +* Digital signatures : ECDSA +* Hybrid encryption : ECIES (like RSA) + +### Symmetric cryptography + +* AES-128 (CBC, OFB, CFB) +* AES-256 (CBC, OFB, CFB) +* Blowfish (CFB and CBC) +* RC4 + +### Other + +* CSPRNG +* HMAC (using SHA512) +* PBKDF2 (SHA256 and SHA512) + +## Example + +```python +#!/usr/bin/python + +import pyelliptic + +# Symmetric encryption +iv = pyelliptic.Cipher.gen_IV('aes-256-cfb') +ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb') + +ciphertext = ctx.update('test1') +ciphertext += ctx.update('test2') +ciphertext += ctx.final() + +ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb') +print ctx2.ciphering(ciphertext) + +# Asymmetric encryption +alice = pyelliptic.ECC() # default curve: sect283r1 +bob = pyelliptic.ECC(curve='sect571r1') + +ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey()) +print bob.decrypt(ciphertext) + +signature = bob.sign("Hello Alice") +# alice's job : +print pyelliptic.ECC(pubkey=bob.get_pubkey()).verify(signature, "Hello Alice") + +# ERROR !!! +try: + key = alice.get_ecdh_key(bob.get_pubkey()) +except: print("For ECDH key agreement, the keys must be defined on the same curve !") + +alice = pyelliptic.ECC(curve='sect571r1') +print alice.get_ecdh_key(bob.get_pubkey()).encode('hex') +print bob.get_ecdh_key(alice.get_pubkey()).encode('hex') +``` diff --git a/pyelliptic/__init__.py b/pyelliptic/__init__.py new file mode 100644 index 00000000..761d08af --- /dev/null +++ b/pyelliptic/__init__.py @@ -0,0 +1,19 @@ +# Copyright (C) 2010 +# Author: Yann GUIBET +# Contact: + +__version__ = '1.3' + +__all__ = [ + 'OpenSSL', + 'ECC', + 'Cipher', + 'hmac_sha256', + 'hmac_sha512', + 'pbkdf2' +] + +from .openssl import OpenSSL +from .ecc import ECC +from .cipher import Cipher +from .hash import hmac_sha256, hmac_sha512, pbkdf2 diff --git a/pyelliptic/arithmetic.py b/pyelliptic/arithmetic.py new file mode 100644 index 00000000..f54359ba --- /dev/null +++ b/pyelliptic/arithmetic.py @@ -0,0 +1,103 @@ +import hashlib, re + +P = 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1 +A = 0 +Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240 +Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424 +G = (Gx,Gy) + +def inv(a,n): + lm, hm = 1,0 + low, high = a%n,n + while low > 1: + r = high/low + nm, new = hm-lm*r, high-low*r + lm, low, hm, high = nm, new, lm, low + return lm % n + +def get_code_string(base): + if base == 2: return '01' + elif base == 10: return '0123456789' + elif base == 16: return "0123456789abcdef" + elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + elif base == 256: return ''.join([chr(x) for x in range(256)]) + else: raise ValueError("Invalid base!") + +def encode(val,base,minlen=0): + code_string = get_code_string(base) + result = "" + while val > 0: + result = code_string[val % base] + result + val /= base + if len(result) < minlen: + result = code_string[0]*(minlen-len(result))+result + return result + +def decode(string,base): + code_string = get_code_string(base) + result = 0 + if base == 16: string = string.lower() + while len(string) > 0: + result *= base + result += code_string.find(string[0]) + string = string[1:] + return result + +def changebase(string,frm,to,minlen=0): + return encode(decode(string,frm),to,minlen) + +def base10_add(a,b): + if a == None: return b[0],b[1] + if b == None: return a[0],a[1] + if a[0] == b[0]: + if a[1] == b[1]: return base10_double(a[0],a[1]) + else: return None + m = ((b[1]-a[1]) * inv(b[0]-a[0],P)) % P + x = (m*m-a[0]-b[0]) % P + y = (m*(a[0]-x)-a[1]) % P + return (x,y) + +def base10_double(a): + if a == None: return None + m = ((3*a[0]*a[0]+A)*inv(2*a[1],P)) % P + x = (m*m-2*a[0]) % P + y = (m*(a[0]-x)-a[1]) % P + return (x,y) + +def base10_multiply(a,n): + if n == 0: return G + if n == 1: return a + if (n%2) == 0: return base10_double(base10_multiply(a,n/2)) + if (n%2) == 1: return base10_add(base10_double(base10_multiply(a,n/2)),a) + +def hex_to_point(h): return (decode(h[2:34],16),decode(h[34:],16)) + +def point_to_hex(p): return '04'+encode(p[0],16,64)+encode(p[1],16,64) + +def multiply(privkey,pubkey): + return point_to_hex(base10_multiply(hex_to_point(pubkey),decode(privkey,16))) + +def privtopub(privkey): + return point_to_hex(base10_multiply(G,decode(privkey,16))) + +def add(p1,p2): + if (len(p1)==32): + return encode(decode(p1,16) + decode(p2,16) % P,16,32) + else: + return point_to_hex(base10_add(hex_to_point(p1),hex_to_point(p2))) + +def hash160(string): + intermed = hashlib.sha256(string).digest() + return hashlib.new('ripemd160').update(intermed).digest() + +def dbl_sha256(string): + return hashlib.sha256(hashlib.sha256(string).digest()).digest() + +def bin_to_b58check(inp): + inp_fmtd = '\x00' + inp + leadingzbytes = len(re.match('^\x00*',inp_fmtd).group(0)) + checksum = dbl_sha256(inp_fmtd)[:4] + return '1' * leadingzbytes + changebase(inp_fmtd+checksum,256,58) + +def pubkey_to_address(pubkey): + return bin_to_b58check(hash_160(changebase(pubkey,16,256))) diff --git a/pyelliptic/cipher.py b/pyelliptic/cipher.py new file mode 100644 index 00000000..fb8d0d46 --- /dev/null +++ b/pyelliptic/cipher.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2011 Yann GUIBET +# See LICENSE for details. + +from pyelliptic.openssl import OpenSSL + + +class Cipher: + """ + Symmetric encryption + + import pyelliptic + iv = pyelliptic.Cipher.gen_IV('aes-256-cfb') + ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb') + ciphertext = ctx.update('test1') + ciphertext += ctx.update('test2') + ciphertext += ctx.final() + + ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb') + print ctx2.ciphering(ciphertext) + """ + def __init__(self, key, iv, do, ciphername='aes-256-cbc'): + """ + do == 1 => Encrypt; do == 0 => Decrypt + """ + self.cipher = OpenSSL.get_cipher(ciphername) + self.ctx = OpenSSL.EVP_CIPHER_CTX_new() + if do == 1 or do == 0: + k = OpenSSL.malloc(key, len(key)) + IV = OpenSSL.malloc(iv, len(iv)) + OpenSSL.EVP_CipherInit_ex( + self.ctx, self.cipher.get_pointer(), 0, k, IV, do) + else: + raise Exception("RTFM ...") + + @staticmethod + def get_all_cipher(): + """ + static method, returns all ciphers available + """ + return OpenSSL.cipher_algo.keys() + + @staticmethod + def get_blocksize(ciphername): + cipher = OpenSSL.get_cipher(ciphername) + return cipher.get_blocksize() + + @staticmethod + def gen_IV(ciphername): + cipher = OpenSSL.get_cipher(ciphername) + return OpenSSL.rand(cipher.get_blocksize()) + + def update(self, input): + i = OpenSSL.c_int(0) + buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize()) + inp = OpenSSL.malloc(input, len(input)) + if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer), + OpenSSL.byref(i), inp, len(input)) == 0: + raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...") + return buffer.raw[0:i.value] + + def final(self): + i = OpenSSL.c_int(0) + buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize()) + if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer), + OpenSSL.byref(i))) == 0: + raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...") + return buffer.raw[0:i.value] + + def ciphering(self, input): + """ + Do update and final in one method + """ + buff = self.update(input) + return buff + self.final() + + def __del__(self): + OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx) + OpenSSL.EVP_CIPHER_CTX_free(self.ctx) diff --git a/pyelliptic/ecc.py b/pyelliptic/ecc.py new file mode 100644 index 00000000..2d1559b2 --- /dev/null +++ b/pyelliptic/ecc.py @@ -0,0 +1,460 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2011 Yann GUIBET +# See LICENSE for details. + +from hashlib import sha512 +from pyelliptic.openssl import OpenSSL +from pyelliptic.cipher import Cipher +from pyelliptic.hash import hmac_sha256 +from struct import pack, unpack + + +class ECC: + """ + Asymmetric encryption with Elliptic Curve Cryptography (ECC) + ECDH, ECDSA and ECIES + + import pyelliptic + + alice = pyelliptic.ECC() # default curve: sect283r1 + bob = pyelliptic.ECC(curve='sect571r1') + + ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey()) + print bob.decrypt(ciphertext) + + signature = bob.sign("Hello Alice") + # alice's job : + print pyelliptic.ECC( + pubkey=bob.get_pubkey()).verify(signature, "Hello Alice") + + # ERROR !!! + try: + key = alice.get_ecdh_key(bob.get_pubkey()) + except: print("For ECDH key agreement,\ + the keys must be defined on the same curve !") + + alice = pyelliptic.ECC(curve='sect571r1') + print alice.get_ecdh_key(bob.get_pubkey()).encode('hex') + print bob.get_ecdh_key(alice.get_pubkey()).encode('hex') + + """ + def __init__(self, pubkey=None, privkey=None, pubkey_x=None, + pubkey_y=None, raw_privkey=None, curve='sect283r1'): + """ + For a normal and High level use, specifie pubkey, + privkey (if you need) and the curve + """ + if type(curve) == str: + self.curve = OpenSSL.get_curve(curve) + else: + self.curve = curve + + if pubkey_x is not None and pubkey_y is not None: + self._set_keys(pubkey_x, pubkey_y, raw_privkey) + elif pubkey is not None: + curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) + if privkey is not None: + curve2, raw_privkey, i = ECC._decode_privkey(privkey) + if curve != curve2: + raise Exception("Bad ECC keys ...") + self.curve = curve + self._set_keys(pubkey_x, pubkey_y, raw_privkey) + else: + self.privkey, self.pubkey_x, self.pubkey_y = self._generate() + + def _set_keys(self, pubkey_x, pubkey_y, privkey): + if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: + self.pubkey_x = None + self.pubkey_y = None + self.privkey = None + raise Exception("Bad ECC keys ...") + else: + self.pubkey_x = pubkey_x + self.pubkey_y = pubkey_y + self.privkey = privkey + + @staticmethod + def get_curves(): + """ + static method, returns the list of all the curves available + """ + return OpenSSL.curves.keys() + + def get_curve(self): + return OpenSSL.get_curve_by_id(self.curve) + + def get_curve_id(self): + return self.curve + + def get_pubkey(self): + """ + High level function which returns : + curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY + """ + return b''.join((pack('!H', self.curve), + pack('!H', len(self.pubkey_x)), + self.pubkey_x, + pack('!H', len(self.pubkey_y)), + self.pubkey_y + )) + + def get_privkey(self): + """ + High level function which returns + curve(2) + len_of_privkey(2) + privkey + """ + return b''.join((pack('!H', self.curve), + pack('!H', len(self.privkey)), + self.privkey + )) + + @staticmethod + def _decode_pubkey(pubkey): + i = 0 + curve = unpack('!H', pubkey[i:i + 2])[0] + i += 2 + tmplen = unpack('!H', pubkey[i:i + 2])[0] + i += 2 + pubkey_x = pubkey[i:i + tmplen] + i += tmplen + tmplen = unpack('!H', pubkey[i:i + 2])[0] + i += 2 + pubkey_y = pubkey[i:i + tmplen] + i += tmplen + return curve, pubkey_x, pubkey_y, i + + @staticmethod + def _decode_privkey(privkey): + i = 0 + curve = unpack('!H', privkey[i:i + 2])[0] + i += 2 + tmplen = unpack('!H', privkey[i:i + 2])[0] + i += 2 + privkey = privkey[i:i + tmplen] + i += tmplen + return curve, privkey, i + + def _generate(self): + try: + pub_key_x = OpenSSL.BN_new() + pub_key_y = OpenSSL.BN_new() + + key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) + if key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + if (OpenSSL.EC_KEY_generate_key(key)) == 0: + raise Exception("[OpenSSL] EC_KEY_generate_key FAIL ...") + if (OpenSSL.EC_KEY_check_key(key)) == 0: + raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") + priv_key = OpenSSL.EC_KEY_get0_private_key(key) + + group = OpenSSL.EC_KEY_get0_group(key) + pub_key = OpenSSL.EC_KEY_get0_public_key(key) + + if (OpenSSL.EC_POINT_get_affine_coordinates_GFp(group, pub_key, + pub_key_x, + pub_key_y, 0 + )) == 0: + raise Exception( + "[OpenSSL] EC_POINT_get_affine_coordinates_GFp FAIL ...") + + privkey = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(priv_key)) + pubkeyx = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_x)) + pubkeyy = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_y)) + OpenSSL.BN_bn2bin(priv_key, privkey) + privkey = privkey.raw + OpenSSL.BN_bn2bin(pub_key_x, pubkeyx) + pubkeyx = pubkeyx.raw + OpenSSL.BN_bn2bin(pub_key_y, pubkeyy) + pubkeyy = pubkeyy.raw + self.raw_check_key(privkey, pubkeyx, pubkeyy) + + return privkey, pubkeyx, pubkeyy + + finally: + OpenSSL.EC_KEY_free(key) + OpenSSL.BN_free(pub_key_x) + OpenSSL.BN_free(pub_key_y) + + def get_ecdh_key(self, pubkey): + """ + High level function. Compute public key with the local private key + and returns a 512bits shared key + """ + curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) + if curve != self.curve: + raise Exception("ECC keys must be from the same curve !") + return sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() + + def raw_get_ecdh_key(self, pubkey_x, pubkey_y): + try: + ecdh_keybuffer = OpenSSL.malloc(0, 32) + + other_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) + if other_key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + + other_pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0) + other_pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0) + + other_group = OpenSSL.EC_KEY_get0_group(other_key) + other_pub_key = OpenSSL.EC_POINT_new(other_group) + + if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(other_group, + other_pub_key, + other_pub_key_x, + other_pub_key_y, + 0)) == 0: + raise Exception( + "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") + if (OpenSSL.EC_KEY_set_public_key(other_key, other_pub_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") + if (OpenSSL.EC_KEY_check_key(other_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") + + own_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) + if own_key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + own_priv_key = OpenSSL.BN_bin2bn( + self.privkey, len(self.privkey), 0) + + if (OpenSSL.EC_KEY_set_private_key(own_key, own_priv_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...") + + OpenSSL.ECDH_set_method(own_key, OpenSSL.ECDH_OpenSSL()) + ecdh_keylen = OpenSSL.ECDH_compute_key( + ecdh_keybuffer, 32, other_pub_key, own_key, 0) + + if ecdh_keylen != 32: + raise Exception("[OpenSSL] ECDH keylen FAIL ...") + + return ecdh_keybuffer.raw + + finally: + OpenSSL.EC_KEY_free(other_key) + OpenSSL.BN_free(other_pub_key_x) + OpenSSL.BN_free(other_pub_key_y) + OpenSSL.EC_POINT_free(other_pub_key) + OpenSSL.EC_KEY_free(own_key) + OpenSSL.BN_free(own_priv_key) + + def check_key(self, privkey, pubkey): + """ + Check the public key and the private key. + The private key is optional (replace by None) + """ + curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) + if privkey is None: + raw_privkey = None + curve2 = curve + else: + curve2, raw_privkey, i = ECC._decode_privkey(privkey) + if curve != curve2: + raise Exception("Bad public and private key") + return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) + + def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): + if curve is None: + curve = self.curve + elif type(curve) == str: + curve = OpenSSL.get_curve(curve) + else: + curve = curve + try: + key = OpenSSL.EC_KEY_new_by_curve_name(curve) + if key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + if privkey is not None: + priv_key = OpenSSL.BN_bin2bn(privkey, len(privkey), 0) + pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0) + pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0) + + if privkey is not None: + if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: + raise Exception( + "[OpenSSL] EC_KEY_set_private_key FAIL ...") + + group = OpenSSL.EC_KEY_get0_group(key) + pub_key = OpenSSL.EC_POINT_new(group) + + if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, + pub_key_x, + pub_key_y, + 0)) == 0: + raise Exception( + "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") + if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") + if (OpenSSL.EC_KEY_check_key(key)) == 0: + raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") + return 0 + + finally: + OpenSSL.EC_KEY_free(key) + OpenSSL.BN_free(pub_key_x) + OpenSSL.BN_free(pub_key_y) + OpenSSL.EC_POINT_free(pub_key) + if privkey is not None: + OpenSSL.BN_free(priv_key) + + def sign(self, inputb): + """ + Sign the input with ECDSA method and returns the signature + """ + try: + size = len(inputb) + buff = OpenSSL.malloc(inputb, size) + digest = OpenSSL.malloc(0, 64) + md_ctx = OpenSSL.EVP_MD_CTX_create() + dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) + siglen = OpenSSL.pointer(OpenSSL.c_int(0)) + sig = OpenSSL.malloc(0, 151) + + key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) + if key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + + priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey), 0) + pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) + pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) + + if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...") + + group = OpenSSL.EC_KEY_get0_group(key) + pub_key = OpenSSL.EC_POINT_new(group) + + if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, + pub_key_x, + pub_key_y, + 0)) == 0: + raise Exception( + "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") + if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") + if (OpenSSL.EC_KEY_check_key(key)) == 0: + raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") + + OpenSSL.EVP_MD_CTX_init(md_ctx) + OpenSSL.EVP_DigestInit(md_ctx, OpenSSL.EVP_ecdsa()) + + if (OpenSSL.EVP_DigestUpdate(md_ctx, buff, size)) == 0: + raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...") + OpenSSL.EVP_DigestFinal(md_ctx, digest, dgst_len) + OpenSSL.ECDSA_sign(0, digest, dgst_len.contents, sig, siglen, key) + if (OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, sig, + siglen.contents, key)) != 1: + raise Exception("[OpenSSL] ECDSA_verify FAIL ...") + + return sig.raw[:siglen.contents.value] + + finally: + OpenSSL.EC_KEY_free(key) + OpenSSL.BN_free(pub_key_x) + OpenSSL.BN_free(pub_key_y) + OpenSSL.BN_free(priv_key) + OpenSSL.EC_POINT_free(pub_key) + OpenSSL.EVP_MD_CTX_destroy(md_ctx) + + def verify(self, sig, inputb): + """ + Verify the signature with the input and the local public key. + Returns a boolean + """ + try: + bsig = OpenSSL.malloc(sig, len(sig)) + binputb = OpenSSL.malloc(inputb, len(inputb)) + digest = OpenSSL.malloc(0, 64) + dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) + md_ctx = OpenSSL.EVP_MD_CTX_create() + + key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) + + if key == 0: + raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") + + pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) + pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) + group = OpenSSL.EC_KEY_get0_group(key) + pub_key = OpenSSL.EC_POINT_new(group) + + if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, + pub_key_x, + pub_key_y, + 0)) == 0: + raise Exception( + "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") + if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: + raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") + if (OpenSSL.EC_KEY_check_key(key)) == 0: + raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") + + OpenSSL.EVP_MD_CTX_init(md_ctx) + OpenSSL.EVP_DigestInit(md_ctx, OpenSSL.EVP_ecdsa()) + if (OpenSSL.EVP_DigestUpdate(md_ctx, binputb, len(inputb))) == 0: + raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...") + + OpenSSL.EVP_DigestFinal(md_ctx, digest, dgst_len) + ret = OpenSSL.ECDSA_verify( + 0, digest, dgst_len.contents, bsig, len(sig), key) + + if ret == -1: + return False # Fail to Check + else: + if ret == 0: + return False # Bad signature ! + else: + return True # Good + return False + + finally: + OpenSSL.EC_KEY_free(key) + OpenSSL.BN_free(pub_key_x) + OpenSSL.BN_free(pub_key_y) + OpenSSL.EC_POINT_free(pub_key) + OpenSSL.EVP_MD_CTX_destroy(md_ctx) + + @staticmethod + def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'): + """ + Encrypt data with ECIES method using the public key of the recipient. + """ + curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) + return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve, + ephemcurve=ephemcurve, ciphername=ciphername) + + @staticmethod + def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1', + ephemcurve=None, ciphername='aes-256-cbc'): + if ephemcurve is None: + ephemcurve = curve + ephem = ECC(curve=ephemcurve) + key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() + key_e, key_m = key[:32], key[32:] + pubkey = ephem.get_pubkey() + iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize()) + ctx = Cipher(key_e, iv, 1, ciphername) + ciphertext = ctx.ciphering(data) + mac = hmac_sha256(key_m, ciphertext) + return iv + pubkey + ciphertext + mac + + def decrypt(self, data, ciphername='aes-256-cbc'): + """ + Decrypt data with ECIES method using the local private key + """ + blocksize = OpenSSL.get_cipher(ciphername).get_blocksize() + iv = data[:blocksize] + i = blocksize + curve, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:]) + i += i2 + ciphertext = data[i:len(data)-32] + i += len(ciphertext) + mac = data[i:] + key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() + key_e, key_m = key[:32], key[32:] + if hmac_sha256(key_m, ciphertext) != mac: + raise RuntimeError("Fail to verify data") + ctx = Cipher(key_e, iv, 0, ciphername) + return ctx.ciphering(ciphertext) diff --git a/pyelliptic/hash.py b/pyelliptic/hash.py new file mode 100644 index 00000000..d8ade000 --- /dev/null +++ b/pyelliptic/hash.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2011 Yann GUIBET +# See LICENSE for details. + +from pyelliptic.openssl import OpenSSL + + +def hmac_sha256(k, m): + """ + Compute the key and the message with HMAC SHA5256 + """ + key = OpenSSL.malloc(k, len(k)) + d = OpenSSL.malloc(m, len(m)) + md = OpenSSL.malloc(0, 32) + i = OpenSSL.pointer(OpenSSL.c_int(0)) + OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i) + return md.raw + + +def hmac_sha512(k, m): + """ + Compute the key and the message with HMAC SHA512 + """ + key = OpenSSL.malloc(k, len(k)) + d = OpenSSL.malloc(m, len(m)) + md = OpenSSL.malloc(0, 64) + i = OpenSSL.pointer(OpenSSL.c_int(0)) + OpenSSL.HMAC(OpenSSL.EVP_sha512(), key, len(k), d, len(m), md, i) + return md.raw + + +def pbkdf2(password, salt=None, i=10000, keylen=64): + if salt is None: + salt = OpenSSL.rand(8) + p_password = OpenSSL.malloc(password, len(password)) + p_salt = OpenSSL.malloc(salt, len(salt)) + output = OpenSSL.malloc(0, keylen) + OpenSSL.PKCS5_PBKDF2_HMAC(p_password, len(password), p_salt, + len(p_salt), i, OpenSSL.EVP_sha256(), + keylen, output) + return salt, output.raw diff --git a/pyelliptic/openssl.py b/pyelliptic/openssl.py new file mode 100644 index 00000000..3dc0ee24 --- /dev/null +++ b/pyelliptic/openssl.py @@ -0,0 +1,429 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2011 Yann GUIBET +# See LICENSE for details. +# +# Software slightly changed by Jonathan Warren + +import sys +import ctypes + +OpenSSL = None + + +class CipherName: + def __init__(self, name, pointer, blocksize): + self._name = name + self._pointer = pointer + self._blocksize = blocksize + + def __str__(self): + return "Cipher : " + self._name + " | Blocksize : " + str(self._blocksize) + " | Fonction pointer : " + str(self._pointer) + + def get_pointer(self): + return self._pointer() + + def get_name(self): + return self._name + + def get_blocksize(self): + return self._blocksize + + +class _OpenSSL: + """ + Wrapper for OpenSSL using ctypes + """ + def __init__(self, library): + """ + Build the wrapper + """ + self._lib = ctypes.CDLL(library) + + self.pointer = ctypes.pointer + self.c_int = ctypes.c_int + self.byref = ctypes.byref + self.create_string_buffer = ctypes.create_string_buffer + + self.BN_new = self._lib.BN_new + self.BN_new.restype = ctypes.c_void_p + self.BN_new.argtypes = [] + + self.BN_free = self._lib.BN_free + self.BN_free.restype = None + self.BN_free.argtypes = [ctypes.c_void_p] + + self.BN_num_bits = self._lib.BN_num_bits + self.BN_num_bits.restype = ctypes.c_int + self.BN_num_bits.argtypes = [ctypes.c_void_p] + + self.BN_bn2bin = self._lib.BN_bn2bin + self.BN_bn2bin.restype = ctypes.c_int + self.BN_bn2bin.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self.BN_bin2bn = self._lib.BN_bin2bn + self.BN_bin2bn.restype = ctypes.c_void_p + self.BN_bin2bn.argtypes = [ctypes.c_void_p, ctypes.c_int, + ctypes.c_void_p] + + self.EC_KEY_free = self._lib.EC_KEY_free + self.EC_KEY_free.restype = None + self.EC_KEY_free.argtypes = [ctypes.c_void_p] + + self.EC_KEY_new_by_curve_name = self._lib.EC_KEY_new_by_curve_name + self.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p + self.EC_KEY_new_by_curve_name.argtypes = [ctypes.c_int] + + self.EC_KEY_generate_key = self._lib.EC_KEY_generate_key + self.EC_KEY_generate_key.restype = ctypes.c_int + self.EC_KEY_generate_key.argtypes = [ctypes.c_void_p] + + self.EC_KEY_check_key = self._lib.EC_KEY_check_key + self.EC_KEY_check_key.restype = ctypes.c_int + self.EC_KEY_check_key.argtypes = [ctypes.c_void_p] + + self.EC_KEY_get0_private_key = self._lib.EC_KEY_get0_private_key + self.EC_KEY_get0_private_key.restype = ctypes.c_void_p + self.EC_KEY_get0_private_key.argtypes = [ctypes.c_void_p] + + self.EC_KEY_get0_public_key = self._lib.EC_KEY_get0_public_key + self.EC_KEY_get0_public_key.restype = ctypes.c_void_p + self.EC_KEY_get0_public_key.argtypes = [ctypes.c_void_p] + + self.EC_KEY_get0_group = self._lib.EC_KEY_get0_group + self.EC_KEY_get0_group.restype = ctypes.c_void_p + self.EC_KEY_get0_group.argtypes = [ctypes.c_void_p] + + self.EC_POINT_get_affine_coordinates_GFp = self._lib.EC_POINT_get_affine_coordinates_GFp + self.EC_POINT_get_affine_coordinates_GFp.restype = ctypes.c_int + self.EC_POINT_get_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key + self.EC_KEY_set_private_key.restype = ctypes.c_int + self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, + ctypes.c_void_p] + + self.EC_KEY_set_public_key = self._lib.EC_KEY_set_public_key + self.EC_KEY_set_public_key.restype = ctypes.c_int + self.EC_KEY_set_public_key.argtypes = [ctypes.c_void_p, + ctypes.c_void_p] + + self.EC_KEY_set_group = self._lib.EC_KEY_set_group + self.EC_KEY_set_group.restype = ctypes.c_int + self.EC_KEY_set_group.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self.EC_POINT_set_affine_coordinates_GFp = self._lib.EC_POINT_set_affine_coordinates_GFp + self.EC_POINT_set_affine_coordinates_GFp.restype = ctypes.c_int + self.EC_POINT_set_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + self.EC_POINT_new = self._lib.EC_POINT_new + self.EC_POINT_new.restype = ctypes.c_void_p + self.EC_POINT_new.argtypes = [ctypes.c_void_p] + + self.EC_POINT_free = self._lib.EC_POINT_free + self.EC_POINT_free.restype = None + self.EC_POINT_free.argtypes = [ctypes.c_void_p] + + self.BN_CTX_free = self._lib.BN_CTX_free + self.BN_CTX_free.restype = None + self.BN_CTX_free.argtypes = [ctypes.c_void_p] + + self.EC_POINT_mul = self._lib.EC_POINT_mul + self.EC_POINT_mul.restype = None + self.EC_POINT_mul.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key + self.EC_KEY_set_private_key.restype = ctypes.c_int + self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, + ctypes.c_void_p] + + self.ECDH_OpenSSL = self._lib.ECDH_OpenSSL + self._lib.ECDH_OpenSSL.restype = ctypes.c_void_p + self._lib.ECDH_OpenSSL.argtypes = [] + + self.BN_CTX_new = self._lib.BN_CTX_new + self._lib.BN_CTX_new.restype = ctypes.c_void_p + self._lib.BN_CTX_new.argtypes = [] + + self.ECDH_set_method = self._lib.ECDH_set_method + self._lib.ECDH_set_method.restype = ctypes.c_int + self._lib.ECDH_set_method.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self.ECDH_compute_key = self._lib.ECDH_compute_key + self.ECDH_compute_key.restype = ctypes.c_int + self.ECDH_compute_key.argtypes = [ctypes.c_void_p, + ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_CipherInit_ex = self._lib.EVP_CipherInit_ex + self.EVP_CipherInit_ex.restype = ctypes.c_int + self.EVP_CipherInit_ex.argtypes = [ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_CIPHER_CTX_new = self._lib.EVP_CIPHER_CTX_new + self.EVP_CIPHER_CTX_new.restype = ctypes.c_void_p + self.EVP_CIPHER_CTX_new.argtypes = [] + + # Cipher + self.EVP_aes_128_cfb128 = self._lib.EVP_aes_128_cfb128 + self.EVP_aes_128_cfb128.restype = ctypes.c_void_p + self.EVP_aes_128_cfb128.argtypes = [] + + self.EVP_aes_256_cfb128 = self._lib.EVP_aes_256_cfb128 + self.EVP_aes_256_cfb128.restype = ctypes.c_void_p + self.EVP_aes_256_cfb128.argtypes = [] + + self.EVP_aes_128_cbc = self._lib.EVP_aes_128_cbc + self.EVP_aes_128_cbc.restype = ctypes.c_void_p + self.EVP_aes_128_cbc.argtypes = [] + + self.EVP_aes_256_cbc = self._lib.EVP_aes_256_cbc + self.EVP_aes_256_cbc.restype = ctypes.c_void_p + self.EVP_aes_256_cbc.argtypes = [] + + #self.EVP_aes_128_ctr = self._lib.EVP_aes_128_ctr + #self.EVP_aes_128_ctr.restype = ctypes.c_void_p + #self.EVP_aes_128_ctr.argtypes = [] + + #self.EVP_aes_256_ctr = self._lib.EVP_aes_256_ctr + #self.EVP_aes_256_ctr.restype = ctypes.c_void_p + #self.EVP_aes_256_ctr.argtypes = [] + + self.EVP_aes_128_ofb = self._lib.EVP_aes_128_ofb + self.EVP_aes_128_ofb.restype = ctypes.c_void_p + self.EVP_aes_128_ofb.argtypes = [] + + self.EVP_aes_256_ofb = self._lib.EVP_aes_256_ofb + self.EVP_aes_256_ofb.restype = ctypes.c_void_p + self.EVP_aes_256_ofb.argtypes = [] + + self.EVP_bf_cbc = self._lib.EVP_bf_cbc + self.EVP_bf_cbc.restype = ctypes.c_void_p + self.EVP_bf_cbc.argtypes = [] + + self.EVP_bf_cfb64 = self._lib.EVP_bf_cfb64 + self.EVP_bf_cfb64.restype = ctypes.c_void_p + self.EVP_bf_cfb64.argtypes = [] + + self.EVP_rc4 = self._lib.EVP_rc4 + self.EVP_rc4.restype = ctypes.c_void_p + self.EVP_rc4.argtypes = [] + + self.EVP_CIPHER_CTX_cleanup = self._lib.EVP_CIPHER_CTX_cleanup + self.EVP_CIPHER_CTX_cleanup.restype = ctypes.c_int + self.EVP_CIPHER_CTX_cleanup.argtypes = [ctypes.c_void_p] + + self.EVP_CIPHER_CTX_free = self._lib.EVP_CIPHER_CTX_free + self.EVP_CIPHER_CTX_free.restype = None + self.EVP_CIPHER_CTX_free.argtypes = [ctypes.c_void_p] + + self.EVP_CipherUpdate = self._lib.EVP_CipherUpdate + self.EVP_CipherUpdate.restype = ctypes.c_int + self.EVP_CipherUpdate.argtypes = [ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] + + self.EVP_CipherFinal_ex = self._lib.EVP_CipherFinal_ex + self.EVP_CipherFinal_ex.restype = ctypes.c_int + self.EVP_CipherFinal_ex.argtypes = [ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_DigestInit = self._lib.EVP_DigestInit + self.EVP_DigestInit.restype = ctypes.c_int + self._lib.EVP_DigestInit.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_DigestUpdate = self._lib.EVP_DigestUpdate + self.EVP_DigestUpdate.restype = ctypes.c_int + self.EVP_DigestUpdate.argtypes = [ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_int] + + self.EVP_DigestFinal = self._lib.EVP_DigestFinal + self.EVP_DigestFinal.restype = ctypes.c_int + self.EVP_DigestFinal.argtypes = [ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_ecdsa = self._lib.EVP_ecdsa + self._lib.EVP_ecdsa.restype = ctypes.c_void_p + self._lib.EVP_ecdsa.argtypes = [] + + self.ECDSA_sign = self._lib.ECDSA_sign + self.ECDSA_sign.restype = ctypes.c_int + self.ECDSA_sign.argtypes = [ctypes.c_int, ctypes.c_void_p, + ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + self.ECDSA_verify = self._lib.ECDSA_verify + self.ECDSA_verify.restype = ctypes.c_int + self.ECDSA_verify.argtypes = [ctypes.c_int, ctypes.c_void_p, + ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] + + self.EVP_MD_CTX_create = self._lib.EVP_MD_CTX_create + self.EVP_MD_CTX_create.restype = ctypes.c_void_p + self.EVP_MD_CTX_create.argtypes = [] + + self.EVP_MD_CTX_init = self._lib.EVP_MD_CTX_init + self.EVP_MD_CTX_init.restype = None + self.EVP_MD_CTX_init.argtypes = [ctypes.c_void_p] + + self.EVP_MD_CTX_destroy = self._lib.EVP_MD_CTX_destroy + self.EVP_MD_CTX_destroy.restype = None + self.EVP_MD_CTX_destroy.argtypes = [ctypes.c_void_p] + + self.RAND_bytes = self._lib.RAND_bytes + self.RAND_bytes.restype = None + self.RAND_bytes.argtypes = [ctypes.c_void_p, ctypes.c_int] + + + self.EVP_sha256 = self._lib.EVP_sha256 + self.EVP_sha256.restype = ctypes.c_void_p + self.EVP_sha256.argtypes = [] + + self.i2o_ECPublicKey = self._lib.i2o_ECPublicKey + self.i2o_ECPublicKey.restype = ctypes.c_void_p + self.i2o_ECPublicKey.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self.EVP_sha512 = self._lib.EVP_sha512 + self.EVP_sha512.restype = ctypes.c_void_p + self.EVP_sha512.argtypes = [] + + self.HMAC = self._lib.HMAC + self.HMAC.restype = ctypes.c_void_p + 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 + 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, + ctypes.c_int, ctypes.c_void_p, + ctypes.c_int, ctypes.c_void_p] + + self._set_ciphers() + self._set_curves() + + def _set_ciphers(self): + self.cipher_algo = { + 'aes-128-cbc': CipherName('aes-128-cbc', self.EVP_aes_128_cbc, 16), + 'aes-256-cbc': CipherName('aes-256-cbc', self.EVP_aes_256_cbc, 16), + 'aes-128-cfb': CipherName('aes-128-cfb', self.EVP_aes_128_cfb128, 16), + 'aes-256-cfb': CipherName('aes-256-cfb', self.EVP_aes_256_cfb128, 16), + 'aes-128-ofb': CipherName('aes-128-ofb', self._lib.EVP_aes_128_ofb, 16), + 'aes-256-ofb': CipherName('aes-256-ofb', self._lib.EVP_aes_256_ofb, 16), + #'aes-128-ctr': CipherName('aes-128-ctr', self._lib.EVP_aes_128_ctr, 16), + #'aes-256-ctr': CipherName('aes-256-ctr', self._lib.EVP_aes_256_ctr, 16), + 'bf-cfb': CipherName('bf-cfb', self.EVP_bf_cfb64, 8), + 'bf-cbc': CipherName('bf-cbc', self.EVP_bf_cbc, 8), + 'rc4': CipherName('rc4', self.EVP_rc4, 128), # 128 is the initialisation size not block size + } + + def _set_curves(self): + self.curves = { + 'secp112r1': 704, + 'secp112r2': 705, + 'secp128r1': 706, + 'secp128r2': 707, + 'secp160k1': 708, + 'secp160r1': 709, + 'secp160r2': 710, + 'secp192k1': 711, + 'secp224k1': 712, + 'secp224r1': 713, + 'secp256k1': 714, + 'secp384r1': 715, + 'secp521r1': 716, + 'sect113r1': 717, + 'sect113r2': 718, + 'sect131r1': 719, + 'sect131r2': 720, + 'sect163k1': 721, + 'sect163r1': 722, + 'sect163r2': 723, + 'sect193r1': 724, + 'sect193r2': 725, + 'sect233k1': 726, + 'sect233r1': 727, + 'sect239k1': 728, + 'sect283k1': 729, + 'sect283r1': 730, + 'sect409k1': 731, + 'sect409r1': 732, + 'sect571k1': 733, + 'sect571r1': 734, + } + + def BN_num_bytes(self, x): + """ + returns the length of a BN (OpenSSl API) + """ + return int((self.BN_num_bits(x) + 7) / 8) + + def get_cipher(self, name): + """ + returns the OpenSSL cipher instance + """ + if name not in self.cipher_algo: + raise Exception("Unknown cipher") + return self.cipher_algo[name] + + def get_curve(self, name): + """ + returns the id of a elliptic curve + """ + if name not in self.curves: + raise Exception("Unknown curve") + return self.curves[name] + + def get_curve_by_id(self, id): + """ + returns the name of a elliptic curve with his id + """ + res = None + for i in self.curves: + if self.curves[i] == id: + res = i + break + if res is None: + raise Exception("Unknown curve") + return res + + def rand(self, size): + """ + OpenSSL random function + """ + buffer = self.malloc(0, size) + self.RAND_bytes(buffer, size) + return buffer.raw + + def malloc(self, data, size): + """ + returns a create_string_buffer (ctypes) + """ + buffer = None + if data != 0: + if sys.version_info.major == 3 and isinstance(data, type('')): + data = data.encode() + buffer = self.create_string_buffer(data, size) + else: + buffer = self.create_string_buffer(size) + return buffer + +try: + OpenSSL = _OpenSSL('libcrypto.so') +except: + try: + OpenSSL = _OpenSSL('libeay32.dll') + except: + try: + OpenSSL = _OpenSSL('libcrypto.dylib') + except: + try: + from os import path + lib_path = path.join(sys._MEIPASS, "libeay32.dll") + OpenSSL = _OpenSSL(lib_path) + except: + if 'linux' in sys.platform: + try: + from ctypes.util import find_library + OpenSSL = _OpenSSL(find_library('ssl')) + except Exception, err: + raise Exception("Couldn't load the OpenSSL library. You must install it. Error message:"+err) + else: + raise Exception("Couldn't load the OpenSSL library. You must install it.") diff --git a/regenerateaddresses.py b/regenerateaddresses.py new file mode 100644 index 00000000..e47f6b6e --- /dev/null +++ b/regenerateaddresses.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'regenerateaddresses.ui' +# +# Created: Thu Jan 24 15:52:24 2013 +# by: PyQt4 UI code generator 4.9.4 +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore, QtGui + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + _fromUtf8 = lambda s: s + +class Ui_regenerateAddressesDialog(object): + def setupUi(self, regenerateAddressesDialog): + regenerateAddressesDialog.setObjectName(_fromUtf8("regenerateAddressesDialog")) + regenerateAddressesDialog.resize(532, 332) + self.gridLayout_2 = QtGui.QGridLayout(regenerateAddressesDialog) + self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) + self.buttonBox = QtGui.QDialogButtonBox(regenerateAddressesDialog) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) + self.buttonBox.setObjectName(_fromUtf8("buttonBox")) + self.gridLayout_2.addWidget(self.buttonBox, 1, 0, 1, 1) + self.groupBox = QtGui.QGroupBox(regenerateAddressesDialog) + self.groupBox.setObjectName(_fromUtf8("groupBox")) + self.gridLayout = QtGui.QGridLayout(self.groupBox) + self.gridLayout.setObjectName(_fromUtf8("gridLayout")) + self.label_6 = QtGui.QLabel(self.groupBox) + self.label_6.setObjectName(_fromUtf8("label_6")) + self.gridLayout.addWidget(self.label_6, 1, 0, 1, 1) + self.lineEditPassphrase = QtGui.QLineEdit(self.groupBox) + self.lineEditPassphrase.setInputMethodHints(QtCore.Qt.ImhHiddenText|QtCore.Qt.ImhNoAutoUppercase|QtCore.Qt.ImhNoPredictiveText) + self.lineEditPassphrase.setEchoMode(QtGui.QLineEdit.Password) + self.lineEditPassphrase.setObjectName(_fromUtf8("lineEditPassphrase")) + self.gridLayout.addWidget(self.lineEditPassphrase, 2, 0, 1, 5) + self.label_11 = QtGui.QLabel(self.groupBox) + self.label_11.setObjectName(_fromUtf8("label_11")) + self.gridLayout.addWidget(self.label_11, 3, 0, 1, 3) + self.spinBoxNumberOfAddressesToMake = QtGui.QSpinBox(self.groupBox) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.spinBoxNumberOfAddressesToMake.sizePolicy().hasHeightForWidth()) + self.spinBoxNumberOfAddressesToMake.setSizePolicy(sizePolicy) + self.spinBoxNumberOfAddressesToMake.setMinimum(1) + self.spinBoxNumberOfAddressesToMake.setProperty("value", 8) + self.spinBoxNumberOfAddressesToMake.setObjectName(_fromUtf8("spinBoxNumberOfAddressesToMake")) + self.gridLayout.addWidget(self.spinBoxNumberOfAddressesToMake, 3, 3, 1, 1) + spacerItem = QtGui.QSpacerItem(132, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout.addItem(spacerItem, 3, 4, 1, 1) + self.label_2 = QtGui.QLabel(self.groupBox) + self.label_2.setObjectName(_fromUtf8("label_2")) + self.gridLayout.addWidget(self.label_2, 4, 0, 1, 1) + self.lineEditAddressVersionNumber = QtGui.QLineEdit(self.groupBox) + self.lineEditAddressVersionNumber.setEnabled(False) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.lineEditAddressVersionNumber.sizePolicy().hasHeightForWidth()) + self.lineEditAddressVersionNumber.setSizePolicy(sizePolicy) + self.lineEditAddressVersionNumber.setMaximumSize(QtCore.QSize(31, 16777215)) + self.lineEditAddressVersionNumber.setObjectName(_fromUtf8("lineEditAddressVersionNumber")) + self.gridLayout.addWidget(self.lineEditAddressVersionNumber, 4, 1, 1, 1) + spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout.addItem(spacerItem1, 4, 2, 1, 1) + self.label_3 = QtGui.QLabel(self.groupBox) + self.label_3.setObjectName(_fromUtf8("label_3")) + self.gridLayout.addWidget(self.label_3, 5, 0, 1, 1) + self.lineEditStreamNumber = QtGui.QLineEdit(self.groupBox) + self.lineEditStreamNumber.setEnabled(False) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.lineEditStreamNumber.sizePolicy().hasHeightForWidth()) + self.lineEditStreamNumber.setSizePolicy(sizePolicy) + self.lineEditStreamNumber.setMaximumSize(QtCore.QSize(31, 16777215)) + self.lineEditStreamNumber.setObjectName(_fromUtf8("lineEditStreamNumber")) + self.gridLayout.addWidget(self.lineEditStreamNumber, 5, 1, 1, 1) + spacerItem2 = QtGui.QSpacerItem(325, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.gridLayout.addItem(spacerItem2, 5, 2, 1, 3) + self.checkBoxEighteenByteRipe = QtGui.QCheckBox(self.groupBox) + self.checkBoxEighteenByteRipe.setObjectName(_fromUtf8("checkBoxEighteenByteRipe")) + self.gridLayout.addWidget(self.checkBoxEighteenByteRipe, 6, 0, 1, 5) + self.label_4 = QtGui.QLabel(self.groupBox) + self.label_4.setWordWrap(True) + self.label_4.setObjectName(_fromUtf8("label_4")) + self.gridLayout.addWidget(self.label_4, 7, 0, 1, 5) + self.label = QtGui.QLabel(self.groupBox) + self.label.setWordWrap(True) + self.label.setObjectName(_fromUtf8("label")) + self.gridLayout.addWidget(self.label, 0, 0, 1, 5) + self.gridLayout_2.addWidget(self.groupBox, 0, 0, 1, 1) + + self.retranslateUi(regenerateAddressesDialog) + QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), regenerateAddressesDialog.accept) + QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), regenerateAddressesDialog.reject) + QtCore.QMetaObject.connectSlotsByName(regenerateAddressesDialog) + + def retranslateUi(self, regenerateAddressesDialog): + regenerateAddressesDialog.setWindowTitle(QtGui.QApplication.translate("regenerateAddressesDialog", "Regenerate Existing Addresses", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox.setTitle(QtGui.QApplication.translate("regenerateAddressesDialog", "Regenerate existing addresses", None, QtGui.QApplication.UnicodeUTF8)) + self.label_6.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "Passphrase", None, QtGui.QApplication.UnicodeUTF8)) + self.label_11.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "Number of addresses to make based on your passphrase:", None, QtGui.QApplication.UnicodeUTF8)) + self.label_2.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "Address version Number:", None, QtGui.QApplication.UnicodeUTF8)) + self.lineEditAddressVersionNumber.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "2", None, QtGui.QApplication.UnicodeUTF8)) + self.label_3.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "Stream number:", None, QtGui.QApplication.UnicodeUTF8)) + self.lineEditStreamNumber.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "1", None, QtGui.QApplication.UnicodeUTF8)) + self.checkBoxEighteenByteRipe.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter", None, QtGui.QApplication.UnicodeUTF8)) + self.label_4.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "You must check (or not check) this box just like you did (or didn\'t) when you made your addresses the first time.", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setText(QtGui.QApplication.translate("regenerateAddressesDialog", "If you have previously made deterministic addresses but lost them due to an accident (like hard drive failure), you can regenerate them here. If you used the random number generator to make your addresses then this form will be of no use to you.", None, QtGui.QApplication.UnicodeUTF8)) + diff --git a/regenerateaddresses.ui b/regenerateaddresses.ui new file mode 100644 index 00000000..2dbecf84 --- /dev/null +++ b/regenerateaddresses.ui @@ -0,0 +1,237 @@ + + + regenerateAddressesDialog + + + + 0 + 0 + 532 + 332 + + + + Regenerate Existing Addresses + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + Regenerate existing addresses + + + + + + Passphrase + + + + + + + Qt::ImhHiddenText|Qt::ImhNoAutoUppercase|Qt::ImhNoPredictiveText + + + QLineEdit::Password + + + + + + + Number of addresses to make based on your passphrase: + + + + + + + + 0 + 0 + + + + 1 + + + 8 + + + + + + + Qt::Horizontal + + + + 132 + 20 + + + + + + + + Address version Number: + + + + + + + false + + + + 0 + 0 + + + + + 31 + 16777215 + + + + 2 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Stream number: + + + + + + + false + + + + 0 + 0 + + + + + 31 + 16777215 + + + + 1 + + + + + + + Qt::Horizontal + + + + 325 + 20 + + + + + + + + Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter + + + + + + + You must check (or not check) this box just like you did (or didn't) when you made your addresses the first time. + + + true + + + + + + + If you have previously made deterministic addresses but lost them due to an accident (like hard drive failure), you can regenerate them here. If you used the random number generator to make your addresses then this form will be of no use to you. + + + true + + + + + + + + + + + + buttonBox + accepted() + regenerateAddressesDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + regenerateAddressesDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + +