self.HOST]=0# The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it.
self.connectionIsOrWasFullyEstablished=False# set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
ifself.streamNumber==-1:# This was an incoming connection. Send out a version message if we accept the other node's version message.
]# 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.
print'The magic bytes were not correct. First 40 bytes of data: '+repr(self.data[0:40])
shared.printLock.release()
self.data=""
return
self.payloadLength,=unpack('>L',self.data[16:20])
iflen(self.data)<self.payloadLength+24:# check if the whole message has arrived yet.
return
ifself.data[20:24]!=hashlib.sha512(self.data[24:self.payloadLength+24]).digest()[0:4]:# test the checksum in the message. If it is correct...
print'Checksum incorrect. Clearing this message.'
self.data=self.data[self.payloadLength+24:]
self.processData()
return
# The time we've last seen this node is obviously right now since we
# just received valid data from it. So update the knownNodes list so
# that other peers can be made aware of its existance.
ifself.initiatedConnectionandself.connectionIsOrWasFullyEstablished:# The remote port is only something we should share with others if it is the remote node's incoming port (rather than some random operating-system-assigned outgoing port).
shared.knownNodesLock.acquire()
shared.knownNodes[self.streamNumber][
self.HOST]=(self.PORT,int(time.time()))
shared.knownNodesLock.release()
ifself.payloadLength<=180000000:# If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.)
print'(concerning',self.HOST+')','number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now',len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
self.HOST]# this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
print'(concerning',self.HOST+')','number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now',len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
self.HOST]# this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
print'(concerning',self.HOST+')','number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now',len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)# this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
# Now let us start appending all of these hashes together. They will be
# sent out in a big inv message to our new peer.
forhash,storedValueinbigInvList.items():
payload+=hash
numberOfObjectsInInvMessage+=1
ifnumberOfObjectsInInvMessage>=50000:# We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages.
self.sendinvMessageToJustThisOnePeer(
numberOfObjectsInInvMessage,payload)
payload=''
numberOfObjectsInInvMessage=0
ifnumberOfObjectsInInvMessage>0:
self.sendinvMessageToJustThisOnePeer(
numberOfObjectsInInvMessage,payload)
# Self explanatory. Notice that there is also a broadcastinv function for
print'The stream number encoded in this broadcast message ('+str(streamNumber)+') does not match the stream number on which it was received. Ignoring it.'
return
shared.inventoryLock.acquire()
self.inventoryHash=calculateInventoryHash(data)
ifself.inventoryHashinshared.inventory:
print'We have already received this broadcast object. Ignoring.'
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.
iflen(data)>100000000:# Size is greater than 100 megabytes
print'Cannot decode incoming broadcast versions higher than 2. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
return
ifbroadcastVersion==1:
beginningOfPubkeyPosition=readPosition# used when we add the pubkey to our pubkey table
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
exceptExceptionaserr:
pass
# print 'cryptorObject.decrypt Exception:', err
ifnotinitialDecryptionSuccessful:
# This is not a broadcast I am interested in.
shared.printLock.acquire()
print'Length of time program spent failing to decrypt this v2 broadcast:',time.time()-self.messageProcessingStartTime,'seconds.'
shared.printLock.release()
return
# At this point this is a broadcast I have decrypted and thus am
# interested in.
signedBroadcastVersion,readPosition=decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition=readPosition# used when we add the pubkey to our pubkey table
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])
ifsendersStream!=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.'
print'The stream number encoded in this msg ('+str(streamNumberAsClaimedByMsg)+') message does not match the stream number on which it was received. Ignoring it.'
return
readPosition+=streamNumberAsClaimedByMsgLength
self.inventoryHash=calculateInventoryHash(data)
shared.inventoryLock.acquire()
ifself.inventoryHashinshared.inventory:
print'We have already received this msg message. Ignoring.'
print'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
shared.inventoryLock.release()
return
# This msg message is valid. Let's let our peers know about it.
objectType='msg'
shared.inventory[self.inventoryHash]=(
objectType,self.streamNumber,data,embeddedTime)
shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash)
shared.UISignalQueue.put((
'incrementNumberOfMessagesProcessed','no data'))
self.processmsg(
readPosition,data)# When this function returns, we will have either successfully processed the message bound for us, ignored it because it isn't bound for us, or found problem with the message that warranted ignoring it.
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
# haven't used the specified amount of time, we shall sleep. These
# values are based on test timings and you may change them at-will.
iflen(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.
eliflen(data)>10000000:# Between 100 and 10 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage=20# seconds. Actual length of time it took my computer to decrypt and verify the signature of a 10 MB message: 0.53 seconds. Actual length of time it takes in practice when processing a real message: 1.44 seconds.
eliflen(data)>1000000:# Between 10 and 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage=3# seconds. Actual length of time it took my computer to decrypt and verify the signature of a 1 MB message: 0.18 seconds. Actual length of time it takes in practice when processing a real message: 0.30 seconds.
else:# Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage=.6# seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 KB message: 0.15 seconds. Actual length of time it takes in practice when processing a real message: 0.25 seconds.
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(encryptedData[readPosition:],bitmessagemain.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode(
print'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:',helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey),' ..and here is the testnet address:',helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey),'. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
shared.printLock.release()
# calculate the fromRipe.
sha=hashlib.new('sha512')
sha.update(pubSigningKey+pubEncryptionKey)
ripe=hashlib.new('ripemd160')
ripe.update(sha.digest())
# Let's store the public key in case we want to reply to this
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.
ifshared.config.get('bitmessagesettings','blackwhitelist')=='black':# If we are using a blacklist
t=(fromAddress,)
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put(
'''SELECT label FROM blacklist where address=? and enabled='1'''')
shared.sqlSubmitQueue.put(t)
queryreturn=shared.sqlReturnQueue.get()
shared.sqlLock.release()
ifqueryreturn!=[]:
shared.printLock.acquire()
print'Message ignored because address is in blacklist.'
shared.printLock.release()
blockMessage=True
else:# We're using a whitelist
t=(fromAddress,)
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put(
'''SELECT label FROM whitelist where address=? and enabled='1'''')
shared.sqlSubmitQueue.put(t)
queryreturn=shared.sqlReturnQueue.get()
shared.sqlLock.release()
ifqueryreturn==[]:
print'Message ignored because address not in whitelist.'
blockMessage=True
ifnotblockMessage:
print'fromAddress:',fromAddress
print'First 150 characters of message:',repr(message[:150])
toLabel=shared.config.get(toAddress,'label')
iftoLabel=='':
toLabel=toAddress
ifmessageEncodingType==2:
bodyPositionIndex=string.find(message,'\nBody:')
ifbodyPositionIndex>1:
subject=message[8:bodyPositionIndex]
subject=subject[
:500]# Only save and show the first 500 characters of the subject. Any more is probably an attak.
body=message[bodyPositionIndex+6:]
else:
subject=''
body=message
elifmessageEncodingType==1:
body=message
subject=''
elifmessageEncodingType==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.'