objectProcessorThread #582
|
@ -29,6 +29,7 @@ from helper_sql import *
|
||||||
from class_sqlThread import *
|
from class_sqlThread import *
|
||||||
from class_singleCleaner import *
|
from class_singleCleaner import *
|
||||||
from class_singleWorker import *
|
from class_singleWorker import *
|
||||||
|
from class_objectProcessor import *
|
||||||
from class_outgoingSynSender import *
|
from class_outgoingSynSender import *
|
||||||
from class_singleListener import *
|
from class_singleListener import *
|
||||||
from class_addressGenerator import *
|
from class_addressGenerator import *
|
||||||
|
@ -47,6 +48,7 @@ if sys.platform == 'darwin':
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
def connectToStream(streamNumber):
|
def connectToStream(streamNumber):
|
||||||
|
shared.streamsInWhichIAmParticipating[streamNumber] = 'no data'
|
||||||
selfInitiatedConnections[streamNumber] = {}
|
selfInitiatedConnections[streamNumber] = {}
|
||||||
shared.inventorySets[streamNumber] = set()
|
shared.inventorySets[streamNumber] = set()
|
||||||
queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber)
|
queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber)
|
||||||
|
@ -980,6 +982,11 @@ class Main:
|
||||||
singleWorkerThread.daemon = True # close the main program even if there are threads left
|
singleWorkerThread.daemon = True # close the main program even if there are threads left
|
||||||
singleWorkerThread.start()
|
singleWorkerThread.start()
|
||||||
|
|
||||||
|
# Start the thread that calculates POWs
|
||||||
|
objectProcessorThread = objectProcessor()
|
||||||
|
objectProcessorThread.daemon = True # close the main program even if there are threads left
|
||||||
|
objectProcessorThread.start()
|
||||||
|
|
||||||
# Start the SQL thread
|
# Start the SQL thread
|
||||||
sqlLookup = sqlThread()
|
sqlLookup = sqlThread()
|
||||||
sqlLookup.daemon = False # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
|
sqlLookup.daemon = False # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
|
||||||
|
|
|
@ -30,18 +30,338 @@ class objectProcessor(threading.Thread):
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
while True:
|
while True:
|
||||||
data = shared.objectProcessorQueue.get()
|
objectType, data = shared.objectProcessorQueue.get()
|
||||||
|
|
||||||
remoteCommand = data[4:16]
|
if objectType == 'getpubkey':
|
||||||
if remoteCommand == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00':
|
self.processgetpubkey(data)
|
||||||
|
elif objectType == 'pubkey':
|
||||||
|
self.processpubkey(data)
|
||||||
|
elif objectType == 'msg':
|
||||||
self.processmsg(data)
|
self.processmsg(data)
|
||||||
|
elif objectType == 'broadcast':
|
||||||
|
self.processbroadcast(data)
|
||||||
|
else:
|
||||||
|
logger.critical('Error! Bug! The class_objectProcessor was passed an object type it doesn\'t recognize: %s' % str(objectType))
|
||||||
|
|
||||||
|
with shared.objectProcessorQueueSizeLock:
|
||||||
|
shared.objectProcessorQueueSize -= len(data) # We maintain objectProcessorQueueSize so that we will slow down requesting objects if too much data accumulates in the queue.
|
||||||
|
#print 'objectProcessorQueueSize:', shared.objectProcessorQueueSize
|
||||||
|
|
||||||
|
def processgetpubkey(self, data):
|
||||||
|
readPosition = 8 # bypass the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += addressVersionLength
|
||||||
|
streamNumber, streamNumberLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += streamNumberLength
|
||||||
|
|
||||||
|
if requestedAddressVersionNumber == 0:
|
||||||
|
print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
|
||||||
|
return
|
||||||
|
elif requestedAddressVersionNumber == 1:
|
||||||
|
print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
|
||||||
|
return
|
||||||
|
elif requestedAddressVersionNumber > 4:
|
||||||
|
print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
|
||||||
|
return
|
||||||
|
|
||||||
|
myAddress = ''
|
||||||
|
if requestedAddressVersionNumber <= 3 :
|
||||||
|
requestedHash = data[readPosition:readPosition + 20]
|
||||||
|
if len(requestedHash) != 20:
|
||||||
|
print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
|
||||||
|
return
|
||||||
|
with shared.printLock:
|
||||||
|
print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex')
|
||||||
|
if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine
|
||||||
|
myAddress = shared.myAddressesByHash[requestedHash]
|
||||||
|
elif requestedAddressVersionNumber >= 4:
|
||||||
|
requestedTag = data[readPosition:readPosition + 32]
|
||||||
|
if len(requestedTag) != 32:
|
||||||
|
print 'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
|
||||||
|
return
|
||||||
|
with shared.printLock:
|
||||||
|
print 'the tag requested in this getpubkey request is:', requestedTag.encode('hex')
|
||||||
|
if requestedTag in shared.myAddressesByTag:
|
||||||
|
myAddress = shared.myAddressesByTag[requestedTag]
|
||||||
|
|
||||||
|
if myAddress == '':
|
||||||
|
with shared.printLock:
|
||||||
|
print 'This getpubkey request is not for any of my keys.'
|
||||||
|
return
|
||||||
|
|
||||||
|
if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
|
||||||
|
with shared.printLock:
|
||||||
|
sys.stderr.write(
|
||||||
|
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.\n')
|
||||||
|
return
|
||||||
|
if decodeAddress(myAddress)[2] != streamNumber:
|
||||||
|
with shared.printLock:
|
||||||
|
sys.stderr.write(
|
||||||
|
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.\n')
|
||||||
|
return
|
||||||
|
if shared.safeConfigGetBoolean(myAddress, 'chan'):
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
lastPubkeySendTime = int(config.get(
|
||||||
|
myAddress, 'lastpubkeysendtime'))
|
||||||
|
except:
|
||||||
|
lastPubkeySendTime = 0
|
||||||
|
if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago...
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
|
||||||
|
return
|
||||||
|
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.'
|
||||||
|
if requestedAddressVersionNumber == 2:
|
||||||
|
shared.workerQueue.put((
|
||||||
|
'doPOWForMyV2Pubkey', requestedHash))
|
||||||
|
elif requestedAddressVersionNumber == 3:
|
||||||
|
shared.workerQueue.put((
|
||||||
|
'sendOutOrStoreMyV3Pubkey', requestedHash))
|
||||||
|
elif requestedAddressVersionNumber == 4:
|
||||||
|
shared.workerQueue.put((
|
||||||
|
'sendOutOrStoreMyV4Pubkey', myAddress))
|
||||||
|
|
||||||
|
def processpubkey(self, data):
|
||||||
|
pubkeyProcessingStartTime = time.time()
|
||||||
|
shared.numberOfPubkeysProcessed += 1
|
||||||
|
shared.UISignalQueue.put((
|
||||||
|
'updateNumberOfPubkeysProcessed', 'no data'))
|
||||||
|
readPosition = 8 # bypass the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
addressVersion, varintLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
streamNumber, varintLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
if addressVersion == 0:
|
||||||
|
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
|
||||||
|
return
|
||||||
|
if addressVersion > 4 or addressVersion == 1:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.'
|
||||||
|
return
|
||||||
|
if addressVersion == 2:
|
||||||
|
if len(data) < 146: # sanity check. This is the minimum possible length.
|
||||||
|
print '(within processpubkey) payloadLength less than 146. Sanity check failed.'
|
||||||
|
return
|
||||||
|
bitfieldBehaviors = data[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
publicSigningKey = data[readPosition:readPosition + 64]
|
||||||
|
# Is it possible for a public key to be invalid such that trying to
|
||||||
|
# encrypt or sign with it will cause an error? If it is, we should
|
||||||
|
# probably test these keys here.
|
||||||
|
readPosition += 64
|
||||||
|
publicEncryptionKey = data[readPosition:readPosition + 64]
|
||||||
|
if len(publicEncryptionKey) < 64:
|
||||||
|
print 'publicEncryptionKey length less than 64. Sanity check failed.'
|
||||||
|
return
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(
|
||||||
|
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
|
||||||
|
ripeHasher = hashlib.new('ripemd160')
|
||||||
|
ripeHasher.update(sha.digest())
|
||||||
|
ripe = ripeHasher.digest()
|
||||||
|
|
||||||
|
with shared.printLock:
|
||||||
|
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
||||||
|
print 'ripe', ripe.encode('hex')
|
||||||
|
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
||||||
|
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
||||||
|
|
||||||
|
|
||||||
|
queryreturn = sqlQuery(
|
||||||
|
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
|
||||||
|
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
|
||||||
|
print 'We HAVE used this pubkey personally. Updating time.'
|
||||||
|
t = (ripe, addressVersion, data, embeddedTime, 'yes')
|
||||||
|
else:
|
||||||
|
print 'We have NOT used this pubkey personally. Inserting in database.'
|
||||||
|
t = (ripe, addressVersion, data, embeddedTime, 'no')
|
||||||
|
# This will also update the embeddedTime.
|
||||||
|
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
||||||
|
# shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
|
||||||
|
self.possibleNewPubkey(ripe = ripe)
|
||||||
|
if addressVersion == 3:
|
||||||
|
if len(data) < 170: # sanity check.
|
||||||
|
print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
|
||||||
|
return
|
||||||
|
bitfieldBehaviors = data[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
|
||||||
|
# Is it possible for a public key to be invalid such that trying to
|
||||||
|
# encrypt or sign with it will cause an error? If it is, we should
|
||||||
|
# probably test these keys here.
|
||||||
|
readPosition += 64
|
||||||
|
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += specifiedNonceTrialsPerByteLength
|
||||||
|
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += specifiedPayloadLengthExtraBytesLength
|
||||||
|
endOfSignedDataPosition = readPosition
|
||||||
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += signatureLengthLength
|
||||||
|
signature = data[readPosition:readPosition + signatureLength]
|
||||||
|
try:
|
||||||
|
if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')):
|
||||||
|
print 'ECDSA verify failed (within processpubkey)'
|
||||||
|
return
|
||||||
|
print 'ECDSA verify passed (within processpubkey)'
|
||||||
|
except Exception as err:
|
||||||
|
print 'ECDSA verify failed (within processpubkey)', err
|
||||||
|
return
|
||||||
|
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(publicSigningKey + publicEncryptionKey)
|
||||||
|
ripeHasher = hashlib.new('ripemd160')
|
||||||
|
ripeHasher.update(sha.digest())
|
||||||
|
ripe = ripeHasher.digest()
|
||||||
|
|
||||||
|
with shared.printLock:
|
||||||
|
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
||||||
|
print 'ripe', ripe.encode('hex')
|
||||||
|
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
||||||
|
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
||||||
|
|
||||||
|
|
||||||
|
queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
|
||||||
|
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
|
||||||
|
print 'We HAVE used this pubkey personally. Updating time.'
|
||||||
|
t = (ripe, addressVersion, data, embeddedTime, 'yes')
|
||||||
|
else:
|
||||||
|
print 'We have NOT used this pubkey personally. Inserting in database.'
|
||||||
|
t = (ripe, addressVersion, data, embeddedTime, 'no')
|
||||||
|
# This will also update the embeddedTime.
|
||||||
|
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
||||||
|
self.possibleNewPubkey(ripe = ripe)
|
||||||
|
|
||||||
|
if addressVersion == 4:
|
||||||
|
if len(data) < 350: # sanity check.
|
||||||
|
print '(within processpubkey) payloadLength less than 350. Sanity check failed.'
|
||||||
|
return
|
||||||
|
signedData = data[8:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
|
||||||
|
tag = data[readPosition:readPosition + 32]
|
||||||
|
readPosition += 32
|
||||||
|
encryptedData = data[readPosition:]
|
||||||
|
if tag not in shared.neededPubkeys:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'We don\'t need this v4 pubkey. We didn\'t ask for it.'
|
||||||
|
return
|
||||||
|
|
||||||
|
# Let us try to decrypt the pubkey
|
||||||
|
cryptorObject = shared.neededPubkeys[tag]
|
||||||
|
try:
|
||||||
|
decryptedData = cryptorObject.decrypt(encryptedData)
|
||||||
|
except:
|
||||||
|
# Someone must have encrypted some data with a different key
|
||||||
|
# but tagged it with a tag for which we are watching.
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Pubkey decryption was unsuccessful.'
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
readPosition = 0
|
||||||
|
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
|
# Is it possible for a public key to be invalid such that trying to
|
||||||
|
# encrypt or check a sig with it will cause an error? If it is, we
|
||||||
|
# should probably test these keys here.
|
||||||
|
readPosition += 64
|
||||||
|
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += specifiedNonceTrialsPerByteLength
|
||||||
|
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += specifiedPayloadLengthExtraBytesLength
|
||||||
|
signedData += decryptedData[:readPosition]
|
||||||
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += signatureLengthLength
|
||||||
|
signature = decryptedData[readPosition:readPosition + signatureLength]
|
||||||
|
try:
|
||||||
|
if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
|
||||||
|
print 'ECDSA verify failed (within processpubkey)'
|
||||||
|
return
|
||||||
|
print 'ECDSA verify passed (within processpubkey)'
|
||||||
|
except Exception as err:
|
||||||
|
print 'ECDSA verify failed (within processpubkey)', err
|
||||||
|
return
|
||||||
|
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(publicSigningKey + publicEncryptionKey)
|
||||||
|
ripeHasher = hashlib.new('ripemd160')
|
||||||
|
ripeHasher.update(sha.digest())
|
||||||
|
ripe = ripeHasher.digest()
|
||||||
|
|
||||||
|
# We need to make sure that the tag on the outside of the encryption
|
||||||
|
# is the one generated from hashing these particular keys.
|
||||||
|
if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.'
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
print 'Tag successfully matches keys in pubkey message' # testing. Will remove soon.
|
||||||
|
|
||||||
|
with shared.printLock:
|
||||||
|
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
||||||
|
print 'ripe', ripe.encode('hex')
|
||||||
|
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
||||||
|
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
||||||
|
|
||||||
|
t = (ripe, addressVersion, signedData, embeddedTime, 'yes')
|
||||||
|
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
||||||
|
|
||||||
|
fromAddress = encodeAddress(addressVersion, streamNumber, ripe)
|
||||||
|
# That this point we know that we have been waiting on this pubkey.
|
||||||
|
# This function will command the workerThread to start work on
|
||||||
|
# the messages that require it.
|
||||||
|
self.possibleNewPubkey(address = fromAddress)
|
||||||
|
|
||||||
|
# Display timing data
|
||||||
|
timeRequiredToProcessPubkey = time.time(
|
||||||
|
) - pubkeyProcessingStartTime
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Time required to process this pubkey:', timeRequiredToProcessPubkey
|
||||||
|
|
||||||
|
|
||||||
def processmsg(self, data):
|
def processmsg(self, data):
|
||||||
"""
|
messageProcessingStartTime = time.time()
|
||||||
We know that the POW and time are correct as they were checked by the
|
shared.numberOfMessagesProcessed += 1
|
||||||
receiveDataThread.
|
shared.UISignalQueue.put((
|
||||||
"""
|
'updateNumberOfMessagesProcessed', 'no data'))
|
||||||
readPosition = 8
|
readPosition = 8 # bypass the nonce
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
@ -90,46 +410,440 @@ class objectProcessor(threading.Thread):
|
||||||
if not initialDecryptionSuccessful:
|
if not initialDecryptionSuccessful:
|
||||||
# This is not a message bound for me.
|
# This is not a message bound for me.
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.'
|
print 'Length of time program spent failing to decrypt this message:', time.time() - messageProcessingStartTime, 'seconds.'
|
||||||
|
return
|
||||||
|
|
||||||
|
# This is a message bound for me.
|
||||||
|
toAddress = shared.myAddressesByHash[
|
||||||
|
toRipe] # Look up my address based on the RIPE hash.
|
||||||
|
readPosition = 0
|
||||||
|
messageVersion, messageVersionLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += messageVersionLength
|
||||||
|
if messageVersion != 1:
|
||||||
|
print 'Cannot understand message versions other than one. Ignoring message.'
|
||||||
|
return
|
||||||
|
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += sendersAddressVersionNumberLength
|
||||||
|
if sendersAddressVersionNumber == 0:
|
||||||
|
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
|
||||||
|
return
|
||||||
|
if sendersAddressVersionNumber > 4:
|
||||||
|
print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
|
||||||
|
return
|
||||||
|
if len(decryptedData) < 170:
|
||||||
|
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
|
||||||
|
return
|
||||||
|
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
if sendersStreamNumber == 0:
|
||||||
|
print 'sender\'s stream number is 0. Ignoring message.'
|
||||||
|
return
|
||||||
|
readPosition += sendersStreamNumberLength
|
||||||
|
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
pubSigningKey = '\x04' + decryptedData[
|
||||||
|
readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
pubEncryptionKey = '\x04' + decryptedData[
|
||||||
|
readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
if sendersAddressVersionNumber >= 3:
|
||||||
|
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
|
||||||
|
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
||||||
|
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
|
||||||
|
if toRipe != decryptedData[readPosition:readPosition + 20]:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
|
||||||
|
print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
|
||||||
|
print 'your toRipe:', toRipe.encode('hex')
|
||||||
|
print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
|
||||||
|
return
|
||||||
|
readPosition += 20
|
||||||
|
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += messageEncodingTypeLength
|
||||||
|
messageLength, messageLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += messageLengthLength
|
||||||
|
message = decryptedData[readPosition:readPosition + messageLength]
|
||||||
|
# print 'First 150 characters of message:', repr(message[:150])
|
||||||
|
readPosition += messageLength
|
||||||
|
ackLength, ackLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += ackLengthLength
|
||||||
|
ackData = decryptedData[readPosition:readPosition + ackLength]
|
||||||
|
readPosition += ackLength
|
||||||
|
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
|
||||||
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += signatureLengthLength
|
||||||
|
signature = decryptedData[
|
||||||
|
readPosition:readPosition + signatureLength]
|
||||||
|
try:
|
||||||
|
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
|
||||||
|
print 'ECDSA verify failed'
|
||||||
|
return
|
||||||
|
print 'ECDSA verify passed'
|
||||||
|
except Exception as err:
|
||||||
|
print 'ECDSA verify failed', err
|
||||||
|
return
|
||||||
|
with shared.printLock:
|
||||||
|
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
|
||||||
|
|
||||||
|
# calculate the fromRipe.
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(pubSigningKey + pubEncryptionKey)
|
||||||
|
ripe = hashlib.new('ripemd160')
|
||||||
|
ripe.update(sha.digest())
|
||||||
|
fromAddress = encodeAddress(
|
||||||
|
sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())
|
||||||
|
# Let's store the public key in case we want to reply to this
|
||||||
|
# person.
|
||||||
|
if sendersAddressVersionNumber <= 3:
|
||||||
|
sqlExecute(
|
||||||
|
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
||||||
|
ripe.digest(),
|
||||||
|
sendersAddressVersionNumber,
|
||||||
|
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
||||||
|
int(time.time()),
|
||||||
|
'yes')
|
||||||
|
# This will check to see whether we happen to be awaiting this
|
||||||
|
# pubkey in order to send a message. If we are, it will do the POW
|
||||||
|
# and send it.
|
||||||
|
self.possibleNewPubkey(ripe=ripe.digest())
|
||||||
|
elif sendersAddressVersionNumber >= 4:
|
||||||
|
sqlExecute(
|
||||||
|
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
||||||
|
ripe.digest(),
|
||||||
|
sendersAddressVersionNumber,
|
||||||
|
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
||||||
|
int(time.time()),
|
||||||
|
'yes')
|
||||||
|
# This will check to see whether we happen to be awaiting this
|
||||||
|
# pubkey in order to send a message. If we are, it will do the POW
|
||||||
|
# and send it.
|
||||||
|
self.possibleNewPubkey(address = fromAddress)
|
||||||
|
# If this message is bound for one of my version 3 addresses (or
|
||||||
|
# higher), then we must check to make sure it meets our demanded
|
||||||
|
# proof of work requirement.
|
||||||
|
if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher:
|
||||||
|
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
|
||||||
|
requiredNonceTrialsPerByte = shared.config.getint(
|
||||||
|
toAddress, 'noncetrialsperbyte')
|
||||||
|
requiredPayloadLengthExtraBytes = shared.config.getint(
|
||||||
|
toAddress, 'payloadlengthextrabytes')
|
||||||
|
if not shared.isProofOfWorkSufficient(data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
|
||||||
|
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
|
||||||
|
return
|
||||||
|
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
|
||||||
|
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
|
||||||
|
queryreturn = sqlQuery(
|
||||||
|
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
|
||||||
|
fromAddress)
|
||||||
|
if queryreturn != []:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Message ignored because address is in blacklist.'
|
||||||
|
|
||||||
|
blockMessage = True
|
||||||
|
else: # We're using a whitelist
|
||||||
|
queryreturn = sqlQuery(
|
||||||
|
'''SELECT label FROM whitelist where address=? and enabled='1' ''',
|
||||||
|
fromAddress)
|
||||||
|
if queryreturn == []:
|
||||||
|
print 'Message ignored because address not in whitelist.'
|
||||||
|
blockMessage = True
|
||||||
|
if not blockMessage:
|
||||||
|
toLabel = shared.config.get(toAddress, 'label')
|
||||||
|
if toLabel == '':
|
||||||
|
toLabel = toAddress
|
||||||
|
|
||||||
|
if messageEncodingType == 2:
|
||||||
|
subject, body = self.decodeType2Message(message)
|
||||||
|
elif messageEncodingType == 1:
|
||||||
|
body = message
|
||||||
|
subject = ''
|
||||||
|
elif messageEncodingType == 0:
|
||||||
|
print 'messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.'
|
||||||
|
else:
|
||||||
|
body = 'Unknown encoding type.\n\n' + repr(message)
|
||||||
|
subject = ''
|
||||||
|
if messageEncodingType != 0:
|
||||||
|
t = (inventoryHash, toAddress, fromAddress, subject, int(
|
||||||
|
time.time()), body, 'inbox', messageEncodingType, 0)
|
||||||
|
helper_inbox.insert(t)
|
||||||
|
|
||||||
|
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
||||||
|
inventoryHash, toAddress, fromAddress, subject, body)))
|
||||||
|
|
||||||
|
# If we are behaving as an API then we might need to run an
|
||||||
|
# outside command to let some program know that a new message
|
||||||
|
# has arrived.
|
||||||
|
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
||||||
|
try:
|
||||||
|
apiNotifyPath = shared.config.get(
|
||||||
|
'bitmessagesettings', 'apinotifypath')
|
||||||
|
except:
|
||||||
|
apiNotifyPath = ''
|
||||||
|
if apiNotifyPath != '':
|
||||||
|
call([apiNotifyPath, "newMessage"])
|
||||||
|
|
||||||
|
# Let us now check and see whether our receiving address is
|
||||||
|
# behaving as a mailing list
|
||||||
|
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
|
||||||
|
try:
|
||||||
|
mailingListName = shared.config.get(
|
||||||
|
toAddress, 'mailinglistname')
|
||||||
|
except:
|
||||||
|
mailingListName = ''
|
||||||
|
# Let us send out this message as a broadcast
|
||||||
|
subject = self.addMailingListNameToSubject(
|
||||||
|
subject, mailingListName)
|
||||||
|
# Let us now send this message out as a broadcast
|
||||||
|
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
|
||||||
|
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
|
||||||
|
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
|
||||||
|
ackdataForBroadcast = OpenSSL.rand(
|
||||||
|
32) # We don't actually need the ackdataForBroadcast for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
|
||||||
|
toAddress = '[Broadcast subscribers]'
|
||||||
|
ripe = ''
|
||||||
|
|
||||||
|
t = ('', toAddress, ripe, fromAddress, subject, message, ackdataForBroadcast, int(
|
||||||
|
time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
|
||||||
|
helper_sent.insert(t)
|
||||||
|
|
||||||
|
shared.UISignalQueue.put(('displayNewSentMessage', (
|
||||||
|
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdataForBroadcast)))
|
||||||
|
shared.workerQueue.put(('sendbroadcast', ''))
|
||||||
|
|
||||||
|
if self.ackDataHasAVaildHeader(ackData):
|
||||||
|
if ackData[4:16] == 'getpubkey\x00\x00\x00':
|
||||||
|
shared.checkAndSharegetpubkeyWithPeers(ackData[24:])
|
||||||
|
elif ackData[4:16] == 'pubkey\x00\x00\x00\x00\x00\x00':
|
||||||
|
shared.checkAndSharePubkeyWithPeers(ackData[24:])
|
||||||
|
elif ackData[4:16] == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00':
|
||||||
|
shared.checkAndShareMsgWithPeers(ackData[24:])
|
||||||
|
elif ackData[4:16] == 'broadcast\x00\x00\x00':
|
||||||
|
shared.checkAndShareBroadcastWithPeers(ackData[24:])
|
||||||
|
|
||||||
|
# Display timing data
|
||||||
|
timeRequiredToAttemptToDecryptMessage = time.time(
|
||||||
|
) - messageProcessingStartTime
|
||||||
|
shared.successfullyDecryptMessageTimings.append(
|
||||||
|
timeRequiredToAttemptToDecryptMessage)
|
||||||
|
sum = 0
|
||||||
|
for item in shared.successfullyDecryptMessageTimings:
|
||||||
|
sum += item
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
|
||||||
|
print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
|
||||||
|
|
||||||
|
|
||||||
|
def processbroadcast(self, data):
|
||||||
|
messageProcessingStartTime = time.time()
|
||||||
|
shared.numberOfBroadcastsProcessed += 1
|
||||||
|
shared.UISignalQueue.put((
|
||||||
|
'updateNumberOfBroadcastsProcessed', 'no data'))
|
||||||
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
readPosition = 8 # bypass the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
else:
|
else:
|
||||||
# This is a message bound for me.
|
readPosition += 4
|
||||||
toAddress = shared.myAddressesByHash[
|
|
||||||
toRipe] # Look up my address based on the RIPE hash.
|
broadcastVersion, broadcastVersionLength = decodeVarint(
|
||||||
readPosition = 0
|
data[readPosition:readPosition + 9])
|
||||||
messageVersion, messageVersionLength = decodeVarint(
|
readPosition += broadcastVersionLength
|
||||||
decryptedData[readPosition:readPosition + 10])
|
if broadcastVersion < 1 or broadcastVersion > 3:
|
||||||
readPosition += messageVersionLength
|
print 'Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
||||||
if messageVersion != 1:
|
return
|
||||||
print 'Cannot understand message versions other than one. Ignoring message.'
|
if broadcastVersion == 1:
|
||||||
|
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
||||||
|
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 9])
|
||||||
|
if sendersAddressVersion <= 1 or sendersAddressVersion >= 3:
|
||||||
|
# Cannot decode senderAddressVersion higher than 2. Assuming
|
||||||
|
# the sender isn\'t being silly, you should upgrade Bitmessage
|
||||||
|
# because this message shall be ignored.
|
||||||
return
|
return
|
||||||
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
|
readPosition += sendersAddressVersionLength
|
||||||
decryptedData[readPosition:readPosition + 10])
|
if sendersAddressVersion == 2:
|
||||||
readPosition += sendersAddressVersionNumberLength
|
sendersStream, sendersStreamLength = decodeVarint(
|
||||||
if sendersAddressVersionNumber == 0:
|
data[readPosition:readPosition + 9])
|
||||||
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
|
readPosition += sendersStreamLength
|
||||||
|
behaviorBitfield = data[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
sendersPubSigningKey = '\x04' + \
|
||||||
|
data[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
sendersPubEncryptionKey = '\x04' + \
|
||||||
|
data[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
endOfPubkeyPosition = readPosition
|
||||||
|
sendersHash = data[readPosition:readPosition + 20]
|
||||||
|
if sendersHash not in shared.broadcastSendersForWhichImWatching:
|
||||||
|
# Display timing data
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - messageProcessingStartTime
|
||||||
|
|
||||||
|
return
|
||||||
|
# At this point, this message claims to be from sendersHash and
|
||||||
|
# we are interested in it. We still have to hash the public key
|
||||||
|
# to make sure it is truly the key that matches the hash, and
|
||||||
|
# also check the signiture.
|
||||||
|
readPosition += 20
|
||||||
|
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
||||||
|
ripe = hashlib.new('ripemd160')
|
||||||
|
ripe.update(sha.digest())
|
||||||
|
if ripe.digest() != sendersHash:
|
||||||
|
# The sender of this message lied.
|
||||||
|
return
|
||||||
|
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 9])
|
||||||
|
if messageEncodingType == 0:
|
||||||
|
return
|
||||||
|
readPosition += messageEncodingTypeLength
|
||||||
|
messageLength, messageLengthLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 9])
|
||||||
|
readPosition += messageLengthLength
|
||||||
|
message = data[readPosition:readPosition + messageLength]
|
||||||
|
readPosition += messageLength
|
||||||
|
readPositionAtBottomOfMessage = readPosition
|
||||||
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 9])
|
||||||
|
readPosition += signatureLengthLength
|
||||||
|
signature = data[readPosition:readPosition + signatureLength]
|
||||||
|
try:
|
||||||
|
if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
||||||
|
print 'ECDSA verify failed'
|
||||||
|
return
|
||||||
|
print 'ECDSA verify passed'
|
||||||
|
except Exception as err:
|
||||||
|
print 'ECDSA verify failed', err
|
||||||
|
return
|
||||||
|
# verify passed
|
||||||
|
fromAddress = encodeAddress(
|
||||||
|
sendersAddressVersion, sendersStream, ripe.digest())
|
||||||
|
with shared.printLock:
|
||||||
|
print 'fromAddress:', fromAddress
|
||||||
|
|
||||||
|
# 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.)
|
||||||
|
sqlExecute(
|
||||||
|
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
||||||
|
ripe.digest(),
|
||||||
|
sendersAddressVersion,
|
||||||
|
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
||||||
|
int(time.time()),
|
||||||
|
'yes')
|
||||||
|
# This will check to see whether we happen to be awaiting this
|
||||||
|
# pubkey in order to send a message. If we are, it will do the
|
||||||
|
# POW and send it.
|
||||||
|
self.possibleNewPubkey(ripe=ripe.digest())
|
||||||
|
|
||||||
|
|
||||||
|
if messageEncodingType == 2:
|
||||||
|
subject, body = decodeType2Message(message)
|
||||||
|
elif messageEncodingType == 1:
|
||||||
|
body = message
|
||||||
|
subject = ''
|
||||||
|
elif messageEncodingType == 0:
|
||||||
|
print 'messageEncodingType == 0. Doing nothing with the message.'
|
||||||
|
else:
|
||||||
|
body = 'Unknown encoding type.\n\n' + repr(message)
|
||||||
|
subject = ''
|
||||||
|
|
||||||
|
toAddress = '[Broadcast subscribers]'
|
||||||
|
if messageEncodingType != 0:
|
||||||
|
|
||||||
|
t = (inventoryHash, toAddress, fromAddress, subject, int(
|
||||||
|
time.time()), body, 'inbox', messageEncodingType, 0)
|
||||||
|
helper_inbox.insert(t)
|
||||||
|
|
||||||
|
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
||||||
|
inventoryHash, toAddress, fromAddress, subject, body)))
|
||||||
|
|
||||||
|
# If we are behaving as an API then we might need to run an
|
||||||
|
# outside command to let some program know that a new
|
||||||
|
# message has arrived.
|
||||||
|
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
||||||
|
try:
|
||||||
|
apiNotifyPath = shared.config.get(
|
||||||
|
'bitmessagesettings', 'apinotifypath')
|
||||||
|
except:
|
||||||
|
apiNotifyPath = ''
|
||||||
|
if apiNotifyPath != '':
|
||||||
|
call([apiNotifyPath, "newBroadcast"])
|
||||||
|
|
||||||
|
# Display timing data
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
|
||||||
|
|
||||||
|
if broadcastVersion == 2:
|
||||||
|
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += cleartextStreamNumberLength
|
||||||
|
initialDecryptionSuccessful = False
|
||||||
|
for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items():
|
||||||
|
try:
|
||||||
|
decryptedData = cryptorObject.decrypt(data[readPosition:])
|
||||||
|
toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
|
||||||
|
initialDecryptionSuccessful = True
|
||||||
|
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
|
||||||
|
break
|
||||||
|
except Exception as err:
|
||||||
|
pass
|
||||||
|
# print 'cryptorObject.decrypt Exception:', err
|
||||||
|
if not initialDecryptionSuccessful:
|
||||||
|
# This is not a broadcast I am interested in.
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - messageProcessingStartTime, 'seconds.'
|
||||||
|
|
||||||
return
|
return
|
||||||
if sendersAddressVersionNumber > 4:
|
# At this point this is a broadcast I have decrypted and thus am
|
||||||
print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
|
# interested in.
|
||||||
|
signedBroadcastVersion, readPosition = decodeVarint(
|
||||||
|
decryptedData[:10])
|
||||||
|
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
||||||
|
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if sendersAddressVersion < 2 or sendersAddressVersion > 3:
|
||||||
|
print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
||||||
return
|
return
|
||||||
if len(decryptedData) < 170:
|
readPosition += sendersAddressVersionLength
|
||||||
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
|
sendersStream, sendersStreamLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if sendersStream != cleartextStreamNumber:
|
||||||
|
print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
|
||||||
return
|
return
|
||||||
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
|
readPosition += sendersStreamLength
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
if sendersStreamNumber == 0:
|
|
||||||
print 'sender\'s stream number is 0. Ignoring message.'
|
|
||||||
return
|
|
||||||
readPosition += sendersStreamNumberLength
|
|
||||||
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
||||||
readPosition += 4
|
readPosition += 4
|
||||||
pubSigningKey = '\x04' + decryptedData[
|
sendersPubSigningKey = '\x04' + \
|
||||||
readPosition:readPosition + 64]
|
decryptedData[readPosition:readPosition + 64]
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
pubEncryptionKey = '\x04' + decryptedData[
|
sendersPubEncryptionKey = '\x04' + \
|
||||||
readPosition:readPosition + 64]
|
decryptedData[readPosition:readPosition + 64]
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
if sendersAddressVersionNumber >= 3:
|
if sendersAddressVersion >= 3:
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decryptedData[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
|
@ -138,131 +852,81 @@ class objectProcessor(threading.Thread):
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decryptedData[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
||||||
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
|
endOfPubkeyPosition = readPosition
|
||||||
if toRipe != decryptedData[readPosition:readPosition + 20]:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
|
|
||||||
print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
|
|
||||||
print 'your toRipe:', toRipe.encode('hex')
|
|
||||||
print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
|
|
||||||
|
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
||||||
|
ripe = hashlib.new('ripemd160')
|
||||||
|
ripe.update(sha.digest())
|
||||||
|
|
||||||
|
if toRipe != ripe.digest():
|
||||||
|
print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
|
||||||
return
|
return
|
||||||
readPosition += 20
|
|
||||||
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if messageEncodingType == 0:
|
||||||
|
return
|
||||||
readPosition += messageEncodingTypeLength
|
readPosition += messageEncodingTypeLength
|
||||||
messageLength, messageLengthLength = decodeVarint(
|
messageLength, messageLengthLength = decodeVarint(
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decryptedData[readPosition:readPosition + 9])
|
||||||
readPosition += messageLengthLength
|
readPosition += messageLengthLength
|
||||||
message = decryptedData[readPosition:readPosition + messageLength]
|
message = decryptedData[readPosition:readPosition + messageLength]
|
||||||
# print 'First 150 characters of message:', repr(message[:150])
|
|
||||||
readPosition += messageLength
|
readPosition += messageLength
|
||||||
ackLength, ackLengthLength = decodeVarint(
|
readPositionAtBottomOfMessage = readPosition
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += ackLengthLength
|
|
||||||
ackData = decryptedData[readPosition:readPosition + ackLength]
|
|
||||||
readPosition += ackLength
|
|
||||||
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decryptedData[readPosition:readPosition + 9])
|
||||||
readPosition += signatureLengthLength
|
readPosition += signatureLengthLength
|
||||||
signature = decryptedData[
|
signature = decryptedData[
|
||||||
readPosition:readPosition + signatureLength]
|
readPosition:readPosition + signatureLength]
|
||||||
try:
|
try:
|
||||||
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
|
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
||||||
print 'ECDSA verify failed'
|
print 'ECDSA verify failed'
|
||||||
return
|
return
|
||||||
print 'ECDSA verify passed'
|
print 'ECDSA verify passed'
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print 'ECDSA verify failed', err
|
print 'ECDSA verify failed', err
|
||||||
return
|
return
|
||||||
with shared.printLock:
|
# verify passed
|
||||||
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
|
|
||||||
|
|
||||||
# calculate the fromRipe.
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(pubSigningKey + pubEncryptionKey)
|
|
||||||
ripe = hashlib.new('ripemd160')
|
|
||||||
ripe.update(sha.digest())
|
|
||||||
fromAddress = encodeAddress(
|
|
||||||
sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())
|
|
||||||
# Let's store the public key in case we want to reply to this
|
# Let's store the public key in case we want to reply to this
|
||||||
# person.
|
# person.
|
||||||
if sendersAddressVersionNumber <= 3:
|
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
||||||
sqlExecute(
|
ripe.digest(),
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
sendersAddressVersion,
|
||||||
ripe.digest(),
|
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
||||||
sendersAddressVersionNumber,
|
int(time.time()),
|
||||||
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
'yes')
|
||||||
int(time.time()),
|
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
|
||||||
'yes')
|
# This will check to see whether we happen to be awaiting this
|
||||||
# This will check to see whether we happen to be awaiting this
|
# pubkey in order to send a message. If we are, it will do the POW
|
||||||
# pubkey in order to send a message. If we are, it will do the POW
|
# and send it.
|
||||||
# and send it.
|
self.possibleNewPubkey(ripe=ripe.digest())
|
||||||
self.possibleNewPubkey(ripe=ripe.digest())
|
|
||||||
elif sendersAddressVersionNumber >= 4:
|
|
||||||
sqlExecute(
|
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
ripe.digest(),
|
|
||||||
sendersAddressVersionNumber,
|
|
||||||
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the POW
|
|
||||||
# and send it.
|
|
||||||
self.possibleNewPubkey(address = fromAddress)
|
|
||||||
# If this message is bound for one of my version 3 addresses (or
|
|
||||||
# higher), then we must check to make sure it meets our demanded
|
|
||||||
# proof of work requirement.
|
|
||||||
if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher:
|
|
||||||
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
|
|
||||||
requiredNonceTrialsPerByte = shared.config.getint(
|
|
||||||
toAddress, 'noncetrialsperbyte')
|
|
||||||
requiredPayloadLengthExtraBytes = shared.config.getint(
|
|
||||||
toAddress, 'payloadlengthextrabytes')
|
|
||||||
if not self.isProofOfWorkSufficient(data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
|
|
||||||
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
|
|
||||||
return
|
|
||||||
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
|
|
||||||
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
|
|
||||||
queryreturn = sqlQuery(
|
|
||||||
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
|
|
||||||
fromAddress)
|
|
||||||
if queryreturn != []:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Message ignored because address is in blacklist.'
|
|
||||||
|
|
||||||
blockMessage = True
|
fromAddress = encodeAddress(
|
||||||
else: # We're using a whitelist
|
sendersAddressVersion, sendersStream, ripe.digest())
|
||||||
queryreturn = sqlQuery(
|
with shared.printLock:
|
||||||
'''SELECT label FROM whitelist where address=? and enabled='1' ''',
|
print 'fromAddress:', fromAddress
|
||||||
fromAddress)
|
|
||||||
if queryreturn == []:
|
|
||||||
print 'Message ignored because address not in whitelist.'
|
|
||||||
blockMessage = True
|
|
||||||
if not blockMessage:
|
|
||||||
toLabel = shared.config.get(toAddress, 'label')
|
|
||||||
if toLabel == '':
|
|
||||||
toLabel = toAddress
|
|
||||||
|
|
||||||
if messageEncodingType == 2:
|
if messageEncodingType == 2:
|
||||||
subject, body = self.decodeType2Message(message)
|
subject, body = self.decodeType2Message(message)
|
||||||
elif messageEncodingType == 1:
|
elif messageEncodingType == 1:
|
||||||
body = message
|
body = message
|
||||||
subject = ''
|
subject = ''
|
||||||
elif messageEncodingType == 0:
|
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.'
|
print 'messageEncodingType == 0. Doing nothing with the message.'
|
||||||
else:
|
else:
|
||||||
body = 'Unknown encoding type.\n\n' + repr(message)
|
body = 'Unknown encoding type.\n\n' + repr(message)
|
||||||
subject = ''
|
subject = ''
|
||||||
if messageEncodingType != 0:
|
|
||||||
t = (inventoryHash, toAddress, fromAddress, subject, int(
|
|
||||||
time.time()), body, 'inbox', messageEncodingType, 0)
|
|
||||||
helper_inbox.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
toAddress = '[Broadcast subscribers]'
|
||||||
inventoryHash, toAddress, fromAddress, subject, body)))
|
if messageEncodingType != 0:
|
||||||
|
|
||||||
|
t = (inventoryHash, toAddress, fromAddress, subject, int(
|
||||||
|
time.time()), body, 'inbox', messageEncodingType, 0)
|
||||||
|
helper_inbox.insert(t)
|
||||||
|
|
||||||
|
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
||||||
|
inventoryHash, toAddress, fromAddress, subject, body)))
|
||||||
|
|
||||||
# If we are behaving as an API then we might need to run an
|
# If we are behaving as an API then we might need to run an
|
||||||
# outside command to let some program know that a new message
|
# outside command to let some program know that a new message
|
||||||
|
@ -274,52 +938,158 @@ class objectProcessor(threading.Thread):
|
||||||
except:
|
except:
|
||||||
apiNotifyPath = ''
|
apiNotifyPath = ''
|
||||||
if apiNotifyPath != '':
|
if apiNotifyPath != '':
|
||||||
call([apiNotifyPath, "newMessage"])
|
call([apiNotifyPath, "newBroadcast"])
|
||||||
|
|
||||||
# Let us now check and see whether our receiving address is
|
|
||||||
# behaving as a mailing list
|
|
||||||
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
|
|
||||||
try:
|
|
||||||
mailingListName = shared.config.get(
|
|
||||||
toAddress, 'mailinglistname')
|
|
||||||
except:
|
|
||||||
mailingListName = ''
|
|
||||||
# Let us send out this message as a broadcast
|
|
||||||
subject = self.addMailingListNameToSubject(
|
|
||||||
subject, mailingListName)
|
|
||||||
# Let us now send this message out as a broadcast
|
|
||||||
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
|
|
||||||
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
|
|
||||||
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
|
|
||||||
ackdata = OpenSSL.rand(
|
|
||||||
32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
|
|
||||||
toAddress = '[Broadcast subscribers]'
|
|
||||||
ripe = ''
|
|
||||||
|
|
||||||
t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
|
|
||||||
time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
|
|
||||||
helper_sent.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewSentMessage', (
|
|
||||||
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata)))
|
|
||||||
shared.workerQueue.put(('sendbroadcast', ''))
|
|
||||||
|
|
||||||
if self.isAckDataValid(ackData):
|
|
||||||
print 'ackData is valid. Will process it.'
|
|
||||||
#self.ackDataThatWeHaveYetToSend.append(
|
|
||||||
# ackData) # When we have processed all data, the processData function will pop the ackData out and process it as if it is a message received from our peer.
|
|
||||||
shared.objectProcessorQueue.put(ackData)
|
|
||||||
# Display timing data
|
# Display timing data
|
||||||
timeRequiredToAttemptToDecryptMessage = time.time(
|
|
||||||
) - self.messageProcessingStartTime
|
|
||||||
shared.successfullyDecryptMessageTimings.append(
|
|
||||||
timeRequiredToAttemptToDecryptMessage)
|
|
||||||
sum = 0
|
|
||||||
for item in shared.successfullyDecryptMessageTimings:
|
|
||||||
sum += item
|
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
|
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
|
||||||
print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
|
|
||||||
|
if broadcastVersion == 3:
|
||||||
|
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += cleartextStreamNumberLength
|
||||||
|
embeddedTag = data[readPosition:readPosition+32]
|
||||||
|
readPosition += 32
|
||||||
|
if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'We\'re not interested in this broadcast.'
|
||||||
|
return
|
||||||
|
# We are interested in this broadcast because of its tag.
|
||||||
|
cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
|
||||||
|
try:
|
||||||
|
decryptedData = cryptorObject.decrypt(data[readPosition:])
|
||||||
|
print 'EC decryption successful'
|
||||||
|
except Exception as err:
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Broadcast version 3 decryption Unsuccessful.'
|
||||||
|
return
|
||||||
|
|
||||||
|
signedBroadcastVersion, readPosition = decodeVarint(
|
||||||
|
decryptedData[:10])
|
||||||
|
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
||||||
|
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if sendersAddressVersion < 4:
|
||||||
|
print 'Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
||||||
|
return
|
||||||
|
readPosition += sendersAddressVersionLength
|
||||||
|
sendersStream, sendersStreamLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if sendersStream != cleartextStreamNumber:
|
||||||
|
print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
|
||||||
|
return
|
||||||
|
readPosition += sendersStreamLength
|
||||||
|
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
||||||
|
readPosition += 4
|
||||||
|
sendersPubSigningKey = '\x04' + \
|
||||||
|
decryptedData[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
sendersPubEncryptionKey = '\x04' + \
|
||||||
|
decryptedData[readPosition:readPosition + 64]
|
||||||
|
readPosition += 64
|
||||||
|
if sendersAddressVersion >= 3:
|
||||||
|
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
|
||||||
|
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
||||||
|
endOfPubkeyPosition = readPosition
|
||||||
|
|
||||||
|
sha = hashlib.new('sha512')
|
||||||
|
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
||||||
|
ripeHasher = hashlib.new('ripemd160')
|
||||||
|
ripeHasher.update(sha.digest())
|
||||||
|
calculatedRipe = ripeHasher.digest()
|
||||||
|
|
||||||
|
calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
||||||
|
sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
|
||||||
|
if calculatedTag != embeddedTag:
|
||||||
|
print 'The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
|
||||||
|
return
|
||||||
|
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
if messageEncodingType == 0:
|
||||||
|
return
|
||||||
|
readPosition += messageEncodingTypeLength
|
||||||
|
messageLength, messageLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
readPosition += messageLengthLength
|
||||||
|
message = decryptedData[readPosition:readPosition + messageLength]
|
||||||
|
readPosition += messageLength
|
||||||
|
readPositionAtBottomOfMessage = readPosition
|
||||||
|
signatureLength, signatureLengthLength = decodeVarint(
|
||||||
|
decryptedData[readPosition:readPosition + 9])
|
||||||
|
readPosition += signatureLengthLength
|
||||||
|
signature = decryptedData[
|
||||||
|
readPosition:readPosition + signatureLength]
|
||||||
|
try:
|
||||||
|
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
||||||
|
print 'ECDSA verify failed'
|
||||||
|
return
|
||||||
|
print 'ECDSA verify passed'
|
||||||
|
except Exception as err:
|
||||||
|
print 'ECDSA verify failed', err
|
||||||
|
return
|
||||||
|
# verify passed
|
||||||
|
|
||||||
|
fromAddress = encodeAddress(
|
||||||
|
sendersAddressVersion, sendersStream, calculatedRipe)
|
||||||
|
with shared.printLock:
|
||||||
|
print 'fromAddress:', fromAddress
|
||||||
|
|
||||||
|
# Let's store the public key in case we want to reply to this person.
|
||||||
|
sqlExecute(
|
||||||
|
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
||||||
|
calculatedRipe,
|
||||||
|
sendersAddressVersion,
|
||||||
|
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
||||||
|
int(time.time()),
|
||||||
|
'yes')
|
||||||
|
# This will check to see whether we happen to be awaiting this
|
||||||
|
# pubkey in order to send a message. If we are, it will do the
|
||||||
|
# POW and send it.
|
||||||
|
self.possibleNewPubkey(address = fromAddress)
|
||||||
|
|
||||||
|
if messageEncodingType == 2:
|
||||||
|
subject, body = self.decodeType2Message(message)
|
||||||
|
elif messageEncodingType == 1:
|
||||||
|
body = message
|
||||||
|
subject = ''
|
||||||
|
elif messageEncodingType == 0:
|
||||||
|
print 'messageEncodingType == 0. Doing nothing with the message.'
|
||||||
|
else:
|
||||||
|
body = 'Unknown encoding type.\n\n' + repr(message)
|
||||||
|
subject = ''
|
||||||
|
|
||||||
|
toAddress = '[Broadcast subscribers]'
|
||||||
|
if messageEncodingType != 0:
|
||||||
|
|
||||||
|
t = (inventoryHash, toAddress, fromAddress, subject, int(
|
||||||
|
time.time()), body, 'inbox', messageEncodingType, 0)
|
||||||
|
helper_inbox.insert(t)
|
||||||
|
|
||||||
|
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
||||||
|
inventoryHash, toAddress, fromAddress, subject, body)))
|
||||||
|
|
||||||
|
# If we are behaving as an API then we might need to run an
|
||||||
|
# outside command to let some program know that a new message
|
||||||
|
# has arrived.
|
||||||
|
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
||||||
|
try:
|
||||||
|
apiNotifyPath = shared.config.get(
|
||||||
|
'bitmessagesettings', 'apinotifypath')
|
||||||
|
except:
|
||||||
|
apiNotifyPath = ''
|
||||||
|
if apiNotifyPath != '':
|
||||||
|
call([apiNotifyPath, "newBroadcast"])
|
||||||
|
|
||||||
|
# Display timing data
|
||||||
|
with shared.printLock:
|
||||||
|
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
|
||||||
|
|
||||||
|
|
||||||
# We have inserted a pubkey into our pubkey table which we received from a
|
# We have inserted a pubkey into our pubkey table which we received from a
|
||||||
# pubkey, msg, or broadcast message. It might be one that we have been
|
# pubkey, msg, or broadcast message. It might be one that we have been
|
||||||
|
@ -352,7 +1122,7 @@ class objectProcessor(threading.Thread):
|
||||||
ripe)
|
ripe)
|
||||||
shared.workerQueue.put(('sendmessage', ''))
|
shared.workerQueue.put(('sendmessage', ''))
|
||||||
|
|
||||||
def isAckDataValid(self, ackData):
|
def ackDataHasAVaildHeader(self, ackData):
|
||||||
if len(ackData) < 24:
|
if len(ackData) < 24:
|
||||||
print 'The length of ackData is unreasonably short. Not sending ackData.'
|
print 'The length of ackData is unreasonably short. Not sending ackData.'
|
||||||
return False
|
return False
|
||||||
|
@ -363,48 +1133,16 @@ class objectProcessor(threading.Thread):
|
||||||
if len(ackData) - 24 != ackDataPayloadLength:
|
if len(ackData) - 24 != ackDataPayloadLength:
|
||||||
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
|
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
|
||||||
return False
|
return False
|
||||||
if ackData[4:16] != 'getpubkey\x00\x00\x00' and ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'broadcast\x00\x00\x00':
|
if ackData[20:24] != hashlib.sha512(ackData[24:]).digest()[0:4]: # test the checksum in the message.
|
||||||
|
print '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] != 'getpubkey\x00\x00\x00' and
|
||||||
|
ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and
|
||||||
|
ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and
|
||||||
|
ackData[4:16] != 'broadcast\x00\x00\x00'):
|
||||||
return False
|
return False
|
||||||
readPosition = 24 # bypass the network header
|
|
||||||
if not shared.isProofOfWorkSufficient(ackData[readPosition:readPosition+10]):
|
|
||||||
print 'Proof of work in msg message insufficient.'
|
|
||||||
return
|
|
||||||
|
|
||||||
readPosition += 8 # bypass the POW nonce
|
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
|
||||||
# time in the protocol.
|
|
||||||
if embeddedTime == 0:
|
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
|
||||||
readPosition += 8
|
|
||||||
else:
|
|
||||||
readPosition += 4
|
|
||||||
|
|
||||||
if embeddedTime > int(time.time()) + 10800:
|
|
||||||
print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime
|
|
||||||
return
|
|
||||||
if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept:
|
|
||||||
print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime
|
|
||||||
return
|
|
||||||
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
if not streamNumberAsClaimedByMsg in shared.streamsInWhichIAmParticipating:
|
|
||||||
print 'The stream number encoded in this msg (' + str(streamNumberAsClaimedByMsg) + ') message does not match a stream number on which it was received. Ignoring it.'
|
|
||||||
return
|
|
||||||
readPosition += streamNumberAsClaimedByMsgLength
|
|
||||||
self.inventoryHash = calculateInventoryHash(data)
|
|
||||||
shared.numberOfInventoryLookupsPerformed += 1
|
|
||||||
shared.inventoryLock.acquire()
|
|
||||||
if self.inventoryHash in shared.inventory:
|
|
||||||
print 'We have already received this msg message. Ignoring.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
elif shared.isInSqlInventory(self.inventoryHash):
|
|
||||||
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
##################
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def decodeType2Message(self, message):
|
def decodeType2Message(self, message):
|
||||||
|
@ -430,4 +1168,20 @@ class objectProcessor(threading.Thread):
|
||||||
if '[' + mailingListName + ']' in subject:
|
if '[' + mailingListName + ']' in subject:
|
||||||
return subject
|
return subject
|
||||||
else:
|
else:
|
||||||
return '[' + mailingListName + '] ' + subject
|
return '[' + mailingListName + '] ' + subject
|
||||||
|
|
||||||
|
def decodeType2Message(self, message):
|
||||||
|
bodyPositionIndex = string.find(message, '\nBody:')
|
||||||
|
if bodyPositionIndex > 1:
|
||||||
|
subject = message[8:bodyPositionIndex]
|
||||||
|
# Only save and show the first 500 characters of the subject.
|
||||||
|
# Any more is probably an attack.
|
||||||
|
subject = subject[:500]
|
||||||
|
body = message[bodyPositionIndex + 6:]
|
||||||
|
else:
|
||||||
|
subject = ''
|
||||||
|
body = message
|
||||||
|
# Throw away any extra lines (headers) after the subject.
|
||||||
|
if subject:
|
||||||
|
subject = subject.splitlines()[0]
|
||||||
|
return subject, body
|
|
@ -8,23 +8,23 @@ import socket
|
||||||
import random
|
import random
|
||||||
from struct import unpack, pack
|
from struct import unpack, pack
|
||||||
import sys
|
import sys
|
||||||
import string
|
#import string
|
||||||
from subprocess import call # used when the API must execute an outside program
|
#from subprocess import call # used when the API must execute an outside program
|
||||||
from pyelliptic.openssl import OpenSSL
|
#from pyelliptic.openssl import OpenSSL
|
||||||
|
|
||||||
import highlevelcrypto
|
#import highlevelcrypto
|
||||||
from addresses import *
|
from addresses import *
|
||||||
import helper_generic
|
import helper_generic
|
||||||
import helper_bitcoin
|
#import helper_bitcoin
|
||||||
import helper_inbox
|
#import helper_inbox
|
||||||
import helper_sent
|
#import helper_sent
|
||||||
from helper_sql import *
|
from helper_sql import *
|
||||||
import tr
|
#import tr
|
||||||
from debug import logger
|
from debug import logger
|
||||||
#from bitmessagemain import shared.lengthOfTimeToLeaveObjectsInInventory, shared.lengthOfTimeToHoldOnToAllPubkeys, shared.maximumAgeOfAnObjectThatIAmWillingToAccept, shared.maximumAgeOfObjectsThatIAdvertiseToOthers, shared.maximumAgeOfNodesThatIAdvertiseToOthers, shared.numberOfObjectsThatWeHaveYetToGetPerPeer, shared.neededPubkeys
|
#from bitmessagemain import shared.lengthOfTimeToLeaveObjectsInInventory, shared.lengthOfTimeToHoldOnToAllPubkeys, shared.maximumAgeOfAnObjectThatIAmWillingToAccept, shared.maximumAgeOfObjectsThatIAdvertiseToOthers, shared.maximumAgeOfNodesThatIAdvertiseToOthers, shared.numberOfObjectsThatWeHaveYetToGetPerPeer, shared.neededPubkeys
|
||||||
|
|
||||||
# This thread is created either by the synSenderThread(for outgoing
|
# This thread is created either by the synSenderThread(for outgoing
|
||||||
# connections) or the singleListenerThread(for incoming connectiosn).
|
# connections) or the singleListenerThread(for incoming connections).
|
||||||
|
|
||||||
class receiveDataThread(threading.Thread):
|
class receiveDataThread(threading.Thread):
|
||||||
|
|
||||||
|
@ -56,8 +56,6 @@ class receiveDataThread(threading.Thread):
|
||||||
else:
|
else:
|
||||||
self.initiatedConnection = True
|
self.initiatedConnection = True
|
||||||
self.selfInitiatedConnections[streamNumber][self] = 0
|
self.selfInitiatedConnections[streamNumber][self] = 0
|
||||||
self.ackDataThatWeHaveYetToSend = [
|
|
||||||
] # When we receive a message bound for us, we store the acknowledgement that we need to send (the ackdata) here until we are done processing all other data received from this peer.
|
|
||||||
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware
|
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
|
@ -71,12 +69,10 @@ class receiveDataThread(threading.Thread):
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Timeout occurred waiting for data from', self.peer, '. Closing receiveData thread. (ID:', str(id(self)) + ')'
|
print 'Timeout occurred waiting for data from', self.peer, '. Closing receiveData thread. (ID:', str(id(self)) + ')'
|
||||||
|
|
||||||
break
|
break
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'sock.recv error. Closing receiveData thread (HOST:', self.peer, 'ID:', str(id(self)) + ').', err
|
print 'sock.recv error. Closing receiveData thread (HOST:', self.peer, 'ID:', str(id(self)) + ').', err
|
||||||
|
|
||||||
break
|
break
|
||||||
# print 'Received', repr(self.data)
|
# print 'Received', repr(self.data)
|
||||||
if len(self.data) == dataLen: # If self.sock.recv returned no data:
|
if len(self.data) == dataLen: # If self.sock.recv returned no data:
|
||||||
|
@ -92,7 +88,7 @@ class receiveDataThread(threading.Thread):
|
||||||
print 'removed self (a receiveDataThread) from selfInitiatedConnections'
|
print 'removed self (a receiveDataThread) from selfInitiatedConnections'
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer)) # commands the corresponding sendDataThread to shut itself down.
|
||||||
try:
|
try:
|
||||||
del shared.connectedHostsList[self.peer.host]
|
del shared.connectedHostsList[self.peer.host]
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
|
@ -114,7 +110,7 @@ class receiveDataThread(threading.Thread):
|
||||||
# with shared.printLock:
|
# with shared.printLock:
|
||||||
# print 'self.data is currently ', repr(self.data)
|
# print 'self.data is currently ', repr(self.data)
|
||||||
#
|
#
|
||||||
if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length
|
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.
|
||||||
return
|
return
|
||||||
if self.data[0:4] != '\xe9\xbe\xb4\xd9':
|
if self.data[0:4] != '\xe9\xbe\xb4\xd9':
|
||||||
if shared.verbose >= 1:
|
if shared.verbose >= 1:
|
||||||
|
@ -150,7 +146,7 @@ class receiveDataThread(threading.Thread):
|
||||||
elif remoteCommand == 'addr\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'addr\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recaddr(self.data[24:self.payloadLength + 24])
|
self.recaddr(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'getpubkey\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'getpubkey\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recgetpubkey(self.data[24:self.payloadLength + 24])
|
shared.checkAndSharegetpubkeyWithPeers(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'pubkey\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'pubkey\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recpubkey(self.data[24:self.payloadLength + 24])
|
self.recpubkey(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
|
@ -158,7 +154,7 @@ class receiveDataThread(threading.Thread):
|
||||||
elif remoteCommand == 'getdata\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'getdata\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recgetdata(self.data[24:self.payloadLength + 24])
|
self.recgetdata(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recmsg(self.data[:self.payloadLength + 24])
|
self.recmsg(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'broadcast\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'broadcast\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
self.recbroadcast(self.data[24:self.payloadLength + 24])
|
self.recbroadcast(self.data[24:self.payloadLength + 24])
|
||||||
elif remoteCommand == 'ping\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
elif remoteCommand == 'ping\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
|
||||||
|
@ -191,7 +187,7 @@ class receiveDataThread(threading.Thread):
|
||||||
else:
|
else:
|
||||||
self.sendgetdata(objectHash)
|
self.sendgetdata(objectHash)
|
||||||
del self.objectsThatWeHaveYetToGetFromThisPeer[
|
del self.objectsThatWeHaveYetToGetFromThisPeer[
|
||||||
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.
|
objectHash] # It is possible that the remote node might not respond with the object. In that case, we'll very likely get it from someone else anyway.
|
||||||
if len(self.objectsThatWeHaveYetToGetFromThisPeer) == 0:
|
if len(self.objectsThatWeHaveYetToGetFromThisPeer) == 0:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now', len(self.objectsThatWeHaveYetToGetFromThisPeer)
|
print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now', len(self.objectsThatWeHaveYetToGetFromThisPeer)
|
||||||
|
@ -217,8 +213,6 @@ class receiveDataThread(threading.Thread):
|
||||||
|
|
||||||
shared.numberOfObjectsThatWeHaveYetToGetPerPeer[self.peer] = len(
|
shared.numberOfObjectsThatWeHaveYetToGetPerPeer[self.peer] = len(
|
||||||
self.objectsThatWeHaveYetToGetFromThisPeer) # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
|
self.objectsThatWeHaveYetToGetFromThisPeer) # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
|
||||||
if len(self.ackDataThatWeHaveYetToSend) > 0:
|
|
||||||
self.data = self.ackDataThatWeHaveYetToSend.pop()
|
|
||||||
self.processData()
|
self.processData()
|
||||||
|
|
||||||
|
|
||||||
|
@ -254,8 +248,7 @@ class receiveDataThread(threading.Thread):
|
||||||
print 'The length of sendDataQueues is now:', len(shared.sendDataQueues)
|
print 'The length of sendDataQueues is now:', len(shared.sendDataQueues)
|
||||||
print 'broadcasting addr from within connectionFullyEstablished function.'
|
print 'broadcasting addr from within connectionFullyEstablished function.'
|
||||||
|
|
||||||
#self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.peer.host,
|
# Let all of our peers know about this new node.
|
||||||
# self.remoteNodeIncomingPort)]) # This lets all of our peers know about this new node.
|
|
||||||
dataToSend = (int(time.time()), self.streamNumber, 1, self.peer.host, self.remoteNodeIncomingPort)
|
dataToSend = (int(time.time()), self.streamNumber, 1, self.peer.host, self.remoteNodeIncomingPort)
|
||||||
shared.broadcastToSendDataQueues((
|
shared.broadcastToSendDataQueues((
|
||||||
self.streamNumber, 'advertisepeer', dataToSend))
|
self.streamNumber, 'advertisepeer', dataToSend))
|
||||||
|
@ -328,71 +321,19 @@ class receiveDataThread(threading.Thread):
|
||||||
# We have received a broadcast message
|
# We have received a broadcast message
|
||||||
def recbroadcast(self, data):
|
def recbroadcast(self, data):
|
||||||
self.messageProcessingStartTime = time.time()
|
self.messageProcessingStartTime = time.time()
|
||||||
# First we must check to make sure the proof of work is sufficient.
|
|
||||||
if not shared.isProofOfWorkSufficient(data):
|
|
||||||
print 'Proof of work in broadcast message insufficient.'
|
|
||||||
return
|
|
||||||
readPosition = 8 # bypass the nonce
|
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
shared.checkAndShareBroadcastWithPeers(data)
|
||||||
# time in the protocol.
|
|
||||||
if embeddedTime == 0:
|
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
|
||||||
readPosition += 8
|
|
||||||
else:
|
|
||||||
readPosition += 4
|
|
||||||
|
|
||||||
if embeddedTime > (int(time.time()) + 10800): # prevent funny business
|
"""
|
||||||
print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.'
|
Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. Sleeping
|
||||||
return
|
will help guarantee that we can process messages faster than a remote
|
||||||
if embeddedTime < (int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept):
|
node can send them. If we fall behind, the attacker could observe that
|
||||||
print 'The embedded time in this broadcast message is too old. Ignoring message.'
|
we are are slowing down the rate at which we request objects from the
|
||||||
return
|
network which would indicate that we own a particular address (whichever
|
||||||
if len(data) < 180:
|
one to which they are sending all of their attack messages). Note
|
||||||
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
|
that if an attacker connects to a target with many connections, this
|
||||||
return
|
mitigation mechanism might not be sufficient.
|
||||||
# Let us check to make sure the stream number is correct (thus
|
"""
|
||||||
# preventing an individual from sending broadcasts out on the wrong
|
|
||||||
# streams or all streams).
|
|
||||||
broadcastVersion, broadcastVersionLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
if broadcastVersion >= 2:
|
|
||||||
streamNumber, streamNumberLength = decodeVarint(data[
|
|
||||||
readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10])
|
|
||||||
if streamNumber != self.streamNumber:
|
|
||||||
print 'The stream number encoded in this broadcast message (' + str(streamNumber) + ') does not match the stream number on which it was received. Ignoring it.'
|
|
||||||
return
|
|
||||||
|
|
||||||
shared.numberOfInventoryLookupsPerformed += 1
|
|
||||||
shared.inventoryLock.acquire()
|
|
||||||
self.inventoryHash = calculateInventoryHash(data)
|
|
||||||
if self.inventoryHash in shared.inventory:
|
|
||||||
print 'We have already received this broadcast object. Ignoring.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
elif shared.isInSqlInventory(self.inventoryHash):
|
|
||||||
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
# It is valid so far. Let's let our peers know about it.
|
|
||||||
objectType = 'broadcast'
|
|
||||||
shared.inventory[self.inventoryHash] = (
|
|
||||||
objectType, self.streamNumber, data, embeddedTime,'')
|
|
||||||
shared.inventorySets[self.streamNumber].add(self.inventoryHash)
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
self.broadcastinv(self.inventoryHash)
|
|
||||||
shared.numberOfBroadcastsProcessed += 1
|
|
||||||
shared.UISignalQueue.put((
|
|
||||||
'updateNumberOfBroadcastsProcessed', 'no data'))
|
|
||||||
|
|
||||||
self.processbroadcast(
|
|
||||||
readPosition, data) # When this function returns, we will have either successfully processed this broadcast because we are interested in it, ignored it because we aren't interested in it, or found problem with the broadcast that warranted ignoring it.
|
|
||||||
|
|
||||||
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
|
|
||||||
# haven't used the specified amount of time, we shall sleep. These
|
|
||||||
# values are mostly the same values used for msg messages although
|
|
||||||
# broadcast messages are processed faster.
|
|
||||||
if len(data) > 100000000: # Size is greater than 100 megabytes
|
if len(data) > 100000000: # Size is greater than 100 megabytes
|
||||||
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds.
|
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds.
|
||||||
elif len(data) > 10000000: # Between 100 and 10 megabytes
|
elif len(data) > 10000000: # Between 100 and 10 megabytes
|
||||||
|
@ -407,505 +348,24 @@ class receiveDataThread(threading.Thread):
|
||||||
if sleepTime > 0 and doTimingAttackMitigation:
|
if sleepTime > 0 and doTimingAttackMitigation:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
||||||
|
|
||||||
time.sleep(sleepTime)
|
time.sleep(sleepTime)
|
||||||
with shared.printLock:
|
|
||||||
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
|
|
||||||
|
|
||||||
|
|
||||||
# A broadcast message has a valid time and POW and requires processing.
|
|
||||||
# The recbroadcast function calls this one.
|
|
||||||
def processbroadcast(self, readPosition, data):
|
|
||||||
broadcastVersion, broadcastVersionLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
readPosition += broadcastVersionLength
|
|
||||||
if broadcastVersion < 1 or broadcastVersion > 3:
|
|
||||||
print 'Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
|
||||||
return
|
|
||||||
if broadcastVersion == 1:
|
|
||||||
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
|
||||||
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
if sendersAddressVersion <= 1 or sendersAddressVersion >= 3:
|
|
||||||
# Cannot decode senderAddressVersion higher than 2. Assuming
|
|
||||||
# the sender isn\'t being silly, you should upgrade Bitmessage
|
|
||||||
# because this message shall be ignored.
|
|
||||||
return
|
|
||||||
readPosition += sendersAddressVersionLength
|
|
||||||
if sendersAddressVersion == 2:
|
|
||||||
sendersStream, sendersStreamLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
readPosition += sendersStreamLength
|
|
||||||
behaviorBitfield = data[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
sendersPubSigningKey = '\x04' + \
|
|
||||||
data[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
sendersPubEncryptionKey = '\x04' + \
|
|
||||||
data[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
endOfPubkeyPosition = readPosition
|
|
||||||
sendersHash = data[readPosition:readPosition + 20]
|
|
||||||
if sendersHash not in shared.broadcastSendersForWhichImWatching:
|
|
||||||
# Display timing data
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime
|
|
||||||
|
|
||||||
return
|
|
||||||
# At this point, this message claims to be from sendersHash and
|
|
||||||
# we are interested in it. We still have to hash the public key
|
|
||||||
# to make sure it is truly the key that matches the hash, and
|
|
||||||
# also check the signiture.
|
|
||||||
readPosition += 20
|
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
|
||||||
ripe = hashlib.new('ripemd160')
|
|
||||||
ripe.update(sha.digest())
|
|
||||||
if ripe.digest() != sendersHash:
|
|
||||||
# The sender of this message lied.
|
|
||||||
return
|
|
||||||
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
if messageEncodingType == 0:
|
|
||||||
return
|
|
||||||
readPosition += messageEncodingTypeLength
|
|
||||||
messageLength, messageLengthLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
readPosition += messageLengthLength
|
|
||||||
message = data[readPosition:readPosition + messageLength]
|
|
||||||
readPosition += messageLength
|
|
||||||
readPositionAtBottomOfMessage = readPosition
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = data[readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed', err
|
|
||||||
return
|
|
||||||
# verify passed
|
|
||||||
fromAddress = encodeAddress(
|
|
||||||
sendersAddressVersion, sendersStream, ripe.digest())
|
|
||||||
with shared.printLock:
|
|
||||||
print 'fromAddress:', fromAddress
|
|
||||||
|
|
||||||
# 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.)
|
|
||||||
sqlExecute(
|
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
ripe.digest(),
|
|
||||||
sendersAddressVersion,
|
|
||||||
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the
|
|
||||||
# POW and send it.
|
|
||||||
self.possibleNewPubkey(ripe=ripe.digest())
|
|
||||||
|
|
||||||
|
|
||||||
if messageEncodingType == 2:
|
|
||||||
subject, body = self.decodeType2Message(message)
|
|
||||||
elif messageEncodingType == 1:
|
|
||||||
body = message
|
|
||||||
subject = ''
|
|
||||||
elif messageEncodingType == 0:
|
|
||||||
print 'messageEncodingType == 0. Doing nothing with the message.'
|
|
||||||
else:
|
|
||||||
body = 'Unknown encoding type.\n\n' + repr(message)
|
|
||||||
subject = ''
|
|
||||||
|
|
||||||
toAddress = '[Broadcast subscribers]'
|
|
||||||
if messageEncodingType != 0:
|
|
||||||
|
|
||||||
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
|
|
||||||
time.time()), body, 'inbox', messageEncodingType, 0)
|
|
||||||
helper_inbox.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
|
||||||
self.inventoryHash, toAddress, fromAddress, subject, body)))
|
|
||||||
|
|
||||||
# If we are behaving as an API then we might need to run an
|
|
||||||
# outside command to let some program know that a new
|
|
||||||
# message has arrived.
|
|
||||||
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
|
||||||
try:
|
|
||||||
apiNotifyPath = shared.config.get(
|
|
||||||
'bitmessagesettings', 'apinotifypath')
|
|
||||||
except:
|
|
||||||
apiNotifyPath = ''
|
|
||||||
if apiNotifyPath != '':
|
|
||||||
call([apiNotifyPath, "newBroadcast"])
|
|
||||||
|
|
||||||
# Display timing data
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
|
|
||||||
|
|
||||||
if broadcastVersion == 2:
|
|
||||||
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += cleartextStreamNumberLength
|
|
||||||
initialDecryptionSuccessful = False
|
|
||||||
for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items():
|
|
||||||
try:
|
|
||||||
decryptedData = cryptorObject.decrypt(data[readPosition:])
|
|
||||||
toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
|
|
||||||
initialDecryptionSuccessful = True
|
|
||||||
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
|
|
||||||
break
|
|
||||||
except Exception as err:
|
|
||||||
pass
|
|
||||||
# print 'cryptorObject.decrypt Exception:', err
|
|
||||||
if not initialDecryptionSuccessful:
|
|
||||||
# This is not a broadcast I am interested in.
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.'
|
|
||||||
|
|
||||||
return
|
|
||||||
# At this point this is a broadcast I have decrypted and thus am
|
|
||||||
# interested in.
|
|
||||||
signedBroadcastVersion, readPosition = decodeVarint(
|
|
||||||
decryptedData[:10])
|
|
||||||
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
|
||||||
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if sendersAddressVersion < 2 or sendersAddressVersion > 3:
|
|
||||||
print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
|
||||||
return
|
|
||||||
readPosition += sendersAddressVersionLength
|
|
||||||
sendersStream, sendersStreamLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if sendersStream != cleartextStreamNumber:
|
|
||||||
print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
|
|
||||||
return
|
|
||||||
readPosition += sendersStreamLength
|
|
||||||
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
sendersPubSigningKey = '\x04' + \
|
|
||||||
decryptedData[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
sendersPubEncryptionKey = '\x04' + \
|
|
||||||
decryptedData[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
if sendersAddressVersion >= 3:
|
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
|
|
||||||
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
|
||||||
endOfPubkeyPosition = readPosition
|
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
|
||||||
ripe = hashlib.new('ripemd160')
|
|
||||||
ripe.update(sha.digest())
|
|
||||||
|
|
||||||
if toRipe != ripe.digest():
|
|
||||||
print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
|
|
||||||
return
|
|
||||||
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if messageEncodingType == 0:
|
|
||||||
return
|
|
||||||
readPosition += messageEncodingTypeLength
|
|
||||||
messageLength, messageLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
readPosition += messageLengthLength
|
|
||||||
message = decryptedData[readPosition:readPosition + messageLength]
|
|
||||||
readPosition += messageLength
|
|
||||||
readPositionAtBottomOfMessage = readPosition
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = decryptedData[
|
|
||||||
readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed', err
|
|
||||||
return
|
|
||||||
# verify passed
|
|
||||||
|
|
||||||
# Let's store the public key in case we want to reply to this
|
|
||||||
# person.
|
|
||||||
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
ripe.digest(),
|
|
||||||
sendersAddressVersion,
|
|
||||||
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the POW
|
|
||||||
# and send it.
|
|
||||||
self.possibleNewPubkey(ripe=ripe.digest())
|
|
||||||
|
|
||||||
fromAddress = encodeAddress(
|
|
||||||
sendersAddressVersion, sendersStream, ripe.digest())
|
|
||||||
with shared.printLock:
|
|
||||||
print 'fromAddress:', fromAddress
|
|
||||||
|
|
||||||
if messageEncodingType == 2:
|
|
||||||
subject, body = self.decodeType2Message(message)
|
|
||||||
elif messageEncodingType == 1:
|
|
||||||
body = message
|
|
||||||
subject = ''
|
|
||||||
elif messageEncodingType == 0:
|
|
||||||
print 'messageEncodingType == 0. Doing nothing with the message.'
|
|
||||||
else:
|
|
||||||
body = 'Unknown encoding type.\n\n' + repr(message)
|
|
||||||
subject = ''
|
|
||||||
|
|
||||||
toAddress = '[Broadcast subscribers]'
|
|
||||||
if messageEncodingType != 0:
|
|
||||||
|
|
||||||
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
|
|
||||||
time.time()), body, 'inbox', messageEncodingType, 0)
|
|
||||||
helper_inbox.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
|
||||||
self.inventoryHash, toAddress, fromAddress, subject, body)))
|
|
||||||
|
|
||||||
# If we are behaving as an API then we might need to run an
|
|
||||||
# outside command to let some program know that a new message
|
|
||||||
# has arrived.
|
|
||||||
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
|
||||||
try:
|
|
||||||
apiNotifyPath = shared.config.get(
|
|
||||||
'bitmessagesettings', 'apinotifypath')
|
|
||||||
except:
|
|
||||||
apiNotifyPath = ''
|
|
||||||
if apiNotifyPath != '':
|
|
||||||
call([apiNotifyPath, "newBroadcast"])
|
|
||||||
|
|
||||||
# Display timing data
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
|
|
||||||
|
|
||||||
if broadcastVersion == 3:
|
|
||||||
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += cleartextStreamNumberLength
|
|
||||||
embeddedTag = data[readPosition:readPosition+32]
|
|
||||||
readPosition += 32
|
|
||||||
if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'We\'re not interested in this broadcast.'
|
|
||||||
return
|
|
||||||
# We are interested in this broadcast because of its tag.
|
|
||||||
cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
|
|
||||||
try:
|
|
||||||
decryptedData = cryptorObject.decrypt(data[readPosition:])
|
|
||||||
print 'EC decryption successful'
|
|
||||||
except Exception as err:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Broadcast version 3 decryption Unsuccessful.'
|
|
||||||
return
|
|
||||||
|
|
||||||
signedBroadcastVersion, readPosition = decodeVarint(
|
|
||||||
decryptedData[:10])
|
|
||||||
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
|
|
||||||
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if sendersAddressVersion < 4:
|
|
||||||
print 'Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
|
|
||||||
return
|
|
||||||
readPosition += sendersAddressVersionLength
|
|
||||||
sendersStream, sendersStreamLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if sendersStream != cleartextStreamNumber:
|
|
||||||
print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
|
|
||||||
return
|
|
||||||
readPosition += sendersStreamLength
|
|
||||||
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
sendersPubSigningKey = '\x04' + \
|
|
||||||
decryptedData[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
sendersPubEncryptionKey = '\x04' + \
|
|
||||||
decryptedData[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
if sendersAddressVersion >= 3:
|
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
|
|
||||||
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
|
||||||
endOfPubkeyPosition = readPosition
|
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
|
|
||||||
ripeHasher = hashlib.new('ripemd160')
|
|
||||||
ripeHasher.update(sha.digest())
|
|
||||||
calculatedRipe = ripeHasher.digest()
|
|
||||||
|
|
||||||
calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
|
||||||
sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
|
|
||||||
if calculatedTag != embeddedTag:
|
|
||||||
print 'The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
|
|
||||||
return
|
|
||||||
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
if messageEncodingType == 0:
|
|
||||||
return
|
|
||||||
readPosition += messageEncodingTypeLength
|
|
||||||
messageLength, messageLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
readPosition += messageLengthLength
|
|
||||||
message = decryptedData[readPosition:readPosition + messageLength]
|
|
||||||
readPosition += messageLength
|
|
||||||
readPositionAtBottomOfMessage = readPosition
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 9])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = decryptedData[
|
|
||||||
readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed', err
|
|
||||||
return
|
|
||||||
# verify passed
|
|
||||||
|
|
||||||
fromAddress = encodeAddress(
|
|
||||||
sendersAddressVersion, sendersStream, calculatedRipe)
|
|
||||||
with shared.printLock:
|
|
||||||
print 'fromAddress:', fromAddress
|
|
||||||
|
|
||||||
# Let's store the public key in case we want to reply to this person.
|
|
||||||
sqlExecute(
|
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
calculatedRipe,
|
|
||||||
sendersAddressVersion,
|
|
||||||
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the
|
|
||||||
# POW and send it.
|
|
||||||
self.possibleNewPubkey(address = fromAddress)
|
|
||||||
|
|
||||||
if messageEncodingType == 2:
|
|
||||||
subject, body = self.decodeType2Message(message)
|
|
||||||
elif messageEncodingType == 1:
|
|
||||||
body = message
|
|
||||||
subject = ''
|
|
||||||
elif messageEncodingType == 0:
|
|
||||||
print 'messageEncodingType == 0. Doing nothing with the message.'
|
|
||||||
else:
|
|
||||||
body = 'Unknown encoding type.\n\n' + repr(message)
|
|
||||||
subject = ''
|
|
||||||
|
|
||||||
toAddress = '[Broadcast subscribers]'
|
|
||||||
if messageEncodingType != 0:
|
|
||||||
|
|
||||||
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
|
|
||||||
time.time()), body, 'inbox', messageEncodingType, 0)
|
|
||||||
helper_inbox.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
|
||||||
self.inventoryHash, toAddress, fromAddress, subject, body)))
|
|
||||||
|
|
||||||
# If we are behaving as an API then we might need to run an
|
|
||||||
# outside command to let some program know that a new message
|
|
||||||
# has arrived.
|
|
||||||
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
|
||||||
try:
|
|
||||||
apiNotifyPath = shared.config.get(
|
|
||||||
'bitmessagesettings', 'apinotifypath')
|
|
||||||
except:
|
|
||||||
apiNotifyPath = ''
|
|
||||||
if apiNotifyPath != '':
|
|
||||||
call([apiNotifyPath, "newBroadcast"])
|
|
||||||
|
|
||||||
# Display timing data
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
|
|
||||||
|
|
||||||
# We have received a msg message.
|
# We have received a msg message.
|
||||||
def recmsg(self, data):
|
def recmsg(self, data):
|
||||||
readPosition = 24 # bypass the network header
|
|
||||||
self.messageProcessingStartTime = time.time()
|
self.messageProcessingStartTime = time.time()
|
||||||
# First we must check to make sure the proof of work is sufficient.
|
|
||||||
if not shared.isProofOfWorkSufficient(data[readPosition:readPosition+10]):
|
|
||||||
print 'Proof of work in msg message insufficient.'
|
|
||||||
return
|
|
||||||
|
|
||||||
readPosition += 8 # bypass the POW nonce
|
shared.checkAndShareMsgWithPeers(data)
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
"""
|
||||||
# time in the protocol.
|
Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. Sleeping
|
||||||
if embeddedTime == 0:
|
will help guarantee that we can process messages faster than a remote
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
node can send them. If we fall behind, the attacker could observe that
|
||||||
readPosition += 8
|
we are are slowing down the rate at which we request objects from the
|
||||||
else:
|
network which would indicate that we own a particular address (whichever
|
||||||
readPosition += 4
|
one to which they are sending all of their attack messages). Note
|
||||||
|
that if an attacker connects to a target with many connections, this
|
||||||
if embeddedTime > int(time.time()) + 10800:
|
mitigation mechanism might not be sufficient.
|
||||||
print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime
|
"""
|
||||||
return
|
|
||||||
if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept:
|
|
||||||
print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime
|
|
||||||
return
|
|
||||||
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 9])
|
|
||||||
if streamNumberAsClaimedByMsg != self.streamNumber:
|
|
||||||
print 'The stream number encoded in this msg (' + str(streamNumberAsClaimedByMsg) + ') message does not match the stream number on which it was received. Ignoring it.'
|
|
||||||
return
|
|
||||||
readPosition += streamNumberAsClaimedByMsgLength
|
|
||||||
self.inventoryHash = calculateInventoryHash(data)
|
|
||||||
shared.numberOfInventoryLookupsPerformed += 1
|
|
||||||
shared.inventoryLock.acquire()
|
|
||||||
if self.inventoryHash in shared.inventory:
|
|
||||||
print 'We have already received this msg message. Ignoring.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
elif shared.isInSqlInventory(self.inventoryHash):
|
|
||||||
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
# This msg message is valid. Let's let our peers know about it.
|
|
||||||
objectType = 'msg'
|
|
||||||
shared.inventory[self.inventoryHash] = (
|
|
||||||
objectType, self.streamNumber, data, embeddedTime,'')
|
|
||||||
shared.inventorySets[self.streamNumber].add(self.inventoryHash)
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
self.broadcastinv(self.inventoryHash)
|
|
||||||
#shared.numberOfMessagesProcessed += 1
|
|
||||||
#shared.UISignalQueue.put((
|
|
||||||
# 'updateNumberOfMessagesProcessed', 'no data'))
|
|
||||||
|
|
||||||
#self.processmsg(
|
|
||||||
# readPosition, data) # When this function returns, we will have either successfully processed the message bound for us, ignored it because it isn't bound for us, or found problem with the message that warranted ignoring it.
|
|
||||||
shared.objectProcessorQueue.put(data)
|
|
||||||
with shard.printLock:
|
|
||||||
print 'Size of objectProcessorQueue is:', sys.getsizeof(shared.objectProcessorQueue)
|
|
||||||
|
|
||||||
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
|
|
||||||
# haven't used the specified amount of time, we shall sleep. These
|
|
||||||
# values are based on test timings and you may change them at-will.
|
|
||||||
if len(data) > 100000000: # Size is greater than 100 megabytes
|
if len(data) > 100000000: # Size is greater than 100 megabytes
|
||||||
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds.
|
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds.
|
||||||
elif len(data) > 10000000: # Between 100 and 10 megabytes
|
elif len(data) > 10000000: # Between 100 and 10 megabytes
|
||||||
|
@ -920,422 +380,13 @@ class receiveDataThread(threading.Thread):
|
||||||
if sleepTime > 0 and doTimingAttackMitigation:
|
if sleepTime > 0 and doTimingAttackMitigation:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
||||||
|
|
||||||
time.sleep(sleepTime)
|
time.sleep(sleepTime)
|
||||||
with shared.printLock:
|
|
||||||
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
|
|
||||||
|
|
||||||
|
|
||||||
# A msg message has a valid time and POW and requires processing. The
|
|
||||||
# recmsg function calls this one.
|
|
||||||
def processmsg(self, readPosition, encryptedData):
|
|
||||||
initialDecryptionSuccessful = False
|
|
||||||
# Let's check whether this is a message acknowledgement bound for us.
|
|
||||||
if encryptedData[readPosition:] in shared.ackdataForWhichImWatching:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'This msg IS an acknowledgement bound for me.'
|
|
||||||
|
|
||||||
del shared.ackdataForWhichImWatching[encryptedData[readPosition:]]
|
|
||||||
sqlExecute('UPDATE sent SET status=? WHERE ackdata=?',
|
|
||||||
'ackreceived', encryptedData[readPosition:])
|
|
||||||
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], tr.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode(
|
|
||||||
time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8')))))
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'This was NOT an acknowledgement bound for me.'
|
|
||||||
# print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching
|
|
||||||
|
|
||||||
|
|
||||||
# This is not an acknowledgement bound for me. See if it is a message
|
|
||||||
# bound for me by trying to decrypt it with my private keys.
|
|
||||||
for key, cryptorObject in shared.myECCryptorObjects.items():
|
|
||||||
try:
|
|
||||||
decryptedData = cryptorObject.decrypt(
|
|
||||||
encryptedData[readPosition:])
|
|
||||||
toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data.
|
|
||||||
initialDecryptionSuccessful = True
|
|
||||||
with shared.printLock:
|
|
||||||
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
|
|
||||||
break
|
|
||||||
except Exception as err:
|
|
||||||
pass
|
|
||||||
# print 'cryptorObject.decrypt Exception:', err
|
|
||||||
if not initialDecryptionSuccessful:
|
|
||||||
# This is not a message bound for me.
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.'
|
|
||||||
|
|
||||||
else:
|
|
||||||
# This is a message bound for me.
|
|
||||||
toAddress = shared.myAddressesByHash[
|
|
||||||
toRipe] # Look up my address based on the RIPE hash.
|
|
||||||
readPosition = 0
|
|
||||||
messageVersion, messageVersionLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += messageVersionLength
|
|
||||||
if messageVersion != 1:
|
|
||||||
print 'Cannot understand message versions other than one. Ignoring message.'
|
|
||||||
return
|
|
||||||
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += sendersAddressVersionNumberLength
|
|
||||||
if sendersAddressVersionNumber == 0:
|
|
||||||
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
|
|
||||||
return
|
|
||||||
if sendersAddressVersionNumber > 4:
|
|
||||||
print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
|
|
||||||
return
|
|
||||||
if len(decryptedData) < 170:
|
|
||||||
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
|
|
||||||
return
|
|
||||||
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
if sendersStreamNumber == 0:
|
|
||||||
print 'sender\'s stream number is 0. Ignoring message.'
|
|
||||||
return
|
|
||||||
readPosition += sendersStreamNumberLength
|
|
||||||
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
pubSigningKey = '\x04' + decryptedData[
|
|
||||||
readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
pubEncryptionKey = '\x04' + decryptedData[
|
|
||||||
readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
if sendersAddressVersionNumber >= 3:
|
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
|
|
||||||
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
|
|
||||||
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
|
|
||||||
if toRipe != decryptedData[readPosition:readPosition + 20]:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
|
|
||||||
print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
|
|
||||||
print 'your toRipe:', toRipe.encode('hex')
|
|
||||||
print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
|
|
||||||
|
|
||||||
return
|
|
||||||
readPosition += 20
|
|
||||||
messageEncodingType, messageEncodingTypeLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += messageEncodingTypeLength
|
|
||||||
messageLength, messageLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += messageLengthLength
|
|
||||||
message = decryptedData[readPosition:readPosition + messageLength]
|
|
||||||
# print 'First 150 characters of message:', repr(message[:150])
|
|
||||||
readPosition += messageLength
|
|
||||||
ackLength, ackLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += ackLengthLength
|
|
||||||
ackData = decryptedData[readPosition:readPosition + ackLength]
|
|
||||||
readPosition += ackLength
|
|
||||||
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = decryptedData[
|
|
||||||
readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed', err
|
|
||||||
return
|
|
||||||
with shared.printLock:
|
|
||||||
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
|
|
||||||
|
|
||||||
# calculate the fromRipe.
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(pubSigningKey + pubEncryptionKey)
|
|
||||||
ripe = hashlib.new('ripemd160')
|
|
||||||
ripe.update(sha.digest())
|
|
||||||
fromAddress = encodeAddress(
|
|
||||||
sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())
|
|
||||||
# Let's store the public key in case we want to reply to this
|
|
||||||
# person.
|
|
||||||
if sendersAddressVersionNumber <= 3:
|
|
||||||
sqlExecute(
|
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
ripe.digest(),
|
|
||||||
sendersAddressVersionNumber,
|
|
||||||
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the POW
|
|
||||||
# and send it.
|
|
||||||
self.possibleNewPubkey(ripe=ripe.digest())
|
|
||||||
elif sendersAddressVersionNumber >= 4:
|
|
||||||
sqlExecute(
|
|
||||||
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
|
|
||||||
ripe.digest(),
|
|
||||||
sendersAddressVersionNumber,
|
|
||||||
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
|
|
||||||
int(time.time()),
|
|
||||||
'yes')
|
|
||||||
# This will check to see whether we happen to be awaiting this
|
|
||||||
# pubkey in order to send a message. If we are, it will do the POW
|
|
||||||
# and send it.
|
|
||||||
self.possibleNewPubkey(address = fromAddress)
|
|
||||||
# If this message is bound for one of my version 3 addresses (or
|
|
||||||
# higher), then we must check to make sure it meets our demanded
|
|
||||||
# proof of work requirement.
|
|
||||||
if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher:
|
|
||||||
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
|
|
||||||
requiredNonceTrialsPerByte = shared.config.getint(
|
|
||||||
toAddress, 'noncetrialsperbyte')
|
|
||||||
requiredPayloadLengthExtraBytes = shared.config.getint(
|
|
||||||
toAddress, 'payloadlengthextrabytes')
|
|
||||||
if not shared.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
|
|
||||||
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
|
|
||||||
return
|
|
||||||
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
|
|
||||||
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
|
|
||||||
queryreturn = sqlQuery(
|
|
||||||
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
|
|
||||||
fromAddress)
|
|
||||||
if queryreturn != []:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Message ignored because address is in blacklist.'
|
|
||||||
|
|
||||||
blockMessage = True
|
|
||||||
else: # We're using a whitelist
|
|
||||||
queryreturn = sqlQuery(
|
|
||||||
'''SELECT label FROM whitelist where address=? and enabled='1' ''',
|
|
||||||
fromAddress)
|
|
||||||
if queryreturn == []:
|
|
||||||
print 'Message ignored because address not in whitelist.'
|
|
||||||
blockMessage = True
|
|
||||||
if not blockMessage:
|
|
||||||
print 'fromAddress:', fromAddress
|
|
||||||
print 'First 150 characters of message:', repr(message[:150])
|
|
||||||
|
|
||||||
toLabel = shared.config.get(toAddress, 'label')
|
|
||||||
if toLabel == '':
|
|
||||||
toLabel = toAddress
|
|
||||||
|
|
||||||
if messageEncodingType == 2:
|
|
||||||
subject, body = self.decodeType2Message(message)
|
|
||||||
elif messageEncodingType == 1:
|
|
||||||
body = message
|
|
||||||
subject = ''
|
|
||||||
elif messageEncodingType == 0:
|
|
||||||
print 'messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.'
|
|
||||||
else:
|
|
||||||
body = 'Unknown encoding type.\n\n' + repr(message)
|
|
||||||
subject = ''
|
|
||||||
if messageEncodingType != 0:
|
|
||||||
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
|
|
||||||
time.time()), body, 'inbox', messageEncodingType, 0)
|
|
||||||
helper_inbox.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewInboxMessage', (
|
|
||||||
self.inventoryHash, toAddress, fromAddress, subject, body)))
|
|
||||||
|
|
||||||
# If we are behaving as an API then we might need to run an
|
|
||||||
# outside command to let some program know that a new message
|
|
||||||
# has arrived.
|
|
||||||
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
|
|
||||||
try:
|
|
||||||
apiNotifyPath = shared.config.get(
|
|
||||||
'bitmessagesettings', 'apinotifypath')
|
|
||||||
except:
|
|
||||||
apiNotifyPath = ''
|
|
||||||
if apiNotifyPath != '':
|
|
||||||
call([apiNotifyPath, "newMessage"])
|
|
||||||
|
|
||||||
# Let us now check and see whether our receiving address is
|
|
||||||
# behaving as a mailing list
|
|
||||||
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
|
|
||||||
try:
|
|
||||||
mailingListName = shared.config.get(
|
|
||||||
toAddress, 'mailinglistname')
|
|
||||||
except:
|
|
||||||
mailingListName = ''
|
|
||||||
# Let us send out this message as a broadcast
|
|
||||||
subject = self.addMailingListNameToSubject(
|
|
||||||
subject, mailingListName)
|
|
||||||
# Let us now send this message out as a broadcast
|
|
||||||
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
|
|
||||||
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
|
|
||||||
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
|
|
||||||
ackdata = OpenSSL.rand(
|
|
||||||
32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
|
|
||||||
toAddress = '[Broadcast subscribers]'
|
|
||||||
ripe = ''
|
|
||||||
|
|
||||||
t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
|
|
||||||
time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
|
|
||||||
helper_sent.insert(t)
|
|
||||||
|
|
||||||
shared.UISignalQueue.put(('displayNewSentMessage', (
|
|
||||||
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata)))
|
|
||||||
shared.workerQueue.put(('sendbroadcast', ''))
|
|
||||||
|
|
||||||
if self.isAckDataValid(ackData):
|
|
||||||
print 'ackData is valid. Will process it.'
|
|
||||||
self.ackDataThatWeHaveYetToSend.append(
|
|
||||||
ackData) # When we have processed all data, the processData function will pop the ackData out and process it as if it is a message received from our peer.
|
|
||||||
# Display timing data
|
|
||||||
timeRequiredToAttemptToDecryptMessage = time.time(
|
|
||||||
) - self.messageProcessingStartTime
|
|
||||||
shared.successfullyDecryptMessageTimings.append(
|
|
||||||
timeRequiredToAttemptToDecryptMessage)
|
|
||||||
sum = 0
|
|
||||||
for item in shared.successfullyDecryptMessageTimings:
|
|
||||||
sum += item
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
|
|
||||||
print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
|
|
||||||
|
|
||||||
def decodeType2Message(self, message):
|
|
||||||
bodyPositionIndex = string.find(message, '\nBody:')
|
|
||||||
if bodyPositionIndex > 1:
|
|
||||||
subject = message[8:bodyPositionIndex]
|
|
||||||
# Only save and show the first 500 characters of the subject.
|
|
||||||
# Any more is probably an attack.
|
|
||||||
subject = subject[:500]
|
|
||||||
body = message[bodyPositionIndex + 6:]
|
|
||||||
else:
|
|
||||||
subject = ''
|
|
||||||
body = message
|
|
||||||
# Throw away any extra lines (headers) after the subject.
|
|
||||||
if subject:
|
|
||||||
subject = subject.splitlines()[0]
|
|
||||||
return subject, body
|
|
||||||
|
|
||||||
def isAckDataValid(self, ackData):
|
|
||||||
if len(ackData) < 24:
|
|
||||||
print 'The length of ackData is unreasonably short. Not sending ackData.'
|
|
||||||
return False
|
|
||||||
if ackData[0:4] != '\xe9\xbe\xb4\xd9':
|
|
||||||
print 'Ackdata magic bytes were wrong. Not sending ackData.'
|
|
||||||
return False
|
|
||||||
ackDataPayloadLength, = unpack('>L', ackData[16:20])
|
|
||||||
if len(ackData) - 24 != ackDataPayloadLength:
|
|
||||||
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
|
|
||||||
return False
|
|
||||||
if ackData[4:16] != 'getpubkey\x00\x00\x00' and ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'broadcast\x00\x00\x00':
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def addMailingListNameToSubject(self, subject, mailingListName):
|
|
||||||
subject = subject.strip()
|
|
||||||
if subject[:3] == 'Re:' or subject[:3] == 'RE:':
|
|
||||||
subject = subject[3:].strip()
|
|
||||||
if '[' + mailingListName + ']' in subject:
|
|
||||||
return subject
|
|
||||||
else:
|
|
||||||
return '[' + mailingListName + '] ' + subject
|
|
||||||
|
|
||||||
# We have inserted a pubkey into our pubkey table which we received from a
|
|
||||||
# pubkey, msg, or broadcast message. It might be one that we have been
|
|
||||||
# waiting for. Let's check.
|
|
||||||
def possibleNewPubkey(self, ripe=None, address=None):
|
|
||||||
# For address versions <= 3, we wait on a key with the correct ripe hash
|
|
||||||
if ripe != None:
|
|
||||||
if ripe in shared.neededPubkeys:
|
|
||||||
print 'We have been awaiting the arrival of this pubkey.'
|
|
||||||
del shared.neededPubkeys[ripe]
|
|
||||||
sqlExecute(
|
|
||||||
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
|
|
||||||
ripe)
|
|
||||||
shared.workerQueue.put(('sendmessage', ''))
|
|
||||||
else:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', ripe.encode('hex')
|
|
||||||
# For address versions >= 4, we wait on a pubkey with the correct tag.
|
|
||||||
# Let us create the tag from the address and see if we were waiting
|
|
||||||
# for it.
|
|
||||||
elif address != None:
|
|
||||||
status, addressVersion, streamNumber, ripe = decodeAddress(address)
|
|
||||||
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
|
||||||
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
|
|
||||||
if tag in shared.neededPubkeys:
|
|
||||||
print 'We have been awaiting the arrival of this pubkey.'
|
|
||||||
del shared.neededPubkeys[tag]
|
|
||||||
sqlExecute(
|
|
||||||
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
|
|
||||||
ripe)
|
|
||||||
shared.workerQueue.put(('sendmessage', ''))
|
|
||||||
|
|
||||||
# We have received a pubkey
|
# We have received a pubkey
|
||||||
def recpubkey(self, data):
|
def recpubkey(self, data):
|
||||||
self.pubkeyProcessingStartTime = time.time()
|
self.pubkeyProcessingStartTime = time.time()
|
||||||
if len(data) < 146 or len(data) > 420: # sanity check
|
|
||||||
return
|
|
||||||
# We must check to make sure the proof of work is sufficient.
|
|
||||||
if not shared.isProofOfWorkSufficient(data):
|
|
||||||
print 'Proof of work in pubkey message insufficient.'
|
|
||||||
return
|
|
||||||
|
|
||||||
readPosition = 8 # for the nonce
|
shared.checkAndSharePubkeyWithPeers(data)
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
|
||||||
# time in the protocol.
|
|
||||||
if embeddedTime == 0:
|
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
|
||||||
readPosition += 8
|
|
||||||
else:
|
|
||||||
readPosition += 4
|
|
||||||
|
|
||||||
if embeddedTime < int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
|
|
||||||
|
|
||||||
return
|
|
||||||
if embeddedTime > int(time.time()) + 10800:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.'
|
|
||||||
|
|
||||||
return
|
|
||||||
addressVersion, varintLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
streamNumber, varintLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
if self.streamNumber != streamNumber:
|
|
||||||
print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.'
|
|
||||||
return
|
|
||||||
if addressVersion >= 4:
|
|
||||||
tag = data[readPosition:readPosition + 32]
|
|
||||||
print 'tag in received pubkey is:', tag.encode('hex')
|
|
||||||
else:
|
|
||||||
tag = ''
|
|
||||||
|
|
||||||
shared.numberOfInventoryLookupsPerformed += 1
|
|
||||||
inventoryHash = calculateInventoryHash(data)
|
|
||||||
shared.inventoryLock.acquire()
|
|
||||||
if inventoryHash in shared.inventory:
|
|
||||||
print 'We have already received this pubkey. Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
elif shared.isInSqlInventory(inventoryHash):
|
|
||||||
print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
objectType = 'pubkey'
|
|
||||||
shared.inventory[inventoryHash] = (
|
|
||||||
objectType, self.streamNumber, data, embeddedTime, tag)
|
|
||||||
shared.inventorySets[self.streamNumber].add(inventoryHash)
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
self.broadcastinv(inventoryHash)
|
|
||||||
shared.numberOfPubkeysProcessed += 1
|
|
||||||
shared.UISignalQueue.put((
|
|
||||||
'updateNumberOfPubkeysProcessed', 'no data'))
|
|
||||||
|
|
||||||
self.processpubkey(data)
|
|
||||||
|
|
||||||
lengthOfTimeWeShouldUseToProcessThisMessage = .1
|
lengthOfTimeWeShouldUseToProcessThisMessage = .1
|
||||||
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
|
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
|
||||||
|
@ -1343,342 +394,7 @@ class receiveDataThread(threading.Thread):
|
||||||
if sleepTime > 0 and doTimingAttackMitigation:
|
if sleepTime > 0 and doTimingAttackMitigation:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
|
||||||
|
|
||||||
time.sleep(sleepTime)
|
time.sleep(sleepTime)
|
||||||
with shared.printLock:
|
|
||||||
print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.'
|
|
||||||
|
|
||||||
|
|
||||||
def processpubkey(self, data):
|
|
||||||
readPosition = 8 # for the nonce
|
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
|
||||||
# time in the protocol.
|
|
||||||
if embeddedTime == 0:
|
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
|
||||||
readPosition += 8
|
|
||||||
else:
|
|
||||||
readPosition += 4
|
|
||||||
|
|
||||||
addressVersion, varintLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
streamNumber, varintLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += varintLength
|
|
||||||
if addressVersion == 0:
|
|
||||||
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
|
|
||||||
return
|
|
||||||
if addressVersion > 4 or addressVersion == 1:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.'
|
|
||||||
|
|
||||||
return
|
|
||||||
if addressVersion == 2:
|
|
||||||
if len(data) < 146: # sanity check. This is the minimum possible length.
|
|
||||||
print '(within processpubkey) payloadLength less than 146. Sanity check failed.'
|
|
||||||
return
|
|
||||||
bitfieldBehaviors = data[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
publicSigningKey = data[readPosition:readPosition + 64]
|
|
||||||
# Is it possible for a public key to be invalid such that trying to
|
|
||||||
# encrypt or sign with it will cause an error? If it is, we should
|
|
||||||
# probably test these keys here.
|
|
||||||
readPosition += 64
|
|
||||||
publicEncryptionKey = data[readPosition:readPosition + 64]
|
|
||||||
if len(publicEncryptionKey) < 64:
|
|
||||||
print 'publicEncryptionKey length less than 64. Sanity check failed.'
|
|
||||||
return
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(
|
|
||||||
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
|
|
||||||
ripeHasher = hashlib.new('ripemd160')
|
|
||||||
ripeHasher.update(sha.digest())
|
|
||||||
ripe = ripeHasher.digest()
|
|
||||||
|
|
||||||
with shared.printLock:
|
|
||||||
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
|
||||||
print 'ripe', ripe.encode('hex')
|
|
||||||
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
|
||||||
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
|
||||||
|
|
||||||
|
|
||||||
queryreturn = sqlQuery(
|
|
||||||
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
|
|
||||||
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
|
|
||||||
print 'We HAVE used this pubkey personally. Updating time.'
|
|
||||||
t = (ripe, addressVersion, data, embeddedTime, 'yes')
|
|
||||||
else:
|
|
||||||
print 'We have NOT used this pubkey personally. Inserting in database.'
|
|
||||||
t = (ripe, addressVersion, data, embeddedTime, 'no')
|
|
||||||
# This will also update the embeddedTime.
|
|
||||||
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
|
||||||
# shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
|
|
||||||
self.possibleNewPubkey(ripe = ripe)
|
|
||||||
if addressVersion == 3:
|
|
||||||
if len(data) < 170: # sanity check.
|
|
||||||
print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
|
|
||||||
return
|
|
||||||
bitfieldBehaviors = data[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
|
|
||||||
# Is it possible for a public key to be invalid such that trying to
|
|
||||||
# encrypt or sign with it will cause an error? If it is, we should
|
|
||||||
# probably test these keys here.
|
|
||||||
readPosition += 64
|
|
||||||
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += specifiedNonceTrialsPerByteLength
|
|
||||||
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += specifiedPayloadLengthExtraBytesLength
|
|
||||||
endOfSignedDataPosition = readPosition
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = data[readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed (within processpubkey)'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed (within processpubkey)'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed (within processpubkey)', err
|
|
||||||
return
|
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(publicSigningKey + publicEncryptionKey)
|
|
||||||
ripeHasher = hashlib.new('ripemd160')
|
|
||||||
ripeHasher.update(sha.digest())
|
|
||||||
ripe = ripeHasher.digest()
|
|
||||||
|
|
||||||
with shared.printLock:
|
|
||||||
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
|
||||||
print 'ripe', ripe.encode('hex')
|
|
||||||
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
|
||||||
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
|
||||||
|
|
||||||
|
|
||||||
queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
|
|
||||||
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
|
|
||||||
print 'We HAVE used this pubkey personally. Updating time.'
|
|
||||||
t = (ripe, addressVersion, data, embeddedTime, 'yes')
|
|
||||||
else:
|
|
||||||
print 'We have NOT used this pubkey personally. Inserting in database.'
|
|
||||||
t = (ripe, addressVersion, data, embeddedTime, 'no')
|
|
||||||
# This will also update the embeddedTime.
|
|
||||||
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
|
||||||
self.possibleNewPubkey(ripe = ripe)
|
|
||||||
|
|
||||||
if addressVersion == 4:
|
|
||||||
if len(data) < 350: # sanity check.
|
|
||||||
print '(within processpubkey) payloadLength less than 350. Sanity check failed.'
|
|
||||||
return
|
|
||||||
signedData = data[8:readPosition] # Used only for v4 or higher pubkeys
|
|
||||||
tag = data[readPosition:readPosition + 32]
|
|
||||||
readPosition += 32
|
|
||||||
encryptedData = data[readPosition:]
|
|
||||||
if tag not in shared.neededPubkeys:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'We don\'t need this v4 pubkey. We didn\'t ask for it.'
|
|
||||||
return
|
|
||||||
|
|
||||||
# Let us try to decrypt the pubkey
|
|
||||||
cryptorObject = shared.neededPubkeys[tag]
|
|
||||||
try:
|
|
||||||
decryptedData = cryptorObject.decrypt(encryptedData)
|
|
||||||
except:
|
|
||||||
# Someone must have encrypted some data with a different key
|
|
||||||
# but tagged it with a tag for which we are watching.
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Pubkey decryption was unsuccessful.'
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
readPosition = 0
|
|
||||||
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
|
|
||||||
readPosition += 4
|
|
||||||
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
|
||||||
# Is it possible for a public key to be invalid such that trying to
|
|
||||||
# encrypt or sign with it will cause an error? If it is, we should
|
|
||||||
# probably test these keys here.
|
|
||||||
readPosition += 64
|
|
||||||
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
|
||||||
readPosition += 64
|
|
||||||
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += specifiedNonceTrialsPerByteLength
|
|
||||||
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += specifiedPayloadLengthExtraBytesLength
|
|
||||||
signedData += decryptedData[:readPosition]
|
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
|
||||||
decryptedData[readPosition:readPosition + 10])
|
|
||||||
readPosition += signatureLengthLength
|
|
||||||
signature = decryptedData[readPosition:readPosition + signatureLength]
|
|
||||||
try:
|
|
||||||
if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
|
|
||||||
print 'ECDSA verify failed (within processpubkey)'
|
|
||||||
return
|
|
||||||
print 'ECDSA verify passed (within processpubkey)'
|
|
||||||
except Exception as err:
|
|
||||||
print 'ECDSA verify failed (within processpubkey)', err
|
|
||||||
return
|
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
|
||||||
sha.update(publicSigningKey + publicEncryptionKey)
|
|
||||||
ripeHasher = hashlib.new('ripemd160')
|
|
||||||
ripeHasher.update(sha.digest())
|
|
||||||
ripe = ripeHasher.digest()
|
|
||||||
|
|
||||||
# We need to make sure that the tag on the outside of the encryption
|
|
||||||
# is the one generated from hashing these particular keys.
|
|
||||||
if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.'
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
print 'Tag successfully matches keys in pubkey message' # testing. Will remove soon.
|
|
||||||
|
|
||||||
with shared.printLock:
|
|
||||||
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
|
|
||||||
print 'ripe', ripe.encode('hex')
|
|
||||||
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
|
|
||||||
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
|
|
||||||
|
|
||||||
t = (ripe, addressVersion, signedData, embeddedTime, 'yes')
|
|
||||||
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
|
||||||
|
|
||||||
fromAddress = encodeAddress(addressVersion, streamNumber, ripe)
|
|
||||||
# That this point we know that we have been waiting on this pubkey.
|
|
||||||
# This function will command the workerThread to start work on
|
|
||||||
# the messages that require it.
|
|
||||||
self.possibleNewPubkey(address = fromAddress)
|
|
||||||
|
|
||||||
# We have received a getpubkey message
|
|
||||||
def recgetpubkey(self, data):
|
|
||||||
if not shared.isProofOfWorkSufficient(data):
|
|
||||||
print 'Proof of work in getpubkey message insufficient.'
|
|
||||||
return
|
|
||||||
if len(data) < 34:
|
|
||||||
print 'getpubkey message doesn\'t contain enough data. Ignoring.'
|
|
||||||
return
|
|
||||||
readPosition = 8 # bypass the nonce
|
|
||||||
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
|
||||||
|
|
||||||
# This section is used for the transition from 32 bit time to 64 bit
|
|
||||||
# time in the protocol.
|
|
||||||
if embeddedTime == 0:
|
|
||||||
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
|
||||||
readPosition += 8
|
|
||||||
else:
|
|
||||||
readPosition += 4
|
|
||||||
|
|
||||||
if embeddedTime > int(time.time()) + 10800:
|
|
||||||
print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime
|
|
||||||
return
|
|
||||||
if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept:
|
|
||||||
print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
|
|
||||||
return
|
|
||||||
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
readPosition += addressVersionLength
|
|
||||||
streamNumber, streamNumberLength = decodeVarint(
|
|
||||||
data[readPosition:readPosition + 10])
|
|
||||||
if streamNumber != self.streamNumber:
|
|
||||||
print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber
|
|
||||||
return
|
|
||||||
readPosition += streamNumberLength
|
|
||||||
|
|
||||||
shared.numberOfInventoryLookupsPerformed += 1
|
|
||||||
inventoryHash = calculateInventoryHash(data)
|
|
||||||
shared.inventoryLock.acquire()
|
|
||||||
if inventoryHash in shared.inventory:
|
|
||||||
print 'We have already received this getpubkey request. Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
elif shared.isInSqlInventory(inventoryHash):
|
|
||||||
print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.'
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
return
|
|
||||||
|
|
||||||
objectType = 'getpubkey'
|
|
||||||
shared.inventory[inventoryHash] = (
|
|
||||||
objectType, self.streamNumber, data, embeddedTime,'')
|
|
||||||
shared.inventorySets[self.streamNumber].add(inventoryHash)
|
|
||||||
shared.inventoryLock.release()
|
|
||||||
# This getpubkey request is valid so far. Forward to peers.
|
|
||||||
self.broadcastinv(inventoryHash)
|
|
||||||
|
|
||||||
if requestedAddressVersionNumber == 0:
|
|
||||||
print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
|
|
||||||
return
|
|
||||||
elif requestedAddressVersionNumber == 1:
|
|
||||||
print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
|
|
||||||
return
|
|
||||||
elif requestedAddressVersionNumber > 4:
|
|
||||||
print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
|
|
||||||
return
|
|
||||||
|
|
||||||
myAddress = ''
|
|
||||||
if requestedAddressVersionNumber <= 3 :
|
|
||||||
requestedHash = data[readPosition:readPosition + 20]
|
|
||||||
if len(requestedHash) != 20:
|
|
||||||
print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
|
|
||||||
return
|
|
||||||
with shared.printLock:
|
|
||||||
print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex')
|
|
||||||
if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine
|
|
||||||
myAddress = shared.myAddressesByHash[requestedHash]
|
|
||||||
elif requestedAddressVersionNumber >= 4:
|
|
||||||
requestedTag = data[readPosition:readPosition + 32]
|
|
||||||
if len(requestedTag) != 32:
|
|
||||||
print 'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
|
|
||||||
return
|
|
||||||
with shared.printLock:
|
|
||||||
print 'the tag requested in this getpubkey request is:', requestedTag.encode('hex')
|
|
||||||
if requestedTag in shared.myAddressesByTag:
|
|
||||||
|
|
||||||
myAddress = shared.myAddressesByTag[requestedTag]
|
|
||||||
|
|
||||||
if myAddress == '':
|
|
||||||
with shared.printLock:
|
|
||||||
print 'This getpubkey request is not for any of my keys.'
|
|
||||||
return
|
|
||||||
|
|
||||||
if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
|
|
||||||
with shared.printLock:
|
|
||||||
sys.stderr.write(
|
|
||||||
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. They shouldn\'t have done that. Ignoring.\n')
|
|
||||||
return
|
|
||||||
if shared.safeConfigGetBoolean(myAddress, 'chan'):
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
lastPubkeySendTime = int(shared.config.get(
|
|
||||||
myAddress, 'lastpubkeysendtime'))
|
|
||||||
except:
|
|
||||||
lastPubkeySendTime = 0
|
|
||||||
if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago...
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
|
|
||||||
return
|
|
||||||
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.'
|
|
||||||
if requestedAddressVersionNumber == 2:
|
|
||||||
shared.workerQueue.put((
|
|
||||||
'doPOWForMyV2Pubkey', requestedHash))
|
|
||||||
elif requestedAddressVersionNumber == 3:
|
|
||||||
shared.workerQueue.put((
|
|
||||||
'sendOutOrStoreMyV3Pubkey', requestedHash))
|
|
||||||
elif requestedAddressVersionNumber == 4:
|
|
||||||
shared.workerQueue.put((
|
|
||||||
'sendOutOrStoreMyV4Pubkey', myAddress))
|
|
||||||
|
|
||||||
|
|
||||||
# We have received an inv message
|
# We have received an inv message
|
||||||
|
@ -1702,7 +418,6 @@ class receiveDataThread(threading.Thread):
|
||||||
if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation
|
if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.'
|
print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.'
|
||||||
|
|
||||||
return
|
return
|
||||||
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[
|
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[
|
||||||
data[lengthOfVarint:32 + lengthOfVarint]] = 0
|
data[lengthOfVarint:32 + lengthOfVarint]] = 0
|
||||||
|
@ -1825,12 +540,12 @@ class receiveDataThread(threading.Thread):
|
||||||
|
|
||||||
|
|
||||||
# Advertise this object to all of our peers
|
# Advertise this object to all of our peers
|
||||||
def broadcastinv(self, hash):
|
"""def broadcastinv(self, hash):
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'broadcasting inv with hash:', hash.encode('hex')
|
print 'broadcasting inv with hash:', hash.encode('hex')
|
||||||
|
|
||||||
shared.broadcastToSendDataQueues((self.streamNumber, 'advertiseobject', hash))
|
shared.broadcastToSendDataQueues((self.streamNumber, 'advertiseobject', hash))
|
||||||
|
"""
|
||||||
# We have received an addr message.
|
# We have received an addr message.
|
||||||
def recaddr(self, data):
|
def recaddr(self, data):
|
||||||
#listOfAddressDetailsToBroadcastToPeers = []
|
#listOfAddressDetailsToBroadcastToPeers = []
|
||||||
|
@ -1853,13 +568,11 @@ class receiveDataThread(threading.Thread):
|
||||||
if data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
|
if data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)])
|
print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)])
|
||||||
|
|
||||||
continue
|
continue
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
sys.stderr.write(
|
sys.stderr.write(
|
||||||
'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err))
|
'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err))
|
||||||
|
|
||||||
break # giving up on unpacking any more. We should still be connected however.
|
break # giving up on unpacking any more. We should still be connected however.
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -1869,7 +582,6 @@ class receiveDataThread(threading.Thread):
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
sys.stderr.write(
|
sys.stderr.write(
|
||||||
'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err))
|
'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err))
|
||||||
|
|
||||||
break # giving up on unpacking any more. We should still be connected however.
|
break # giving up on unpacking any more. We should still be connected however.
|
||||||
if recaddrStream == 0:
|
if recaddrStream == 0:
|
||||||
continue
|
continue
|
||||||
|
@ -1882,7 +594,6 @@ class receiveDataThread(threading.Thread):
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
sys.stderr.write(
|
sys.stderr.write(
|
||||||
'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err))
|
'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err))
|
||||||
|
|
||||||
break # giving up on unpacking any more. We should still be connected however.
|
break # giving up on unpacking any more. We should still be connected however.
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -1892,7 +603,6 @@ class receiveDataThread(threading.Thread):
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
sys.stderr.write(
|
sys.stderr.write(
|
||||||
'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err))
|
'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err))
|
||||||
|
|
||||||
break # giving up on unpacking any more. We should still be connected however.
|
break # giving up on unpacking any more. We should still be connected however.
|
||||||
# print 'Within recaddr(): IP', recaddrIP, ', Port',
|
# print 'Within recaddr(): IP', recaddrIP, ', Port',
|
||||||
# recaddrPort, ', i', i
|
# recaddrPort, ', i', i
|
||||||
|
@ -1945,37 +655,6 @@ class receiveDataThread(threading.Thread):
|
||||||
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
|
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
|
||||||
|
|
||||||
|
|
||||||
# Function runs when we want to broadcast an addr message to all of our
|
|
||||||
# peers. Runs when we learn of nodes that we didn't previously know about
|
|
||||||
# and want to share them with our peers.
|
|
||||||
"""def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers):
|
|
||||||
numberOfAddressesInAddrMessage = len(
|
|
||||||
listOfAddressDetailsToBroadcastToPeers)
|
|
||||||
payload = ''
|
|
||||||
for hostDetails in listOfAddressDetailsToBroadcastToPeers:
|
|
||||||
timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails
|
|
||||||
payload += pack(
|
|
||||||
'>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time
|
|
||||||
payload += pack('>I', streamNumber)
|
|
||||||
payload += pack(
|
|
||||||
'>q', services) # service bit flags offered by this node
|
|
||||||
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
|
|
||||||
socket.inet_aton(host)
|
|
||||||
payload += pack('>H', port) # remote port
|
|
||||||
|
|
||||||
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
|
|
||||||
datatosend = '\xE9\xBE\xB4\xD9addr\x00\x00\x00\x00\x00\x00\x00\x00'
|
|
||||||
datatosend = datatosend + pack('>L', len(payload)) # payload length
|
|
||||||
datatosend = datatosend + hashlib.sha512(payload).digest()[0:4]
|
|
||||||
datatosend = datatosend + payload
|
|
||||||
|
|
||||||
if shared.verbose >= 1:
|
|
||||||
with shared.printLock:
|
|
||||||
print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.'
|
|
||||||
|
|
||||||
shared.broadcastToSendDataQueues((
|
|
||||||
self.streamNumber, 'sendaddr', datatosend))"""
|
|
||||||
|
|
||||||
# Send a big addr message to our peer
|
# Send a big addr message to our peer
|
||||||
def sendaddr(self):
|
def sendaddr(self):
|
||||||
addrsInMyStream = {}
|
addrsInMyStream = {}
|
||||||
|
@ -2079,7 +758,6 @@ class receiveDataThread(threading.Thread):
|
||||||
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Closing connection to old protocol version 1 node: ', self.peer
|
print 'Closing connection to old protocol version 1 node: ', self.peer
|
||||||
|
|
||||||
return
|
return
|
||||||
# print 'remoteProtocolVersion', self.remoteProtocolVersion
|
# print 'remoteProtocolVersion', self.remoteProtocolVersion
|
||||||
self.myExternalIP = socket.inet_ntoa(data[40:44])
|
self.myExternalIP = socket.inet_ntoa(data[40:44])
|
||||||
|
@ -2103,7 +781,6 @@ class receiveDataThread(threading.Thread):
|
||||||
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Closed connection to', self.peer, 'because they are interested in stream', self.streamNumber, '.'
|
print 'Closed connection to', self.peer, 'because they are interested in stream', self.streamNumber, '.'
|
||||||
|
|
||||||
return
|
return
|
||||||
shared.connectedHostsList[
|
shared.connectedHostsList[
|
||||||
self.peer.host] = 1 # We use this data structure to not only keep track of what hosts we are connected to so that we don't try to connect to them again, but also to list the connections count on the Network Status tab.
|
self.peer.host] = 1 # We use this data structure to not only keep track of what hosts we are connected to so that we don't try to connect to them again, but also to list the connections count on the Network Status tab.
|
||||||
|
@ -2116,7 +793,6 @@ class receiveDataThread(threading.Thread):
|
||||||
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Closing connection to myself: ', self.peer
|
print 'Closing connection to myself: ', self.peer
|
||||||
|
|
||||||
return
|
return
|
||||||
shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', (
|
shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', (
|
||||||
self.peer, self.remoteProtocolVersion)))
|
self.peer, self.remoteProtocolVersion)))
|
||||||
|
@ -2148,7 +824,6 @@ class receiveDataThread(threading.Thread):
|
||||||
def sendverack(self):
|
def sendverack(self):
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Sending verack'
|
print 'Sending verack'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.sock.sendall(
|
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')
|
'\xE9\xBE\xB4\xD9\x76\x65\x72\x61\x63\x6B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')
|
||||||
|
@ -2156,11 +831,6 @@ class receiveDataThread(threading.Thread):
|
||||||
# if not 'Bad file descriptor' in err:
|
# if not 'Bad file descriptor' in err:
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'sock.sendall error:', err
|
print 'sock.sendall error:', err
|
||||||
|
|
||||||
# cf
|
|
||||||
# 83
|
|
||||||
# e1
|
|
||||||
# 35
|
|
||||||
self.verackSent = True
|
self.verackSent = True
|
||||||
if self.verackReceived:
|
if self.verackReceived:
|
||||||
self.connectionFullyEstablished()
|
self.connectionFullyEstablished()
|
||||||
|
|
|
@ -494,7 +494,7 @@ class singleWorker(threading.Thread):
|
||||||
if queryreturn != []: # if there was a pubkey in our inventory with the correct tag, we need to try to decrypt it.
|
if queryreturn != []: # if there was a pubkey in our inventory with the correct tag, we need to try to decrypt it.
|
||||||
for row in queryreturn:
|
for row in queryreturn:
|
||||||
data, = row
|
data, = row
|
||||||
if shared.decryptAndCheckPubkeyPayload(data[8:], toaddress) == 'successful':
|
if shared.decryptAndCheckPubkeyPayload(data, toaddress) == 'successful':
|
||||||
needToRequestPubkey = False
|
needToRequestPubkey = False
|
||||||
print 'debug. successfully decrypted and checked pubkey from sql inventory.' #testing
|
print 'debug. successfully decrypted and checked pubkey from sql inventory.' #testing
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
|
@ -508,7 +508,7 @@ class singleWorker(threading.Thread):
|
||||||
for hash, storedValue in shared.inventory.items():
|
for hash, storedValue in shared.inventory.items():
|
||||||
objectType, streamNumber, payload, receivedTime, tag = storedValue
|
objectType, streamNumber, payload, receivedTime, tag = storedValue
|
||||||
if objectType == 'pubkey' and tag == toTag:
|
if objectType == 'pubkey' and tag == toTag:
|
||||||
result = shared.decryptAndCheckPubkeyPayload(payload[8:], toaddress) #if valid, this function also puts it in the pubkeys table.
|
result = shared.decryptAndCheckPubkeyPayload(payload, toaddress) #if valid, this function also puts it in the pubkeys table.
|
||||||
if result == 'successful':
|
if result == 'successful':
|
||||||
print 'debug. successfully decrypted and checked pubkey from memory inventory.'
|
print 'debug. successfully decrypted and checked pubkey from memory inventory.'
|
||||||
needToRequestPubkey = False
|
needToRequestPubkey = False
|
||||||
|
|
285
src/shared.py
285
src/shared.py
|
@ -45,6 +45,8 @@ sendDataQueues = [] #each sendData thread puts its queue in this list.
|
||||||
inventory = {} #of objects (like msg payloads and pubkey payloads) Does not include protocol headers (the first 24 bytes of each packet).
|
inventory = {} #of objects (like msg payloads and pubkey payloads) Does not include protocol headers (the first 24 bytes of each packet).
|
||||||
inventoryLock = threading.Lock() #Guarantees that two receiveDataThreads don't receive and process the same message concurrently (probably sent by a malicious individual)
|
inventoryLock = threading.Lock() #Guarantees that two receiveDataThreads don't receive and process the same message concurrently (probably sent by a malicious individual)
|
||||||
printLock = threading.Lock()
|
printLock = threading.Lock()
|
||||||
|
objectProcessorQueueSizeLock = threading.Lock()
|
||||||
|
objectProcessorQueueSize = 0 # in Bytes. We maintain this to prevent nodes from flooing us with objects which take up too much memory. If this gets too big we'll sleep before asking for further objects.
|
||||||
appdata = '' #holds the location of the application data storage directory
|
appdata = '' #holds the location of the application data storage directory
|
||||||
statusIconColor = 'red'
|
statusIconColor = 'red'
|
||||||
connectedHostsList = {} #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice.
|
connectedHostsList = {} #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice.
|
||||||
|
@ -92,10 +94,7 @@ frozen = getattr(sys,'frozen', None)
|
||||||
|
|
||||||
def isInSqlInventory(hash):
|
def isInSqlInventory(hash):
|
||||||
queryreturn = sqlQuery('''select hash from inventory where hash=?''', hash)
|
queryreturn = sqlQuery('''select hash from inventory where hash=?''', hash)
|
||||||
if queryreturn == []:
|
return queryreturn != []
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return True
|
|
||||||
|
|
||||||
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
|
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
|
||||||
payload = ''
|
payload = ''
|
||||||
|
@ -104,7 +103,7 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
|
||||||
payload += pack('>q', int(time.time()))
|
payload += pack('>q', int(time.time()))
|
||||||
|
|
||||||
payload += pack(
|
payload += pack(
|
||||||
'>q', 1) # boolservices of remote connection. How can I even know this for sure? This is probably ignored by the remote host.
|
'>q', 1) # boolservices of remote connection; ignored by the remote host.
|
||||||
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
|
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
|
||||||
socket.inet_aton(remoteHost)
|
socket.inet_aton(remoteHost)
|
||||||
payload += pack('>H', remotePort) # remote IPv6 and port
|
payload += pack('>H', remotePort) # remote IPv6 and port
|
||||||
|
@ -113,7 +112,7 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
|
||||||
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
|
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
|
||||||
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
|
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
|
||||||
payload += pack('>H', shared.config.getint(
|
payload += pack('>H', shared.config.getint(
|
||||||
'bitmessagesettings', 'port')) # my external IPv6 and port
|
'bitmessagesettings', 'port'))
|
||||||
|
|
||||||
random.seed()
|
random.seed()
|
||||||
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
|
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
|
||||||
|
@ -132,7 +131,6 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
|
||||||
|
|
||||||
def lookupAppdataFolder():
|
def lookupAppdataFolder():
|
||||||
APPNAME = "PyBitmessage"
|
APPNAME = "PyBitmessage"
|
||||||
from os import path, environ
|
|
||||||
if "BITMESSAGE_HOME" in environ:
|
if "BITMESSAGE_HOME" in environ:
|
||||||
dataFolder = environ["BITMESSAGE_HOME"]
|
dataFolder = environ["BITMESSAGE_HOME"]
|
||||||
if dataFolder[-1] not in [os.path.sep, os.path.altsep]:
|
if dataFolder[-1] not in [os.path.sep, os.path.altsep]:
|
||||||
|
@ -210,7 +208,8 @@ def decodeWalletImportFormat(WIFstring):
|
||||||
privkey = fullString[:-4]
|
privkey = fullString[:-4]
|
||||||
if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
|
if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
|
||||||
logger.critical('Major problem! When trying to decode one of your private keys, the checksum '
|
logger.critical('Major problem! When trying to decode one of your private keys, the checksum '
|
||||||
'failed. Here is the PRIVATE key: %s' % str(WIFstring))
|
'failed. Here are the first 6 characters of the PRIVATE key: %s' % str(WIFstring)[:6])
|
||||||
|
os._exit(0)
|
||||||
return ""
|
return ""
|
||||||
else:
|
else:
|
||||||
#checksum passed
|
#checksum passed
|
||||||
|
@ -220,6 +219,7 @@ def decodeWalletImportFormat(WIFstring):
|
||||||
logger.critical('Major problem! When trying to decode one of your private keys, the '
|
logger.critical('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 '
|
'checksum passed but the key doesn\'t begin with hex 80. Here is the '
|
||||||
'PRIVATE key: %s' % str(WIFstring))
|
'PRIVATE key: %s' % str(WIFstring))
|
||||||
|
os._exit(0)
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
@ -281,14 +281,13 @@ def reloadBroadcastSendersForWhichImWatching():
|
||||||
MyECSubscriptionCryptorObjects[tag] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex'))
|
MyECSubscriptionCryptorObjects[tag] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex'))
|
||||||
|
|
||||||
def isProofOfWorkSufficient(
|
def isProofOfWorkSufficient(
|
||||||
self,
|
|
||||||
data,
|
data,
|
||||||
nonceTrialsPerByte=0,
|
nonceTrialsPerByte=0,
|
||||||
payloadLengthExtraBytes=0):
|
payloadLengthExtraBytes=0):
|
||||||
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
|
if nonceTrialsPerByte < networkDefaultProofOfWorkNonceTrialsPerByte:
|
||||||
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
|
nonceTrialsPerByte = networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
|
if payloadLengthExtraBytes < networkDefaultPayloadLengthExtraBytes:
|
||||||
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
|
payloadLengthExtraBytes = networkDefaultPayloadLengthExtraBytes
|
||||||
POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
|
POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
|
||||||
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
|
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
|
||||||
# print 'POW:', POW
|
# print 'POW:', POW
|
||||||
|
@ -413,8 +412,8 @@ def decryptAndCheckPubkeyPayload(payload, address):
|
||||||
status, addressVersion, streamNumber, ripe = decodeAddress(address)
|
status, addressVersion, streamNumber, ripe = decodeAddress(address)
|
||||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
||||||
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()
|
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()
|
||||||
# this function expects that the nonce is Not included in payload.
|
readPosition = 8 # bypass the nonce
|
||||||
readPosition = 8 # for the time
|
readPosition += 8 # bypass the time
|
||||||
embeddedVersionNumber, varintLength = decodeVarint(
|
embeddedVersionNumber, varintLength = decodeVarint(
|
||||||
payload[readPosition:readPosition + 10])
|
payload[readPosition:readPosition + 10])
|
||||||
if embeddedVersionNumber != addressVersion:
|
if embeddedVersionNumber != addressVersion:
|
||||||
|
@ -448,7 +447,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
|
||||||
readPosition = 4 # bypass the behavior bitfield
|
readPosition = 4 # bypass the behavior bitfield
|
||||||
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
# Is it possible for a public key to be invalid such that trying to
|
# 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
|
# encrypt or check a sig with it will cause an error? If it is, we should
|
||||||
# probably test these keys here.
|
# probably test these keys here.
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
|
@ -493,5 +492,259 @@ def decryptAndCheckPubkeyPayload(payload, address):
|
||||||
|
|
||||||
Peer = collections.namedtuple('Peer', ['host', 'port'])
|
Peer = collections.namedtuple('Peer', ['host', 'port'])
|
||||||
|
|
||||||
|
def checkAndShareMsgWithPeers(data):
|
||||||
|
# Let us check to make sure that the proof of work is sufficient.
|
||||||
|
if not isProofOfWorkSufficient(data):
|
||||||
|
print 'Proof of work in msg message insufficient.'
|
||||||
|
return
|
||||||
|
|
||||||
|
readPosition = 8
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 9])
|
||||||
|
if not streamNumberAsClaimedByMsg in streamsInWhichIAmParticipating:
|
||||||
|
print 'The streamNumber', streamNumberAsClaimedByMsg, 'isn\'t one we are interested in.'
|
||||||
|
return
|
||||||
|
readPosition += streamNumberAsClaimedByMsgLength
|
||||||
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
shared.numberOfInventoryLookupsPerformed += 1
|
||||||
|
inventoryLock.acquire()
|
||||||
|
if inventoryHash in inventory:
|
||||||
|
print 'We have already received this msg message. Ignoring.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
elif isInSqlInventory(inventoryHash):
|
||||||
|
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
# This msg message is valid. Let's let our peers know about it.
|
||||||
|
objectType = 'msg'
|
||||||
|
inventory[inventoryHash] = (
|
||||||
|
objectType, streamNumberAsClaimedByMsg, data, embeddedTime,'')
|
||||||
|
inventorySets[streamNumberAsClaimedByMsg].add(inventoryHash)
|
||||||
|
inventoryLock.release()
|
||||||
|
with printLock:
|
||||||
|
print 'advertising inv with hash:', inventoryHash.encode('hex')
|
||||||
|
broadcastToSendDataQueues((streamNumberAsClaimedByMsg, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
|
# Now let's enqueue it to be processed ourselves.
|
||||||
|
# If we already have too much data in the queue to be processed, just sleep for now.
|
||||||
|
while shared.objectProcessorQueueSize > 120000000:
|
||||||
|
time.sleep(2)
|
||||||
|
with shared.objectProcessorQueueSizeLock:
|
||||||
|
shared.objectProcessorQueueSize += len(data)
|
||||||
|
objectProcessorQueue.put((objectType,data))
|
||||||
|
|
||||||
|
def checkAndSharegetpubkeyWithPeers(data):
|
||||||
|
if not isProofOfWorkSufficient(data):
|
||||||
|
print 'Proof of work in getpubkey message insufficient.'
|
||||||
|
return
|
||||||
|
if len(data) < 34:
|
||||||
|
print 'getpubkey message doesn\'t contain enough data. Ignoring.'
|
||||||
|
return
|
||||||
|
readPosition = 8 # bypass the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
if embeddedTime > int(time.time()) + 10800:
|
||||||
|
print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime
|
||||||
|
return
|
||||||
|
if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept:
|
||||||
|
print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
|
||||||
|
return
|
||||||
|
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += addressVersionLength
|
||||||
|
streamNumber, streamNumberLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
if not streamNumber in streamsInWhichIAmParticipating:
|
||||||
|
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
|
||||||
|
return
|
||||||
|
readPosition += streamNumberLength
|
||||||
|
|
||||||
|
shared.numberOfInventoryLookupsPerformed += 1
|
||||||
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
inventoryLock.acquire()
|
||||||
|
if inventoryHash in inventory:
|
||||||
|
print 'We have already received this getpubkey request. Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
elif isInSqlInventory(inventoryHash):
|
||||||
|
print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
|
||||||
|
objectType = 'getpubkey'
|
||||||
|
inventory[inventoryHash] = (
|
||||||
|
objectType, streamNumber, data, embeddedTime,'')
|
||||||
|
inventorySets[streamNumber].add(inventoryHash)
|
||||||
|
inventoryLock.release()
|
||||||
|
# This getpubkey request is valid. Forward to peers.
|
||||||
|
with printLock:
|
||||||
|
print 'advertising inv with hash:', inventoryHash.encode('hex')
|
||||||
|
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
|
# Now let's queue it to be processed ourselves.
|
||||||
|
# If we already have too much data in the queue to be processed, just sleep for now.
|
||||||
|
while shared.objectProcessorQueueSize > 120000000:
|
||||||
|
time.sleep(2)
|
||||||
|
with shared.objectProcessorQueueSizeLock:
|
||||||
|
shared.objectProcessorQueueSize += len(data)
|
||||||
|
objectProcessorQueue.put((objectType,data))
|
||||||
|
|
||||||
|
def checkAndSharePubkeyWithPeers(data):
|
||||||
|
if len(data) < 146 or len(data) > 420: # sanity check
|
||||||
|
return
|
||||||
|
# Let us make sure that the proof of work is sufficient.
|
||||||
|
if not isProofOfWorkSufficient(data):
|
||||||
|
print 'Proof of work in pubkey message insufficient.'
|
||||||
|
return
|
||||||
|
|
||||||
|
readPosition = 8 # for the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys:
|
||||||
|
with printLock:
|
||||||
|
print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
|
||||||
|
return
|
||||||
|
if embeddedTime > int(time.time()) + 10800:
|
||||||
|
with printLock:
|
||||||
|
print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.'
|
||||||
|
return
|
||||||
|
addressVersion, varintLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
streamNumber, varintLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
readPosition += varintLength
|
||||||
|
if not streamNumber in streamsInWhichIAmParticipating:
|
||||||
|
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
|
||||||
|
return
|
||||||
|
if addressVersion >= 4:
|
||||||
|
tag = data[readPosition:readPosition + 32]
|
||||||
|
print 'tag in received pubkey is:', tag.encode('hex')
|
||||||
|
else:
|
||||||
|
tag = ''
|
||||||
|
|
||||||
|
shared.numberOfInventoryLookupsPerformed += 1
|
||||||
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
inventoryLock.acquire()
|
||||||
|
if inventoryHash in inventory:
|
||||||
|
print 'We have already received this pubkey. Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
elif isInSqlInventory(inventoryHash):
|
||||||
|
print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
objectType = 'pubkey'
|
||||||
|
inventory[inventoryHash] = (
|
||||||
|
objectType, streamNumber, data, embeddedTime, tag)
|
||||||
|
inventorySets[streamNumber].add(inventoryHash)
|
||||||
|
inventoryLock.release()
|
||||||
|
# This object is valid. Forward it to peers.
|
||||||
|
with printLock:
|
||||||
|
print 'advertising inv with hash:', inventoryHash.encode('hex')
|
||||||
|
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
|
|
||||||
|
# Now let's queue it to be processed ourselves.
|
||||||
|
# If we already have too much data in the queue to be processed, just sleep for now.
|
||||||
|
while shared.objectProcessorQueueSize > 120000000:
|
||||||
|
time.sleep(2)
|
||||||
|
with shared.objectProcessorQueueSizeLock:
|
||||||
|
shared.objectProcessorQueueSize += len(data)
|
||||||
|
objectProcessorQueue.put((objectType,data))
|
||||||
|
|
||||||
|
|
||||||
|
def checkAndShareBroadcastWithPeers(data):
|
||||||
|
# Let us verify that the proof of work is sufficient.
|
||||||
|
if not isProofOfWorkSufficient(data):
|
||||||
|
print 'Proof of work in broadcast message insufficient.'
|
||||||
|
return
|
||||||
|
readPosition = 8 # bypass the nonce
|
||||||
|
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
|
||||||
|
|
||||||
|
# This section is used for the transition from 32 bit time to 64 bit
|
||||||
|
# time in the protocol.
|
||||||
|
if embeddedTime == 0:
|
||||||
|
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
|
||||||
|
readPosition += 8
|
||||||
|
else:
|
||||||
|
readPosition += 4
|
||||||
|
|
||||||
|
if embeddedTime > (int(time.time()) + 10800): # prevent funny business
|
||||||
|
print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.'
|
||||||
|
return
|
||||||
|
if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept):
|
||||||
|
print 'The embedded time in this broadcast message is too old. Ignoring message.'
|
||||||
|
return
|
||||||
|
if len(data) < 180:
|
||||||
|
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
|
||||||
|
return
|
||||||
|
broadcastVersion, broadcastVersionLength = decodeVarint(
|
||||||
|
data[readPosition:readPosition + 10])
|
||||||
|
if broadcastVersion >= 2:
|
||||||
|
streamNumber, streamNumberLength = decodeVarint(data[
|
||||||
|
readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10])
|
||||||
|
if not streamNumber in streamsInWhichIAmParticipating:
|
||||||
|
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
|
||||||
|
return
|
||||||
|
|
||||||
|
shared.numberOfInventoryLookupsPerformed += 1
|
||||||
|
inventoryLock.acquire()
|
||||||
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
if inventoryHash in inventory:
|
||||||
|
print 'We have already received this broadcast object. Ignoring.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
elif isInSqlInventory(inventoryHash):
|
||||||
|
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
|
||||||
|
inventoryLock.release()
|
||||||
|
return
|
||||||
|
# It is valid. Let's let our peers know about it.
|
||||||
|
objectType = 'broadcast'
|
||||||
|
inventory[inventoryHash] = (
|
||||||
|
objectType, streamNumber, data, embeddedTime,'')
|
||||||
|
inventorySets[streamNumber].add(inventoryHash)
|
||||||
|
inventoryLock.release()
|
||||||
|
# This object is valid. Forward it to peers.
|
||||||
|
with printLock:
|
||||||
|
print 'advertising inv with hash:', inventoryHash.encode('hex')
|
||||||
|
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
|
# Now let's queue it to be processed ourselves.
|
||||||
|
# If we already have too much data in the queue to be processed, just sleep for now.
|
||||||
|
while shared.objectProcessorQueueSize > 120000000:
|
||||||
|
time.sleep(2)
|
||||||
|
with shared.objectProcessorQueueSizeLock:
|
||||||
|
shared.objectProcessorQueueSize += len(data)
|
||||||
|
objectProcessorQueue.put((objectType,data))
|
||||||
|
|
||||||
|
|
||||||
helper_startup.loadConfig()
|
helper_startup.loadConfig()
|
||||||
from debug import logger
|
from debug import logger
|
||||||
|
|
Reference in New Issue
Block a user