# yet contain logic to expand into further streams.
# The software version variable is now held in shared.py
verbose=1
maximumAgeOfAnObjectThatIAmWillingToAccept=216000# Equals two days and 12 hours.
lengthOfTimeToLeaveObjectsInInventory=237600# Equals two days and 18 hours. This should be longer than maximumAgeOfAnObjectThatIAmWillingToAccept so that we don't process messages twice.
lengthOfTimeToHoldOnToAllPubkeys=2419200# Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time.
maximumAgeOfObjectsThatIAdvertiseToOthers=216000# Equals two days and 12 hours
maximumAgeOfNodesThatIAdvertiseToOthers=10800# Equals three hours
useVeryEasyProofOfWorkForTesting=False# If you set this to True while on the normal network, you won't be able to send or sometimes receive messages.
encryptedBroadcastSwitchoverTime=1369735200
importsys
importQueue
fromaddressesimport*
importshared
fromdefaultKnownNodesimport*
importtime
importsocket
importthreading
importhashlib
fromstructimport*
importpickle
importrandom
importsqlite3
fromtimeimportstrftime,localtime,gmtime
importstring
importsocks
importhighlevelcrypto
frompyelliptic.opensslimportOpenSSL
#import ctypes
importsignal# Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully.
# The next 3 are used for the API
fromSimpleXMLRPCServerimport*
importjson
fromsubprocessimportcall# used when the API must execute an outside program
importsingleton
importproofofwork
# Classes
fromclass_sqlThreadimport*
fromclass_singleCleanerimport*
fromclass_singleWorkerimport*
fromclass_outgoingSynSenderimport*
fromclass_singleListenerimport*
fromclass_addressGeneratorimport*
# Helper Functions
importhelper_startup
importhelper_bootstrap
importhelper_inbox
importhelper_sent
importhelper_generic
importhelper_bitcoin
# For each stream to which we connect, several outgoingSynSender threads
# will exist and will collectively create 8 connections with peers.
classoutgoingSynSender(threading.Thread):
def__init__(self):
threading.Thread.__init__(self)
defsetup(self,streamNumber):
self.streamNumber=streamNumber
defrun(self):
time.sleep(1)
globalalreadyAttemptedConnectionsListResetTime
whileTrue:
whilelen(selfInitiatedConnections[self.streamNumber])>=8:# maximum number of outgoing connections = 8
rd.daemon=True# close the main program even if there are threads left
objectsOfWhichThisRemoteNodeIsAlreadyAware={}
rd.setup(sock,HOST,PORT,self.streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware)
rd.start()
shared.printLock.acquire()
printself,'connected to',HOST,'during an outgoing attempt.'
shared.printLock.release()
sd=sendDataThread()
sd.setup(sock,HOST,PORT,self.streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware)
sd.start()
sd.sendVersionMessage()
exceptsocks.GeneralProxyErroraserr:
ifverbose>=2:
shared.printLock.acquire()
print'Could NOT connect to',HOST,'during outgoing attempt.',err
shared.printLock.release()
PORT,timeLastSeen=shared.knownNodes[
self.streamNumber][HOST]
if(int(time.time())-timeLastSeen)>172800andlen(shared.knownNodes[self.streamNumber])>1000:# for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure.
shared.knownNodesLock.acquire()
delshared.knownNodes[self.streamNumber][HOST]
shared.knownNodesLock.release()
shared.printLock.acquire()
print'deleting ',HOST,'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'
print'Bitmessage MIGHT be having trouble connecting to the SOCKS server. '+str(err)
else:
ifverbose>=1:
shared.printLock.acquire()
print'Could NOT connect to',HOST,'during outgoing attempt.',err
shared.printLock.release()
PORT,timeLastSeen=shared.knownNodes[
self.streamNumber][HOST]
if(int(time.time())-timeLastSeen)>172800andlen(shared.knownNodes[self.streamNumber])>1000:# for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure.
shared.knownNodesLock.acquire()
delshared.knownNodes[self.streamNumber][HOST]
shared.knownNodesLock.release()
shared.printLock.acquire()
print'deleting ',HOST,'from knownNodes because it is more than 48 hours old and we could not connect to it.'
shared.printLock.release()
exceptExceptionaserr:
sys.stderr.write(
'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: %s\n'%err)
time.sleep(0.1)
# Only one singleListener thread will ever exist. It creates the
# receiveDataThread and sendDataThread for each incoming connection. Note
# that it cannot set the stream number because it is not known yet- the
# other node will have to tell us its stream number in a version message.
# If we don't care about their stream, we will close the connection
# (within the recversion function of the recieveData thread)
classsingleListener(threading.Thread):
def__init__(self):
threading.Thread.__init__(self)
defrun(self):
# We don't want to accept incoming connections if the user is using a
# SOCKS proxy. If they eventually select proxy 'none' then this will
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.
self.initiatedConnection=False
else:
self.initiatedConnection=True
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.
print'The size of the connectedHostsList is now:',len(shared.connectedHostsList)
shared.printLock.release()
defprocessData(self):
globalverbose
# if verbose >= 3:
# shared.printLock.acquire()
# print 'self.data is currently ', repr(self.data)
# shared.printLock.release()
iflen(self.data)<20:# if so little of the data has arrived that we can't even unpack the payload length
return
ifself.data[0:4]!='\xe9\xbe\xb4\xd9':
ifverbose>=1:
shared.printLock.acquire()
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.'
shared.inventoryLock.release()
return
elifisInSqlInventory(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.
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.'
shared.inventoryLock.release()
return
elifisInSqlInventory(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.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:],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.'
))+' 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.
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
successfullyDecryptMessageTimings.append(
timeRequiredToAttemptToDecryptMessage)
sum=0
foriteminsuccessfullyDecryptMessageTimings:
sum+=item
shared.printLock.acquire()
print'Time to decrypt this message successfully:',timeRequiredToAttemptToDecryptMessage
print'Average time for all message decryption successes since startup:',sum/len(successfullyDecryptMessageTimings)
shared.printLock.release()
defisAckDataValid(self,ackData):
iflen(ackData)<24:
print'The length of ackData is unreasonably short. Not sending ackData.'
returnFalse
ifackData[0:4]!='\xe9\xbe\xb4\xd9':
print'Ackdata magic bytes were wrong. Not sending ackData.'
returnFalse
ackDataPayloadLength,=unpack('>L',ackData[16:20])
iflen(ackData)-24!=ackDataPayloadLength:
print'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'