diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index b46e5a03..7f13ded4 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -48,7 +48,7 @@ import time # OSX python version check import sys -if sys.platform == 'darwin': +if 'win' in sys.platform: if float("{1}.{2}".format(*sys.version_info)) < 7.5: msg = "You should use python 2.7.5 or greater. Your version: %s", "{0}.{1}.{2}".format(*sys.version_info) logger.critical(msg) diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index c6e99a4b..2e215606 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -79,11 +79,11 @@ class addressGenerator(threading.Thread): startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) - potentialPubSigningKey = pointMult(potentialPrivSigningKey) + potentialPubSigningKey = highlevelcrypto.pointMult(potentialPrivSigningKey) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) - potentialPubEncryptionKey = pointMult( + potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', @@ -175,9 +175,9 @@ class addressGenerator(threading.Thread): deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] - potentialPubSigningKey = pointMult( + potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey) - potentialPubEncryptionKey = pointMult( + potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', @@ -280,32 +280,3 @@ class addressGenerator(threading.Thread): raise Exception( "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command) - -# Does an EC point multiplication; turns a private key into a public key. -def pointMult(secret): - # ctx = OpenSSL.BN_CTX_new() #This value proved to cause Seg Faults on - # Linux. It turns out that it really didn't speed up EC_POINT_mul anyway. - k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1')) - priv_key = OpenSSL.BN_bin2bn(secret, 32, 0) - group = OpenSSL.EC_KEY_get0_group(k) - pub_key = OpenSSL.EC_POINT_new(group) - - OpenSSL.EC_POINT_mul(group, pub_key, priv_key, None, None, None) - OpenSSL.EC_KEY_set_private_key(k, priv_key) - OpenSSL.EC_KEY_set_public_key(k, pub_key) - # print 'priv_key',priv_key - # print 'pub_key',pub_key - - size = OpenSSL.i2o_ECPublicKey(k, 0) - mb = ctypes.create_string_buffer(size) - OpenSSL.i2o_ECPublicKey(k, ctypes.byref(ctypes.pointer(mb))) - # print 'mb.raw', mb.raw.encode('hex'), 'length:', len(mb.raw) - # print 'mb.raw', mb.raw, 'length:', len(mb.raw) - - OpenSSL.EC_POINT_free(pub_key) - # OpenSSL.BN_CTX_free(ctx) - OpenSSL.BN_free(priv_key) - OpenSSL.EC_KEY_free(k) - return mb.raw - - diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 2b215a60..ce3f8b63 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -1150,25 +1150,27 @@ class objectProcessor(threading.Thread): shared.workerQueue.put(('sendmessage', '')) def ackDataHasAVaildHeader(self, ackData): - if len(ackData) < 24: + if len(ackData) < shared.Header.size: logger.info('The length of ackData is unreasonably short. Not sending ackData.') return False - if ackData[0:4] != '\xe9\xbe\xb4\xd9': + + magic,command,payload_length,checksum = shared.Header.unpack(ackData[:shared.Header.size]) + if magic != 0xE9BEB4D9: logger.info('Ackdata magic bytes were wrong. Not sending ackData.') return False - ackDataPayloadLength, = unpack('>L', ackData[16:20]) - if len(ackData) - 24 != ackDataPayloadLength: + payload = ackData[shared.Header.size:] + if len(payload) != payload_length: logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.') return False - if ackData[20:24] != hashlib.sha512(ackData[24:]).digest()[0:4]: # test the checksum in the message. + if payload_length > 180000000: # If the size of the message is greater than 180MB, ignore it. + return False + if checksum != hashlib.sha512(payload).digest()[0:4]: # test the checksum in the message. logger.info('ackdata checksum wrong. Not sending ackdata.') return False - if ackDataPayloadLength > 180000000: # If the size of the message is greater than 180MB, ignore it. - return False - if (ackData[4:16] != addDataPadding('getpubkey') and - ackData[4:16] != addDataPadding('pubkey') and - ackData[4:16] != addDataPadding('msg') and - ackData[4:16] != addDataPadding('broadcast')): + if (command != addDataPadding('getpubkey') and + command != addDataPadding('pubkey') and + command != addDataPadding('msg') and + command != addDataPadding('broadcast')): return False return True @@ -1211,4 +1213,4 @@ class objectProcessor(threading.Thread): # Throw away any extra lines (headers) after the subject. if subject: subject = subject.splitlines()[0] - return subject, body \ No newline at end of file + return subject, body diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 51ce9fe9..b8b61bce 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -47,7 +47,6 @@ class receiveDataThread(threading.Thread): self.sock = sock self.peer = shared.Peer(HOST, port) self.streamNumber = streamNumber - self.payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header self.objectsThatWeHaveYetToGetFromThisPeer = {} self.selfInitiatedConnections = selfInitiatedConnections self.sendDataThreadQueue = sendDataThreadQueue # used to send commands and data to the sendDataThread @@ -113,28 +112,39 @@ class receiveDataThread(threading.Thread): # with shared.printLock: # print 'self.data is currently ', repr(self.data) # - if len(self.data) < 24: # if so little of the data has arrived that we can't even read the checksum then wait for more data. + if len(self.data) < shared.Header.size: # if so little of the data has arrived that we can't even read the checksum then wait for more data. return - if self.data[0:4] != '\xe9\xbe\xb4\xd9': + #Use a memoryview so we don't copy data unnecessarily + view = memoryview(self.data) + magic,command,payloadLength,checksum = shared.Header.unpack(view[:shared.Header.size]) + view = view[shared.Header.size:] + if magic != 0xE9BEB4D9: #if shared.verbose >= 1: # with shared.printLock: # print 'The magic bytes were not correct. First 40 bytes of data: ' + repr(self.data[0:40]) self.data = "" return - self.payloadLength, = unpack('>L', self.data[16:20]) - if self.payloadLength > 20000000: - logger.info('The incoming message, which we have not yet download, is too large. Ignoring it. (unfortunately there is no way to tell the other node to stop sending it except to disconnect.) Message size: %s' % self.payloadLength) - self.data = self.data[self.payloadLength + 24:] + if payloadLength > 20000000: + logger.info('The incoming message, which we have not yet download, is too large. Ignoring it. (unfortunately there is no way to tell the other node to stop sending it except to disconnect.) Message size: %s' % payloadLength) + self.data = view[payloadLength:].tobytes() + del view,magic,command,payloadLength,checksum # we don't need these anymore and better to clean them now before the recursive call rather than after self.processData() return - if len(self.data) < self.payloadLength + 24: # check if the whole message has arrived yet. + if len(view) < payloadLength: # check if the whole message has arrived yet. return - if self.data[20:24] != hashlib.sha512(self.data[24:self.payloadLength + 24]).digest()[0:4]: # test the checksum in the message. If it is correct... + payload = view[:payloadLength] + if checksum != hashlib.sha512(payload).digest()[0:4]: # test the checksum in the message. print 'Checksum incorrect. Clearing this message.' - self.data = self.data[self.payloadLength + 24:] + self.data = view[payloadLength:].tobytes() + del view,magic,command,payloadLength,checksum,payload #again better to clean up before the recursive call self.processData() return + + #We can now revert back to bytestrings and take this message out + payload = payload.tobytes() + self.data = view[payloadLength:].tobytes() + del view,magic,payloadLength,checksum # The time we've last seen this node is obviously right now since we # just received valid data from it. So update the knownNodes list so # that other peers can be made aware of its existance. @@ -143,37 +153,39 @@ class receiveDataThread(threading.Thread): shared.knownNodes[self.streamNumber][self.peer] = int(time.time()) shared.knownNodesLock.release() - remoteCommand = self.data[4:16] + #Strip the nulls + command = command.rstrip('\x00') with shared.printLock: - print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.peer + print 'remoteCommand', repr(command), ' from', self.peer + + #TODO: Use a dispatcher here + if not self.connectionIsOrWasFullyEstablished: + if command == 'version': + self.recversion(payload) + elif command == 'verack': + self.recverack() + else: + if command == 'addr': + self.recaddr(payload) + elif command == 'getpubkey': + shared.checkAndSharegetpubkeyWithPeers(payload) + elif command == 'pubkey': + self.recpubkey(payload) + elif command == 'inv': + self.recinv(payload) + elif command == 'getdata': + self.recgetdata(payload) + elif command == 'msg': + self.recmsg(payload) + elif command == 'broadcast': + self.recbroadcast(payload) + elif command == 'ping': + self.sendpong(payload) + #elif command == 'pong': + # pass + #elif command == 'alert': + # pass - if remoteCommand == addDataPadding('version') and not self.connectionIsOrWasFullyEstablished: - self.recversion(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('verack') and not self.connectionIsOrWasFullyEstablished: - self.recverack() - elif remoteCommand == addDataPadding('addr') and self.connectionIsOrWasFullyEstablished: - self.recaddr(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('getpubkey') and self.connectionIsOrWasFullyEstablished: - shared.checkAndSharegetpubkeyWithPeers(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('pubkey') and self.connectionIsOrWasFullyEstablished: - self.recpubkey(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('inv') and self.connectionIsOrWasFullyEstablished: - self.recinv(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('getdata') and self.connectionIsOrWasFullyEstablished: - self.recgetdata(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('msg') and self.connectionIsOrWasFullyEstablished: - self.recmsg(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('broadcast') and self.connectionIsOrWasFullyEstablished: - self.recbroadcast(self.data[24:self.payloadLength + 24]) - elif remoteCommand == addDataPadding('ping') and self.connectionIsOrWasFullyEstablished: - self.sendpong() - elif remoteCommand == addDataPadding('pong') and self.connectionIsOrWasFullyEstablished: - pass - elif remoteCommand == addDataPadding('alert') and self.connectionIsOrWasFullyEstablished: - pass - - self.data = self.data[ - self.payloadLength + 24:] # take this message out and then process the next message if self.data == '': while len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0: shared.numberOfInventoryLookupsPerformed += 1 @@ -226,7 +238,7 @@ class receiveDataThread(threading.Thread): def sendpong(self): print 'Sending pong' - self.sendDataThreadQueue.put((0, 'sendRawData', '\xE9\xBE\xB4\xD9\x70\x6F\x6E\x67' + addDataPadding('') + '\xcf\x83\xe1\x35')) + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('pong'))) def recverack(self): @@ -297,7 +309,7 @@ class receiveDataThread(threading.Thread): 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. + if numberOfObjectsInInvMessage == 50000: # We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages. self.sendinvMessageToJustThisOnePeer( numberOfObjectsInInvMessage, payload) payload = '' @@ -311,13 +323,9 @@ class receiveDataThread(threading.Thread): # function for broadcasting invs to everyone in our stream. def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): payload = encodeVarint(numberOfObjects) + payload - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - headerData += addDataPadding('inv') - headerData += pack('>L', len(payload)) - headerData += hashlib.sha512(payload).digest()[:4] with shared.printLock: print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' - self.sendDataThreadQueue.put((0, 'sendRawData', headerData + payload)) + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('inv', payload))) def _sleepForTimingAttackMitigation(self, sleepTime): # We don't need to do the timing attack mitigation if we are @@ -455,14 +463,8 @@ class receiveDataThread(threading.Thread): def sendgetdata(self, hash): with shared.printLock: print 'sending getdata to retrieve object with hash:', hash.encode('hex') - payload = '\x01' + hash - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - headerData += addDataPadding('getdata') - headerData += pack('>L', len( - payload)) # payload length. Note that we add an extra 8 for the nonce. - headerData += hashlib.sha512(payload).digest()[:4] - self.sendDataThreadQueue.put((0, 'sendRawData', headerData + payload)) + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('getdata', payload))) # We have received a getdata request from our peer @@ -499,43 +501,17 @@ class receiveDataThread(threading.Thread): # Our peer has requested (in a getdata message) that we send an object. def sendData(self, objectType, payload): - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - if objectType == 'pubkey': - with shared.printLock: - print 'sending pubkey' - - headerData += addDataPadding('pubkey') - elif objectType == 'getpubkey' or objectType == 'pubkeyrequest': - with shared.printLock: - print 'sending getpubkey' - - headerData += addDataPadding('getpubkey') - elif objectType == 'msg': - with shared.printLock: - print 'sending msg' - - headerData += addDataPadding('msg') - elif objectType == 'broadcast': - with shared.printLock: - print 'sending broadcast' - - headerData += addDataPadding('broadcast') - else: + if (objectType != 'pubkey' and + objectType != 'getpubkey' and + objectType != 'msg' and + objectType != 'broadcast'): sys.stderr.write( 'Error: sendData has been asked to send a strange objectType: %s\n' % str(objectType)) return - headerData += pack('>L', len(payload)) # payload length. - headerData += hashlib.sha512(payload).digest()[:4] - self.sendDataThreadQueue.put((0, 'sendRawData', headerData + payload)) - - - # Advertise this object to all of our peers - """def broadcastinv(self, hash): with shared.printLock: - print 'broadcasting inv with hash:', hash.encode('hex') + print 'sending', objectType + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket(objectType, payload))) - shared.broadcastToSendDataQueues((self.streamNumber, 'advertiseobject', hash)) - """ def _checkIPv4Address(self, host, hostFromAddrMessage): # print 'hostFromAddrMessage', hostFromAddrMessage @@ -545,7 +521,7 @@ class receiveDataThread(threading.Thread): if host[0] == '\x0A': print 'Ignoring IP address in private range:', hostFromAddrMessage return False - if host[0:2] == '\xC0A8': + if host[0:2] == '\xC0\xA8': print 'Ignoring IP address in private range:', hostFromAddrMessage return False return True @@ -745,11 +721,7 @@ class receiveDataThread(threading.Thread): payload += pack('>H', PORT) # remote port payload = encodeVarint(numberOfAddressesInAddrMessage) + payload - datatosend = '\xE9\xBE\xB4\xD9' + addDataPadding('addr') - datatosend = datatosend + pack('>L', len(payload)) # payload length - datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] - datatosend = datatosend + payload - self.sendDataThreadQueue.put((0, 'sendRawData', datatosend)) + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('addr', payload))) # We have received a version message @@ -832,7 +804,7 @@ class receiveDataThread(threading.Thread): def sendverack(self): with shared.printLock: print 'Sending verack' - self.sendDataThreadQueue.put((0, 'sendRawData', '\xE9\xBE\xB4\xD9\x76\x65\x72\x61\x63\x6B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')) + self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('verack'))) self.verackSent = True if self.verackReceived: self.connectionFullyEstablished() diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index f2bc5e20..b8bb61e8 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -109,13 +109,9 @@ class sendDataThread(threading.Thread): payload += pack('>H', port) payload = encodeVarint(numberOfAddressesInAddrMessage) + payload - datatosend = '\xE9\xBE\xB4\xD9' + addDataPadding('addr') - datatosend = datatosend + pack('>L', len(payload)) # payload length - datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] - datatosend = datatosend + payload - + packet = shared.CreatePacket('addr', payload) try: - self.sock.sendall(datatosend) + self.sock.sendall(packet) self.lastTimeISentData = int(time.time()) except: print 'sendaddr: self.sock.sendall failed' @@ -132,12 +128,9 @@ class sendDataThread(threading.Thread): payload += hash if payload != '': payload = encodeVarint(len(payload)/32) + payload - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - headerData += addDataPadding('inv') - headerData += pack('>L', len(payload)) - headerData += hashlib.sha512(payload).digest()[:4] + packet = shared.CreatePacket('inv', payload) try: - self.sock.sendall(headerData + payload) + self.sock.sendall(packet) self.lastTimeISentData = int(time.time()) except: print 'sendinv: self.sock.sendall failed' @@ -148,10 +141,9 @@ class sendDataThread(threading.Thread): # Send out a pong message to keep the connection alive. with shared.printLock: print 'Sending pong to', self.peer, 'to keep connection alive.' - + packet = shared.CreatePacket('pong') try: - self.sock.sendall( - '\xE9\xBE\xB4\xD9' + addDataPadding('pong') + '\x00\x00\x00\x00\xcf\x83\xe1\x35') # Magic bytes + pong command + zero data length + checksum + self.sock.sendall(packet) self.lastTimeISentData = int(time.time()) except: print 'send pong failed' diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 362d1d8f..5e8f11e8 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -8,7 +8,6 @@ from addresses import * import highlevelcrypto import proofofwork import sys -from class_addressGenerator import pointMult import tr from debug import logger from helper_sql import * @@ -305,7 +304,7 @@ class singleWorker(threading.Thread): addressVersionNumber) + encodeVarint(streamNumber) + hash).digest()).digest() payload += doubleHashOfAddressData[32:] # the tag privEncryptionKey = doubleHashOfAddressData[:32] - pubEncryptionKey = pointMult(privEncryptionKey) + pubEncryptionKey = highlevelcrypto.pointMult(privEncryptionKey) payload += highlevelcrypto.encrypt( dataToEncrypt, pubEncryptionKey.encode('hex')) @@ -416,7 +415,7 @@ class singleWorker(threading.Thread): else: privEncryptionKey = doubleHashOfAddressData[:32] - pubEncryptionKey = pointMult(privEncryptionKey) + pubEncryptionKey = highlevelcrypto.pointMult(privEncryptionKey) payload += highlevelcrypto.encrypt( dataToEncrypt, pubEncryptionKey.encode('hex')) @@ -950,8 +949,4 @@ class singleWorker(threading.Thread): pass payload = pack('>Q', nonce) + payload - headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - headerData += addDataPadding('msg') - headerData += pack('>L', len(payload)) - headerData += hashlib.sha512(payload).digest()[:4] - return headerData + payload + return shared.CreatePacket('msg', payload) diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 22f44ed3..8838aa9f 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -1,33 +1,56 @@ import pyelliptic -from pyelliptic import arithmetic as a +from pyelliptic import arithmetic as a, OpenSSL 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 + private_key = a.changebase(privkey, 16, 256, minlen=32) + public_key = pointMult(private_key) + privkey_bin = '\x02\xca\x00\x20' + private_key + pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-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 + 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) + 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) + private_key = a.changebase(privkey, 16, 256, minlen=32) + public_key = pointMult(private_key) + return public_key.encode('hex') # Encrypts message with hex public key def encrypt(msg,hexPubkey): - return pyelliptic.ECC(curve='secp256k1').encrypt(msg,hexToPubkey(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) + return makeCryptor(hexPrivkey).decrypt(msg) # Decrypts message with an existing pyelliptic.ECC.ECC object def decryptFast(msg,cryptor): - return cryptor.decrypt(msg) + return cryptor.decrypt(msg) # Signs with hex private key def sign(msg,hexPrivkey): - return makeCryptor(hexPrivkey).sign(msg) + return makeCryptor(hexPrivkey).sign(msg) # Verifies with hex public key def verify(msg,sig,hexPubkey): - return makePubCryptor(hexPubkey).verify(sig,msg) + return makePubCryptor(hexPubkey).verify(sig,msg) + +# Does an EC point multiplication; turns a private key into a public key. +def pointMult(secret): + k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1')) + priv_key = OpenSSL.BN_bin2bn(secret, 32, None) + 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) + + size = OpenSSL.i2o_ECPublicKey(k, None) + mb = OpenSSL.create_string_buffer(size) + OpenSSL.i2o_ECPublicKey(k, OpenSSL.byref(OpenSSL.pointer(mb))) + + OpenSSL.EC_POINT_free(pub_key) + OpenSSL.BN_free(priv_key) + OpenSSL.EC_KEY_free(k) + return mb.raw diff --git a/src/shared.py b/src/shared.py index 96b9a7ce..d4df5da1 100644 --- a/src/shared.py +++ b/src/shared.py @@ -21,6 +21,7 @@ import stat import threading import time from os import path, environ +from struct import Struct # Project imports. from addresses import * @@ -104,6 +105,23 @@ frozen = getattr(sys,'frozen', None) # security. trustedPeer = None +#Compiled struct for packing/unpacking headers +#New code should use CreatePacket instead of Header.pack +Header = Struct('!L12sL4s') + +#Create a packet +def CreatePacket(command, payload=''): + payload_length = len(payload) + if payload_length == 0: + checksum = '\xCF\x83\xE1\x35' + else: + checksum = hashlib.sha512(payload).digest()[0:4] + + b = bytearray(Header.size + payload_length) + Header.pack_into(b, 0, 0xE9BEB4D9, command, payload_length, checksum) + b[Header.size:] = payload + return bytes(b) + def isInSqlInventory(hash): queryreturn = sqlQuery('''select hash from inventory where hash=?''', hash) return queryreturn != [] @@ -141,11 +159,7 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): 1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection. payload += encodeVarint(myStreamNumber) - datatosend = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. - datatosend = datatosend + 'version\x00\x00\x00\x00\x00' # version command - datatosend = datatosend + pack('>L', len(payload)) # payload length - datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] - return datatosend + payload + return CreatePacket('version', payload) def lookupAppdataFolder(): APPNAME = "PyBitmessage"