#Right now, PyBitmessage only support connecting to stream 1. It doesn't yet contain logic to expand into further streams.
softwareVersion='0.2.7'
verbose=2
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.
@ -40,8 +40,6 @@ from defaultKnownNodes import *
importtime
importsocket
importthreading
#import rsa
#from rsa.bigfile import *
importhashlib
fromstructimport*
importpickle
@ -255,7 +253,7 @@ class receiveDataThread(QThread):
whileTrue:
try:
self.data= self.data+self.sock.recv(65536)
self.data+=self.sock.recv(65536)
exceptsocket.timeout:
printLock.acquire()
print'Timeout occurred waiting for data. Closing receiveData thread.'
@ -305,14 +303,14 @@ class receiveDataThread(QThread):
defprocessData(self):
globalverbose
#if verbose >= 2:
#if verbose >= 3:
#printLock.acquire()
#print 'self.data is currently ', repr(self.data)
#printLock.release()
iflen(self.data)<20:#if so little of the data has arrived that we can't even unpack the payload length
pass
elifself.data[0:4]!='\xe9\xbe\xb4\xd9':
ifverbose>=2:
ifverbose>=1:
printLock.acquire()
sys.stderr.write('The magic bytes were not correct. First 40 bytes of data: %s\n'%repr(self.data[0:40]))
print'self.data:',self.data.encode('hex')
@ -332,25 +330,25 @@ class receiveDataThread(QThread):
#Notice that I have divided the averageProofOfWorkNonceTrialsPerByte by two. This makes the POW requirement easier. This gives us wiggle-room: if we decide that we want to make the POW easier, the change won't obsolete old clients because they already expect a lower POW. If we decide that the current work done by clients feels approperate then we can remove this division by 2 and make the requirement match what is actually done by a sending node. If we want to raise the POW requirement then old nodes will HAVE to upgrade no matter what.
self.processbroadcast()#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.
self.processbroadcast(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.
ifself.payloadLength>100000000:#Size is greater than 100 megabytes
@ -548,32 +547,32 @@ class receiveDataThread(QThread):
printLock.release()
#A broadcast message has a valid time and POW and requires processing. The recbroadcast function calls this one.
#Cannot decode incoming broadcast versions higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.
return
readPosition+=broadcastVersionLength
beginningOfPubkeyPosition=readPosition#used when we add the pubkey to our pubkey table
#Cannot decode senderAddressVersion higher than 2. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.
@ -612,7 +611,7 @@ class receiveDataThread(QThread):
#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.)
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''')
sqlSubmitQueue.put(t)
@ -621,7 +620,9 @@ class receiveDataThread(QThread):
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.
#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.
print'The stream number encoded in this msg ('+str(streamNumberAsClaimedByMsg)+') message does not match the stream number on which it was received. Ignoring it.'
self.processmsg(readPosition) #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.
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.
ifself.payloadLength>100000000:#Size is greater than 100 megabytes
@ -805,232 +726,35 @@ class receiveDataThread(QThread):
#The initial decryption passed though there is a small chance that the message isn't actually for me. We'll need to check that the 20 zeros are present.
#print 'initial decryption successful using key', repr(key)
initialDecryptionSuccessful=True
printLock.acquire()
print'Initial decryption passed'
printLock.release()
break
exceptException,err:
infile.seek(0)
#print 'Exception:', err
#print 'outfile len is:', len(outfile.getvalue()),'data is:', repr(outfile.getvalue())
#print 'Initial decryption failed using key', value
#decryption failed for this key. The message is for someone else (or for a different key of mine).
ifinitialDecryptionSuccessfulandoutfile.getvalue()[:20]=='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00':#this run of 0s allows the true message receiver to identify his message
#This is clearly a message bound for me.
outfile.seek(0)
data=outfile.getvalue()
readPosition=20#To start reading past the 20 zero bytes
#Let's store the public key in case we want to reply to this person.
#We don't have the correct nonce in order to 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.)
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.'
#We'll need to make sure that our client will properly process the ackData; if the packet is malformed, it might cause us to clear out self.data and an attacker could use that behavior to determine that we decoded this message.
ackDataValidThusFar=True
iflen(ackData)<24:
print'The length of ackData is unreasonably short. Not sending ackData.'
ackDataValidThusFar=False
ifackData[0:4]!='\xe9\xbe\xb4\xd9':
print'Ackdata magic bytes were wrong. Not sending ackData.'
ackDataValidThusFar=False
ifackDataValidThusFar:
ackDataPayloadLength,=unpack('>L',ackData[16:20])
iflen(ackData)-24!=ackDataPayloadLength:#This ackData includes the protocol header which is not counted in the payload length.
print'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
ackDataValidThusFar=False
ifackDataValidThusFar:
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.
else:
print'This program cannot decode messages from addresses with versions higher than 1. Ignoring.'
statusbar='This program cannot decode messages from addresses with versions higher than 1. Ignoring it.'
statusbar='Error: Cannot decode incoming msg versions higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage. Ignoring message.'
sqlSubmitQueue.put('UPDATE sent SET status=? WHERE ackdata=?')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlLock.release()
self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),self.data[readPosition:24+self.payloadLength],'Acknowledgement of the message received just now.')
self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),encryptedData[readPosition:],'Acknowledgement of the message received just now.')
return
else:
printLock.acquire()
print'This was NOT an acknowledgement bound for me.'#Msg potential ack data:', repr(self.data[readPosition:24+self.payloadLength])
print'This was NOT an acknowledgement bound for me.'
@ -1114,7 +838,7 @@ class receiveDataThread(QThread):
ripe.update(sha.digest())
#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.)
ifembeddedTime<int(time.time())-lengthOfTimeToHoldOnToAllPubkeys-86400:#If the pubkey is more than a month old then reject it. (the 86400 is included to give an extra day of wiggle-room. If the wiggle-room is actually of any use, everyone on the network will delete this pubkey from their database the next time the cleanerThread cleans anyway- except for the node that actually wants the pubkey.)
printLock.acquire()
print'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:',embeddedTime
@ -1288,15 +1011,15 @@ class receiveDataThread(QThread):
#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.
#This getpubkey request is valid so far. Forward to peers.
self.broadcastinv(inventoryHash)
@ -1496,10 +1168,15 @@ class receiveDataThread(QThread):
elifaddressVersionNumber>2:
print'The addressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
return
print'the hash requested in this getpubkey request is:',self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength].encode('hex')
sqlSubmitQueue.put('''SELECT hash, transmitdata, time FROM pubkeys WHERE hash=? AND havecorrectnonce=1 AND time>?''')
sqlSubmitQueue.put(t)
queryreturn=sqlReturnQueue.get()
@ -1515,48 +1192,11 @@ class receiveDataThread(QThread):
inventory[inventoryHash]=(objectType,self.streamNumber,payload,timeEncodedInPubkey)#If the time embedded in this pubkey is more than 3 days old then this object isn't going to last very long in the inventory- the cleanerThread is going to come along and move it from the inventory in memory to the SQL inventory and then delete it from the SQL inventory. It should still find its way back to the original requestor if he is online however.
self.broadcastinv(inventoryHash)
else:#the pubkey is not in our database of pubkeys. Let's check if the requested key is ours (which would mean we should do the POW, put it in the pubkey table, and broadcast out the pubkey.)
ifself.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength]inmyECAddressHashes:#if this address hash is one of mine
ifrequestedHashinmyECAddressHashes:#if this address hash is one of mine
printLock.acquire()
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.'
print'(For pubkey message) Found proof of work',trialValue,'Nonce:',nonce
payload=pack('>Q',nonce)+payload
t=(self.data[36+addressVersionLength+streamNumberLength:56+addressVersionLength+streamNumberLength],True,payload,int(time.time())+1209600)#after two weeks (1,209,600 seconds), we may remove our own pub key from our database. It will be regenerated and put back in the database if it is requested.
sqlLock.acquire()
#** pubkeys insert query not yet fixed! **
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
ifnumberOfItemsInInv==1:#we'll just request this data from the person who advertised the object.
foriinrange(numberOfItemsInInv):
iflen(self.data[24+lengthOfVarint+(32*i):56+lengthOfVarint+(32*i)])==32:#The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously.
foriinrange(numberOfItemsInInv):#upon finishing dealing with an incoming message, the receiveDataThread will request a random object from the peer. This way if we get multiple inv messages from multiple peers which list mostly the same objects, we will make getdata requests for different random objects from the various peers.
iflen(self.data[24+lengthOfVarint+(32*i):56+lengthOfVarint+(32*i)])==32:#The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously.
iflen(data[lengthOfVarint+(32*i):32+lengthOfVarint+(32*i)])==32:#The length of an inventory hash should be 32. If it isn't 32 then the remote node is either badly programmed or behaving nefariously.
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n'%str(err))
printLock.release()
printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n'%str(err))
printLock.release()
break#giving up on unpacking any more. We should still be connected however.
ifrecaddrStream==0:
continue
ifrecaddrStream!=self.streamNumberandrecaddrStream!=(self.streamNumber*2)andrecaddrStream!=((self.streamNumber*2)+1):#if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business.
print'Ignoring IP address in private range:',hostFromAddrMessage
continue
timeSomeoneElseReceivedMessageFromThisNode,=unpack('>I',self.data[24+lengthOfNumberOfAddresses+(34*i):28+lengthOfNumberOfAddresses+(34*i)])#This is the 'time' value in the received addr message.
timeSomeoneElseReceivedMessageFromThisNode,=unpack('>I',data[lengthOfNumberOfAddresses+(34*i):4+lengthOfNumberOfAddresses+(34*i)])#This is the 'time' value in the received addr message.
ifrecaddrStreamnotinknownNodes:#knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it.
#This version message is unreasonably short. Forget it.
return
elifnotself.verackSent:#There is a potential exploit if we don't check to make sure that we have not already received and accepted a version message: An attacker could connect directly to us, send a msg message with the ackdata set to an invalid version message which would cause us to close the connection to the attacker thus proving that we were able to decode the message. Checking the connectionIsOrWasFullyEstablished variable would also suffice.
@ -1925,12 +1556,6 @@ class receiveDataThread(QThread):
pickle.dump(knownNodes,output)
output.close()
#I've commented out this code because it should be up to the newer node to decide whether their protocol version is incompatiable with the remote node's version.
'''if self.remoteProtocolVersion > 1:
print'The remote node''s protocol version is too new for this program to understand. Disconnecting. It is:',self.remoteProtocolVersion
sqlSubmitQueue.put('''select address from addressbook where address=?''')
sqlSubmitQueue.put(t)
queryreturn=sqlReturnQueue.get()
sqlLock.release()
returnqueryreturn!=[]
#This thread exists because SQLITE3 is so un-threadsafe that we must submit queries to it and it puts results back in a different queue. They won't let us just use locks.