2013-06-24 23:29:15 +02:00
doTimingAttackMitigation = True
2013-06-24 23:29:04 +02:00
2013-06-22 00:29:04 +02:00
import time
import threading
import shared
2013-06-22 01:49:50 +02:00
import hashlib
import socket
import pickle
import random
from struct import unpack , pack
import sys
2013-06-23 21:52:39 +02:00
import string
from subprocess import call # used when the API must execute an outside program
from pyelliptic . openssl import OpenSSL
2013-06-22 01:49:50 +02:00
2013-06-23 21:52:39 +02:00
import highlevelcrypto
2013-06-22 01:49:50 +02:00
from addresses import *
import helper_generic
2013-06-23 21:52:39 +02:00
import helper_bitcoin
import helper_inbox
import helper_sent
2013-06-24 21:51:01 +02:00
import tr
#from bitmessagemain import shared.lengthOfTimeToLeaveObjectsInInventory, shared.lengthOfTimeToHoldOnToAllPubkeys, shared.maximumAgeOfAnObjectThatIAmWillingToAccept, shared.maximumAgeOfObjectsThatIAdvertiseToOthers, shared.maximumAgeOfNodesThatIAdvertiseToOthers, shared.numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer, shared.neededPubkeys
2013-06-22 00:29:04 +02:00
# This thread is created either by the synSenderThread(for outgoing
# connections) or the singleListenerThread(for incoming connectiosn).
class receiveDataThread ( threading . Thread ) :
def __init__ ( self ) :
threading . Thread . __init__ ( self )
self . data = ' '
self . verackSent = False
self . verackReceived = False
def setup (
self ,
sock ,
HOST ,
port ,
streamNumber ,
2013-06-24 21:51:01 +02:00
someObjectsOfWhichThisRemoteNodeIsAlreadyAware ,
2013-06-22 01:49:50 +02:00
selfInitiatedConnections ) :
2013-06-22 00:29:04 +02:00
self . sock = sock
2013-07-30 22:23:18 +02:00
self . peer = shared . Peer ( HOST , port )
2013-06-22 00:29:04 +02:00
self . streamNumber = streamNumber
self . payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header
self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = { }
2013-06-22 01:49:50 +02:00
self . selfInitiatedConnections = selfInitiatedConnections
2013-06-22 00:29:04 +02:00
shared . connectedHostsList [
2013-07-30 22:23:18 +02:00
self . peer ] = 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.
2013-06-22 00:29:04 +02:00
self . connectionIsOrWasFullyEstablished = False # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
if self . streamNumber == - 1 : # This was an incoming connection. Send out a version message if we accept the other node's version message.
self . initiatedConnection = False
else :
self . initiatedConnection = True
2013-06-22 01:49:50 +02:00
self . selfInitiatedConnections [ streamNumber ] [ self ] = 0
2013-06-22 00:29:04 +02:00
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.
2013-06-24 21:51:01 +02:00
self . someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware
2013-06-22 00:29:04 +02:00
def run ( self ) :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' ID of the receiveDataThread is ' , str ( id ( self ) ) + ' . The size of the shared.connectedHostsList is now ' , len ( shared . connectedHostsList )
2013-06-22 00:29:04 +02:00
while True :
2013-07-02 17:43:54 +02:00
dataLen = len ( self . data )
2013-06-22 00:29:04 +02:00
try :
self . data + = self . sock . recv ( 4096 )
except socket . timeout :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' Timeout occurred waiting for data from ' , self . peer , ' . Closing receiveData thread. (ID: ' , str ( id ( self ) ) + ' ) '
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
break
except Exception as err :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' sock.recv error. Closing receiveData thread (HOST: ' , self . peer , ' ID: ' , str ( id ( self ) ) + ' ). ' , err
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
break
# print 'Received', repr(self.data)
2013-07-05 22:56:49 +02:00
if len ( self . data ) == dataLen : # If self.sock.recv returned no data:
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' Connection to ' , self . peer , ' closed. Closing receiveData thread. (ID: ' , str ( id ( self ) ) + ' ) '
2013-06-22 00:29:04 +02:00
break
else :
self . processData ( )
try :
2013-06-22 01:49:50 +02:00
del self . selfInitiatedConnections [ self . streamNumber ] [ self ]
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' removed self (a receiveDataThread) from selfInitiatedConnections '
2013-06-22 00:29:04 +02:00
except :
pass
2013-07-30 22:23:18 +02:00
shared . broadcastToSendDataQueues ( ( 0 , ' shutdown ' , self . peer ) )
2013-06-22 00:29:04 +02:00
try :
2013-07-30 22:23:18 +02:00
del shared . connectedHostsList [ self . peer ]
2013-06-22 00:29:04 +02:00
except Exception as err :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' Could not delete ' , self . peer , ' from shared.connectedHostsList. ' , err
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
try :
2013-06-24 21:51:01 +02:00
del shared . numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer [
2013-07-30 22:23:18 +02:00
self . peer ]
2013-06-22 00:29:04 +02:00
except :
pass
shared . UISignalQueue . put ( ( ' updateNetworkStatusTab ' , ' no data ' ) )
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' The size of the connectedHostsList is now: ' , len ( shared . connectedHostsList )
2013-06-22 00:29:04 +02:00
def processData ( self ) :
2013-06-24 21:51:01 +02:00
# if shared.verbose >= 3:
2013-06-29 19:29:35 +02:00
# with shared.printLock:
# print 'self.data is currently ', repr(self.data)
#
2013-06-22 00:29:04 +02:00
if len ( self . data ) < 20 : # if so little of the data has arrived that we can't even unpack the payload length
return
if self . data [ 0 : 4 ] != ' \xe9 \xbe \xb4 \xd9 ' :
2013-06-24 21:51:01 +02:00
if shared . verbose > = 1 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' The magic bytes were not correct. First 40 bytes of data: ' + repr ( self . data [ 0 : 40 ] )
2013-06-22 00:29:04 +02:00
self . data = " "
return
self . payloadLength , = unpack ( ' >L ' , self . data [ 16 : 20 ] )
if len ( self . data ) < self . payloadLength + 24 : # check if the whole message has arrived yet.
return
if self . data [ 20 : 24 ] != hashlib . sha512 ( self . data [ 24 : self . payloadLength + 24 ] ) . digest ( ) [ 0 : 4 ] : # test the checksum in the message. If it is correct...
print ' Checksum incorrect. Clearing this message. '
self . data = self . data [ self . payloadLength + 24 : ]
self . processData ( )
return
# The time we've last seen this node is obviously right now since we
# just received valid data from it. So update the knownNodes list so
# that other peers can be made aware of its existance.
if self . initiatedConnection and self . connectionIsOrWasFullyEstablished : # The remote port is only something we should share with others if it is the remote node's incoming port (rather than some random operating-system-assigned outgoing port).
shared . knownNodesLock . acquire ( )
2013-07-30 22:23:18 +02:00
shared . knownNodes [ self . streamNumber ] [ self . peer ] = int ( time . time ( ) )
2013-06-22 00:29:04 +02:00
shared . knownNodesLock . release ( )
if self . payloadLength < = 180000000 : # If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.)
remoteCommand = self . data [ 4 : 16 ]
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' remoteCommand ' , repr ( remoteCommand . replace ( ' \x00 ' , ' ' ) ) , ' from ' , self . peer
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
if remoteCommand == ' version \x00 \x00 \x00 \x00 \x00 ' :
self . recversion ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' verack \x00 \x00 \x00 \x00 \x00 \x00 ' :
self . recverack ( )
elif remoteCommand == ' addr \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recaddr ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' getpubkey \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recgetpubkey ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' pubkey \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recpubkey ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' inv \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recinv ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' getdata \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recgetdata ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' msg \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recmsg ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' broadcast \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recbroadcast ( self . data [ 24 : self . payloadLength + 24 ] )
elif remoteCommand == ' ping \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . sendpong ( )
elif remoteCommand == ' pong \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
pass
elif remoteCommand == ' alert \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
pass
self . data = self . data [
self . payloadLength + 24 : ] # take this message out and then process the next message
if self . data == ' ' :
while len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) > 0 :
random . seed ( )
objectHash , = random . sample (
self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave , 1 )
if objectHash in shared . inventory :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Inventory (in memory) already has object listed in inv message. '
2013-06-22 00:29:04 +02:00
del self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave [
objectHash ]
2013-06-24 21:51:01 +02:00
elif shared . isInSqlInventory ( objectHash ) :
if shared . verbose > = 3 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Inventory (SQL on disk) already has object listed in inv message. '
2013-06-22 00:29:04 +02:00
del self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave [
objectHash ]
else :
self . sendgetdata ( objectHash )
del self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave [
objectHash ] # It is possible that the remote node doesn't respond with the object. In that case, we'll very likely get it from someone else anyway.
if len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) == 0 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' (concerning ' , self . peer + ' ) ' , ' number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now ' , len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave )
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
try :
2013-06-24 21:51:01 +02:00
del shared . numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer [
2013-07-30 22:23:18 +02:00
self . peer ] # 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.
2013-06-22 00:29:04 +02:00
except :
pass
break
if len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) == 0 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' (concerning ' , self . peer + ' ) ' , ' number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now ' , len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave )
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
try :
2013-06-24 21:51:01 +02:00
del shared . numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer [
2013-07-30 22:23:18 +02:00
self . peer ] # 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.
2013-06-22 00:29:04 +02:00
except :
pass
if len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) > 0 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' (concerning ' , str ( self . peer ) + ' ) ' , ' number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now ' , len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave )
2013-06-29 19:29:35 +02:00
2013-07-30 22:23:18 +02:00
shared . numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer [ self . peer ] = len (
2013-06-22 00:29:04 +02:00
self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
if len ( self . ackDataThatWeHaveYetToSend ) > 0 :
self . data = self . ackDataThatWeHaveYetToSend . pop ( )
self . processData ( )
def isProofOfWorkSufficient (
self ,
data ,
nonceTrialsPerByte = 0 ,
payloadLengthExtraBytes = 0 ) :
if nonceTrialsPerByte < shared . networkDefaultProofOfWorkNonceTrialsPerByte :
nonceTrialsPerByte = shared . networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes < shared . networkDefaultPayloadLengthExtraBytes :
payloadLengthExtraBytes = shared . networkDefaultPayloadLengthExtraBytes
POW , = unpack ( ' >Q ' , hashlib . sha512 ( hashlib . sha512 ( data [
: 8 ] + hashlib . sha512 ( data [ 8 : ] ) . digest ( ) ) . digest ( ) ) . digest ( ) [ 0 : 8 ] )
# print 'POW:', POW
return POW < = 2 * * 64 / ( ( len ( data ) + payloadLengthExtraBytes ) * ( nonceTrialsPerByte ) )
def sendpong ( self ) :
print ' Sending pong '
try :
self . sock . sendall (
' \xE9 \xBE \xB4 \xD9 \x70 \x6F \x6E \x67 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \xcf \x83 \xe1 \x35 ' )
except Exception as err :
# if not 'Bad file descriptor' in err:
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' sock.sendall error: ' , err
2013-06-22 00:29:04 +02:00
def recverack ( self ) :
print ' verack received '
self . verackReceived = True
if self . verackSent :
# We have thus both sent and received a verack.
self . connectionFullyEstablished ( )
def connectionFullyEstablished ( self ) :
self . connectionIsOrWasFullyEstablished = True
if not self . initiatedConnection :
shared . UISignalQueue . put ( ( ' setStatusIcon ' , ' green ' ) )
self . sock . settimeout (
600 ) # We'll send out a pong every 5 minutes to make sure the connection stays alive if there has been no other traffic to send lately.
shared . UISignalQueue . put ( ( ' updateNetworkStatusTab ' , ' no data ' ) )
2013-07-30 22:23:18 +02:00
remoteNodeSeenTime = shared . knownNodes [
self . streamNumber ] [ self . peer ]
2013-06-29 19:29:35 +02:00
with shared . printLock :
2013-07-30 22:23:18 +02:00
print ' Connection fully established with ' , self . peer
2013-06-29 19:29:35 +02:00
print ' The size of the connectedHostsList is now ' , len ( shared . connectedHostsList )
print ' The length of sendDataQueues is now: ' , len ( shared . sendDataQueues )
print ' broadcasting addr from within connectionFullyEstablished function. '
2013-07-30 22:23:18 +02:00
self . broadcastaddr ( [ ( int ( time . time ( ) ) , self . streamNumber , 1 , self . peer . host ,
self . peer . port ) ] ) # This lets all of our peers know about this new node.
2013-06-22 00:29:04 +02:00
self . sendaddr ( ) # This is one large addr message to this one peer.
if not self . initiatedConnection and len ( shared . connectedHostsList ) > 200 :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' We are connected to too many people. Closing connection. '
2013-07-30 22:23:18 +02:00
shared . broadcastToSendDataQueues ( ( 0 , ' shutdown ' , self . peer ) )
2013-06-22 00:29:04 +02:00
return
self . sendBigInv ( )
def sendBigInv ( self ) :
shared . sqlLock . acquire ( )
# Select all hashes which are younger than two days old and in this
# stream.
2013-06-24 21:51:01 +02:00
t = ( int ( time . time ( ) ) - shared . maximumAgeOfObjectsThatIAdvertiseToOthers , int (
time . time ( ) ) - shared . lengthOfTimeToHoldOnToAllPubkeys , self . streamNumber )
2013-06-22 00:29:04 +02:00
shared . sqlSubmitQueue . put (
''' SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<> ' pubkey ' ) or (receivedtime>? and objecttype= ' pubkey ' )) and streamnumber=? ''' )
shared . sqlSubmitQueue . put ( t )
queryreturn = shared . sqlReturnQueue . get ( )
shared . sqlLock . release ( )
bigInvList = { }
for row in queryreturn :
hash , = row
2013-06-24 21:51:01 +02:00
if hash not in self . someObjectsOfWhichThisRemoteNodeIsAlreadyAware :
2013-06-22 00:29:04 +02:00
bigInvList [ hash ] = 0
# We also have messages in our inventory in memory (which is a python
# dictionary). Let's fetch those too.
for hash , storedValue in shared . inventory . items ( ) :
2013-06-24 21:51:01 +02:00
if hash not in self . someObjectsOfWhichThisRemoteNodeIsAlreadyAware :
2013-06-22 00:29:04 +02:00
objectType , streamNumber , payload , receivedTime = storedValue
2013-06-24 21:51:01 +02:00
if streamNumber == self . streamNumber and receivedTime > int ( time . time ( ) ) - shared . maximumAgeOfObjectsThatIAdvertiseToOthers :
2013-06-22 00:29:04 +02:00
bigInvList [ hash ] = 0
numberOfObjectsInInvMessage = 0
payload = ' '
# Now let us start appending all of these hashes together. They will be
# sent out in a big inv message to our new peer.
for hash , storedValue in bigInvList . items ( ) :
payload + = hash
numberOfObjectsInInvMessage + = 1
if numberOfObjectsInInvMessage > = 50000 : # We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages.
self . sendinvMessageToJustThisOnePeer (
numberOfObjectsInInvMessage , payload )
payload = ' '
numberOfObjectsInInvMessage = 0
if numberOfObjectsInInvMessage > 0 :
self . sendinvMessageToJustThisOnePeer (
numberOfObjectsInInvMessage , payload )
# Self explanatory. Notice that there is also a broadcastinv function for
# broadcasting invs to everyone in our stream.
def sendinvMessageToJustThisOnePeer ( self , numberOfObjects , payload ) :
payload = encodeVarint ( numberOfObjects ) + payload
headerData = ' \xe9 \xbe \xb4 \xd9 ' # magic bits, slighly different from Bitcoin's magic bits.
headerData + = ' inv \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 '
headerData + = pack ( ' >L ' , len ( payload ) )
headerData + = hashlib . sha512 ( payload ) . digest ( ) [ : 4 ]
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Sending huge inv message with ' , numberOfObjects , ' objects to just this one peer '
2013-06-22 00:29:04 +02:00
try :
self . sock . sendall ( headerData + payload )
except Exception as err :
# if not 'Bad file descriptor' in err:
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' sock.sendall error: ' , err
2013-06-22 00:29:04 +02:00
# We have received a broadcast message
def recbroadcast ( self , data ) :
self . messageProcessingStartTime = time . time ( )
# First we must check to make sure the proof of work is sufficient.
if not self . isProofOfWorkSufficient ( data ) :
print ' Proof of work in broadcast message insufficient. '
return
readPosition = 8 # bypass the nonce
embeddedTime , = unpack ( ' >I ' , data [ readPosition : readPosition + 4 ] )
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0 :
embeddedTime , = unpack ( ' >Q ' , data [ readPosition : readPosition + 8 ] )
readPosition + = 8
else :
readPosition + = 4
if embeddedTime > ( int ( time . time ( ) ) + 10800 ) : # prevent funny business
print ' The embedded time in this broadcast message is more than three hours in the future. That doesn \' t make sense. Ignoring message. '
return
2013-06-24 21:51:01 +02:00
if embeddedTime < ( int ( time . time ( ) ) - shared . maximumAgeOfAnObjectThatIAmWillingToAccept ) :
2013-06-22 00:29:04 +02:00
print ' The embedded time in this broadcast message is too old. Ignoring message. '
return
if len ( data ) < 180 :
print ' The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message. '
return
# Let us check to make sure the stream number is correct (thus
# preventing an individual from sending broadcasts out on the wrong
# streams or all streams).
broadcastVersion , broadcastVersionLength = decodeVarint (
data [ readPosition : readPosition + 10 ] )
if broadcastVersion > = 2 :
streamNumber , streamNumberLength = decodeVarint ( data [
readPosition + broadcastVersionLength : readPosition + broadcastVersionLength + 10 ] )
if streamNumber != self . streamNumber :
print ' The stream number encoded in this broadcast message ( ' + str ( streamNumber ) + ' ) does not match the stream number on which it was received. Ignoring it. '
return
shared . inventoryLock . acquire ( )
self . inventoryHash = calculateInventoryHash ( data )
if self . inventoryHash in shared . inventory :
print ' We have already received this broadcast object. Ignoring. '
shared . inventoryLock . release ( )
return
2013-06-24 21:51:01 +02:00
elif shared . isInSqlInventory ( self . inventoryHash ) :
2013-06-22 00:29:04 +02:00
print ' We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it. '
shared . inventoryLock . release ( )
return
# It is valid so far. Let's let our peers know about it.
objectType = ' broadcast '
shared . inventory [ self . inventoryHash ] = (
objectType , self . streamNumber , data , embeddedTime )
shared . inventoryLock . release ( )
self . broadcastinv ( self . inventoryHash )
shared . UISignalQueue . put ( (
' incrementNumberOfBroadcastsProcessed ' , ' no data ' ) )
self . processbroadcast (
readPosition , data ) # When this function returns, we will have either successfully processed this broadcast because we are interested in it, ignored it because we aren't interested in it, or found problem with the broadcast that warranted ignoring it.
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
# haven't used the specified amount of time, we shall sleep. These
# values are mostly the same values used for msg messages although
# broadcast messages are processed faster.
if len ( data ) > 100000000 : # Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds.
elif len ( data ) > 10000000 : # Between 100 and 10 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds.
elif len ( data ) > 1000000 : # Between 10 and 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds.
else : # Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds.
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
( time . time ( ) - self . messageProcessingStartTime )
2013-06-24 23:29:04 +02:00
if sleepTime > 0 and doTimingAttackMitigation :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Timing attack mitigation: Sleeping for ' , sleepTime , ' seconds. '
2013-06-22 00:29:04 +02:00
time . sleep ( sleepTime )
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Total message processing time: ' , time . time ( ) - self . messageProcessingStartTime , ' seconds. '
2013-06-22 00:29:04 +02:00
# A broadcast message has a valid time and POW and requires processing.
# The recbroadcast function calls this one.
def processbroadcast ( self , readPosition , data ) :
broadcastVersion , broadcastVersionLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
readPosition + = broadcastVersionLength
if broadcastVersion < 1 or broadcastVersion > 2 :
print ' Cannot decode incoming broadcast versions higher than 2. Assuming the sender isn \' t being silly, you should upgrade Bitmessage because this message shall be ignored. '
return
if broadcastVersion == 1 :
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion , sendersAddressVersionLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
if sendersAddressVersion < = 1 or sendersAddressVersion > = 3 :
# Cannot decode senderAddressVersion higher than 2. Assuming
# the sender isn\'t being silly, you should upgrade Bitmessage
# because this message shall be ignored.
return
readPosition + = sendersAddressVersionLength
if sendersAddressVersion == 2 :
sendersStream , sendersStreamLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
readPosition + = sendersStreamLength
behaviorBitfield = data [ readPosition : readPosition + 4 ]
readPosition + = 4
sendersPubSigningKey = ' \x04 ' + \
data [ readPosition : readPosition + 64 ]
readPosition + = 64
sendersPubEncryptionKey = ' \x04 ' + \
data [ readPosition : readPosition + 64 ]
readPosition + = 64
endOfPubkeyPosition = readPosition
sendersHash = data [ readPosition : readPosition + 20 ]
if sendersHash not in shared . broadcastSendersForWhichImWatching :
# Display timing data
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Time spent deciding that we are not interested in this v1 broadcast: ' , time . time ( ) - self . messageProcessingStartTime
2013-06-22 00:29:04 +02:00
return
# At this point, this message claims to be from sendersHash and
# we are interested in it. We still have to hash the public key
# to make sure it is truly the key that matches the hash, and
# also check the signiture.
readPosition + = 20
sha = hashlib . new ( ' sha512 ' )
sha . update ( sendersPubSigningKey + sendersPubEncryptionKey )
ripe = hashlib . new ( ' ripemd160 ' )
ripe . update ( sha . digest ( ) )
if ripe . digest ( ) != sendersHash :
# The sender of this message lied.
return
messageEncodingType , messageEncodingTypeLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
if messageEncodingType == 0 :
return
readPosition + = messageEncodingTypeLength
messageLength , messageLengthLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
readPosition + = messageLengthLength
message = data [ readPosition : readPosition + messageLength ]
readPosition + = messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength , signatureLengthLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
readPosition + = signatureLengthLength
signature = data [ readPosition : readPosition + signatureLength ]
try :
if not highlevelcrypto . verify ( data [ 12 : readPositionAtBottomOfMessage ] , signature , sendersPubSigningKey . encode ( ' hex ' ) ) :
print ' ECDSA verify failed '
return
print ' ECDSA verify passed '
except Exception as err :
print ' ECDSA verify failed ' , err
return
# verify passed
# Let's store the public key in case we want to reply to this person.
# We don't have the correct nonce or time (which would let us
# send out a pubkey message) so we'll just fill it with 1's. We
# won't be able to send this pubkey to others (without doing
# the proof of work ourselves, which this program is programmed
# to not do.)
t = ( ripe . digest ( ) , ' \xFF \xFF \xFF \xFF \xFF \xFF \xFF \xFF ' + ' \xFF \xFF \xFF \xFF ' + data [
beginningOfPubkeyPosition : endOfPubkeyPosition ] , int ( time . time ( ) ) , ' yes ' )
shared . sqlLock . acquire ( )
shared . sqlSubmitQueue . put (
''' INSERT INTO pubkeys VALUES (?,?,?,?) ''' )
shared . sqlSubmitQueue . put ( t )
shared . sqlReturnQueue . get ( )
shared . sqlSubmitQueue . put ( ' commit ' )
shared . sqlLock . release ( )
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the
# POW and send it.
self . possibleNewPubkey ( ripe . digest ( ) )
fromAddress = encodeAddress (
sendersAddressVersion , sendersStream , ripe . digest ( ) )
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' fromAddress: ' , fromAddress
2013-06-22 00:29:04 +02:00
if messageEncodingType == 2 :
2013-07-12 12:16:34 +02:00
subject , body = self . decodeType2Message ( message )
2013-06-22 00:29:04 +02:00
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
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Time spent processing this interesting broadcast: ' , time . time ( ) - self . messageProcessingStartTime
2013-06-22 00:29:04 +02:00
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.
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Length of time program spent failing to decrypt this v2 broadcast: ' , time . time ( ) - self . messageProcessingStartTime , ' seconds. '
2013-06-22 00:29:04 +02:00
return
# At this point this is a broadcast I have decrypted and thus am
# interested in.
signedBroadcastVersion , readPosition = decodeVarint (
decryptedData [ : 10 ] )
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion , sendersAddressVersionLength = decodeVarint (
decryptedData [ readPosition : readPosition + 9 ] )
if sendersAddressVersion < 2 or sendersAddressVersion > 3 :
print ' Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn \' t being silly, you should upgrade Bitmessage because this message shall be ignored. '
return
readPosition + = sendersAddressVersionLength
sendersStream , sendersStreamLength = decodeVarint (
decryptedData [ readPosition : readPosition + 9 ] )
if sendersStream != cleartextStreamNumber :
print ' The stream number outside of the encryption on which the POW was completed doesn \' t match the stream number inside the encryption. Ignoring broadcast. '
return
readPosition + = sendersStreamLength
behaviorBitfield = decryptedData [ readPosition : readPosition + 4 ]
readPosition + = 4
sendersPubSigningKey = ' \x04 ' + \
decryptedData [ readPosition : readPosition + 64 ]
readPosition + = 64
sendersPubEncryptionKey = ' \x04 ' + \
decryptedData [ readPosition : readPosition + 64 ]
readPosition + = 64
if sendersAddressVersion > = 3 :
requiredAverageProofOfWorkNonceTrialsPerByte , varintLength = decodeVarint (
decryptedData [ readPosition : readPosition + 10 ] )
readPosition + = varintLength
print ' sender \' s requiredAverageProofOfWorkNonceTrialsPerByte is ' , requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes , varintLength = decodeVarint (
decryptedData [ readPosition : readPosition + 10 ] )
readPosition + = varintLength
print ' sender \' s requiredPayloadLengthExtraBytes is ' , requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition
sha = hashlib . new ( ' sha512 ' )
sha . update ( sendersPubSigningKey + sendersPubEncryptionKey )
ripe = hashlib . new ( ' ripemd160 ' )
ripe . update ( sha . digest ( ) )
if toRipe != ripe . digest ( ) :
print ' The encryption key used to encrypt this message doesn \' t match the keys inbedded in the message itself. Ignoring message. '
return
messageEncodingType , messageEncodingTypeLength = decodeVarint (
decryptedData [ readPosition : readPosition + 9 ] )
if messageEncodingType == 0 :
return
readPosition + = messageEncodingTypeLength
messageLength , messageLengthLength = decodeVarint (
decryptedData [ readPosition : readPosition + 9 ] )
readPosition + = messageLengthLength
message = decryptedData [ readPosition : readPosition + messageLength ]
readPosition + = messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength , signatureLengthLength = decodeVarint (
decryptedData [ readPosition : readPosition + 9 ] )
readPosition + = signatureLengthLength
signature = decryptedData [
readPosition : readPosition + signatureLength ]
try :
if not highlevelcrypto . verify ( decryptedData [ : readPositionAtBottomOfMessage ] , signature , sendersPubSigningKey . encode ( ' hex ' ) ) :
print ' ECDSA verify failed '
return
print ' ECDSA verify passed '
except Exception as err :
print ' ECDSA verify failed ' , err
return
# verify passed
# Let's store the public key in case we want to reply to this
# person.
t = ( ripe . digest ( ) , ' \xFF \xFF \xFF \xFF \xFF \xFF \xFF \xFF ' + ' \xFF \xFF \xFF \xFF ' + decryptedData [
beginningOfPubkeyPosition : endOfPubkeyPosition ] , int ( time . time ( ) ) , ' yes ' )
shared . sqlLock . acquire ( )
shared . sqlSubmitQueue . put (
''' INSERT INTO pubkeys VALUES (?,?,?,?) ''' )
shared . sqlSubmitQueue . put ( t )
shared . sqlReturnQueue . get ( )
shared . sqlSubmitQueue . put ( ' commit ' )
shared . sqlLock . release ( )
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self . possibleNewPubkey ( ripe . digest ( ) )
fromAddress = encodeAddress (
sendersAddressVersion , sendersStream , ripe . digest ( ) )
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' fromAddress: ' , fromAddress
2013-06-22 00:29:04 +02:00
if messageEncodingType == 2 :
2013-07-12 12:16:34 +02:00
subject , body = self . decodeType2Message ( message )
2013-06-22 00:29:04 +02:00
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
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Time spent processing this interesting broadcast: ' , time . time ( ) - self . messageProcessingStartTime
2013-06-22 00:29:04 +02:00
# We have received a msg message.
def recmsg ( self , data ) :
self . messageProcessingStartTime = time . time ( )
# First we must check to make sure the proof of work is sufficient.
if not self . isProofOfWorkSufficient ( data ) :
print ' Proof of work in msg message insufficient. '
return
readPosition = 8
embeddedTime , = unpack ( ' >I ' , data [ readPosition : readPosition + 4 ] )
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0 :
embeddedTime , = unpack ( ' >Q ' , data [ readPosition : readPosition + 8 ] )
readPosition + = 8
else :
readPosition + = 4
if embeddedTime > int ( time . time ( ) ) + 10800 :
print ' The time in the msg message is too new. Ignoring it. Time: ' , embeddedTime
return
2013-06-24 21:51:01 +02:00
if embeddedTime < int ( time . time ( ) ) - shared . maximumAgeOfAnObjectThatIAmWillingToAccept :
2013-06-22 00:29:04 +02:00
print ' The time in the msg message is too old. Ignoring it. Time: ' , embeddedTime
return
streamNumberAsClaimedByMsg , streamNumberAsClaimedByMsgLength = decodeVarint (
data [ readPosition : readPosition + 9 ] )
if streamNumberAsClaimedByMsg != self . streamNumber :
print ' The stream number encoded in this msg ( ' + str ( streamNumberAsClaimedByMsg ) + ' ) message does not match the stream number on which it was received. Ignoring it. '
return
readPosition + = streamNumberAsClaimedByMsgLength
self . inventoryHash = calculateInventoryHash ( data )
shared . inventoryLock . acquire ( )
if self . inventoryHash in shared . inventory :
print ' We have already received this msg message. Ignoring. '
shared . inventoryLock . release ( )
return
2013-06-24 21:51:01 +02:00
elif shared . isInSqlInventory ( self . inventoryHash ) :
2013-06-22 00:29:04 +02:00
print ' We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it. '
shared . inventoryLock . release ( )
return
# This msg message is valid. Let's let our peers know about it.
objectType = ' msg '
shared . inventory [ self . inventoryHash ] = (
objectType , self . streamNumber , data , embeddedTime )
shared . inventoryLock . release ( )
self . broadcastinv ( self . inventoryHash )
shared . UISignalQueue . put ( (
' incrementNumberOfMessagesProcessed ' , ' no data ' ) )
self . processmsg (
readPosition , data ) # When this function returns, we will have either successfully processed the message bound for us, ignored it because it isn't bound for us, or found problem with the message that warranted ignoring it.
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
# haven't used the specified amount of time, we shall sleep. These
# values are based on test timings and you may change them at-will.
if len ( data ) > 100000000 : # Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds.
elif len ( data ) > 10000000 : # Between 100 and 10 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 20 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 10 MB message: 0.53 seconds. Actual length of time it takes in practice when processing a real message: 1.44 seconds.
elif len ( data ) > 1000000 : # Between 10 and 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = 3 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 1 MB message: 0.18 seconds. Actual length of time it takes in practice when processing a real message: 0.30 seconds.
else : # Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 KB message: 0.15 seconds. Actual length of time it takes in practice when processing a real message: 0.25 seconds.
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
( time . time ( ) - self . messageProcessingStartTime )
2013-06-24 23:29:04 +02:00
if sleepTime > 0 and doTimingAttackMitigation :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Timing attack mitigation: Sleeping for ' , sleepTime , ' seconds. '
2013-06-22 00:29:04 +02:00
time . sleep ( sleepTime )
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Total message processing time: ' , time . time ( ) - self . messageProcessingStartTime , ' seconds. '
2013-06-22 00:29:04 +02:00
# 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.
2013-06-24 21:51:01 +02:00
if encryptedData [ readPosition : ] in shared . ackdataForWhichImWatching :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' This msg IS an acknowledgement bound for me. '
2013-06-24 21:51:01 +02:00
del shared . ackdataForWhichImWatching [ encryptedData [ readPosition : ] ]
2013-06-22 00:29:04 +02:00
t = ( ' ackreceived ' , encryptedData [ readPosition : ] )
shared . sqlLock . acquire ( )
shared . sqlSubmitQueue . put (
' UPDATE sent SET status=? WHERE ackdata=? ' )
shared . sqlSubmitQueue . put ( t )
shared . sqlReturnQueue . get ( )
shared . sqlSubmitQueue . put ( ' commit ' )
shared . sqlLock . release ( )
2013-06-24 21:51:01 +02:00
shared . UISignalQueue . put ( ( ' updateSentItemStatusByAckdata ' , ( encryptedData [ readPosition : ] , tr . translateText ( " MainWindow " , ' Acknowledgement of the message received. % 1 ' ) . arg ( unicode (
2013-06-23 21:52:39 +02:00
time . strftime ( shared . config . get ( ' bitmessagesettings ' , ' timeformat ' ) , time . localtime ( int ( time . time ( ) ) ) ) , ' utf-8 ' ) ) ) ) )
2013-06-22 00:29:04 +02:00
return
else :
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' This was NOT an acknowledgement bound for me. '
2013-06-24 21:51:01 +02:00
# print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching
2013-06-29 19:29:35 +02:00
2013-06-22 00:29:04 +02:00
# 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
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' EC decryption successful using key associated with ripe hash: ' , key . encode ( ' hex ' )
2013-06-22 00:29:04 +02:00
break
except Exception as err :
pass
# print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful :
# This is not a message bound for me.
2013-06-29 19:29:35 +02:00
with shared . printLock :
print ' Length of time program spent failing to decrypt this message: ' , time . time ( ) - self . messageProcessingStartTime , ' seconds. '
2013-06-22 00:29:04 +02:00
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