2013-02-18 21:22:48 +01:00
#!/usr/bin/env python2.7
2012-11-19 20:45:05 +01:00
# Copyright (c) 2012 Jonathan Warren
# Copyright (c) 2012 The Bitmessage developers
# Distributed under the MIT/X11 software license. See the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#Right now, PyBitmessage only support connecting to stream 1. It doesn't yet contain logic to expand into further streams.
2013-02-21 05:35:10 +01:00
softwareVersion = ' 0.2.5 '
2012-11-19 20:45:05 +01:00
verbose = 2
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.
2013-02-11 22:28:38 +01:00
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.
2012-11-19 20:45:05 +01:00
maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 #Equals two days and 12 hours
maximumAgeOfNodesThatIAdvertiseToOthers = 10800 #Equals three hours
2013-01-21 01:00:46 +01:00
storeConfigFilesInSameDirectoryAsProgram = False
2013-01-22 20:29:49 +01:00
useVeryEasyProofOfWorkForTesting = False #If you set this to True while on the normal network, you won't be able to send or sometimes receive messages.
2012-11-19 20:45:05 +01:00
import sys
try :
from PyQt4 . QtCore import *
from PyQt4 . QtGui import *
except Exception , err :
2012-11-26 01:36:29 +01:00
print ' PyBitmessage requires PyQt. You can download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \' PyQt Download \' (without quotes). '
2012-11-19 20:45:05 +01:00
print ' Error message: ' , err
sys . exit ( )
import ConfigParser
from bitmessageui import *
from newaddressdialog import *
from newsubscriptiondialog import *
2013-01-24 22:07:24 +01:00
from regenerateaddresses import *
2013-02-26 00:09:32 +01:00
from specialaddressbehavior import *
2012-11-19 20:45:05 +01:00
from settings import *
from about import *
from help import *
from iconglossary import *
from addresses import *
import Queue
from defaultKnownNodes import *
import time
import socket
import threading
import rsa
from rsa . bigfile import *
import hashlib
from struct import *
import pickle
import random
import sqlite3
import threading #used for the locks, not for the threads
import cStringIO
from time import strftime , localtime
import os
2012-12-04 18:11:14 +01:00
import string
2012-12-18 19:09:10 +01:00
import socks
2013-01-21 01:00:46 +01:00
#import pyelliptic
import highlevelcrypto
2013-01-16 17:52:52 +01:00
from pyelliptic . openssl import OpenSSL
import ctypes
from pyelliptic import arithmetic
2012-11-19 20:45:05 +01:00
#For each stream to which we connect, one outgoingSynSender thread will exist and will create 8 connections with peers.
class outgoingSynSender ( QThread ) :
def __init__ ( self , parent = None ) :
QThread . __init__ ( self , parent )
self . selfInitiatedConnectionList = [ ] #This is a list of current connections (the thread pointers at least)
self . alreadyAttemptedConnectionsList = [ ] #This is a list of nodes to which we have already attempted a connection
def setup ( self , streamNumber ) :
self . streamNumber = streamNumber
def run ( self ) :
time . sleep ( 1 )
resetTime = int ( time . time ( ) ) #used below to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect.
while True :
2013-02-26 00:09:32 +01:00
#time.sleep(999999)#I sometimes use this to prevent connections for testing.
2012-11-19 20:45:05 +01:00
if len ( self . selfInitiatedConnectionList ) < 8 : #maximum number of outgoing connections = 8
random . seed ( )
HOST , = random . sample ( knownNodes [ self . streamNumber ] , 1 )
while HOST in self . alreadyAttemptedConnectionsList or HOST in connectedHostsList :
#print 'choosing new sample'
random . seed ( )
HOST , = random . sample ( knownNodes [ self . streamNumber ] , 1 )
time . sleep ( 1 )
#Clear out the alreadyAttemptedConnectionsList every half hour so that this program will again attempt a connection to any nodes, even ones it has already tried.
if ( int ( time . time ( ) ) - resetTime ) > 1800 :
self . alreadyAttemptedConnectionsList = [ ]
resetTime = int ( time . time ( ) )
self . alreadyAttemptedConnectionsList . append ( HOST )
PORT , timeNodeLastSeen = knownNodes [ self . streamNumber ] [ HOST ]
2012-12-18 19:09:10 +01:00
sock = socks . socksocket ( socket . AF_INET , socket . SOCK_STREAM )
2012-12-19 07:22:04 +01:00
sock . settimeout ( 20 )
2012-12-18 19:09:10 +01:00
if config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) == ' none ' :
printLock . acquire ( )
print ' Trying an outgoing connection to ' , HOST , ' : ' , PORT
printLock . release ( )
#sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) == ' SOCKS4a ' :
printLock . acquire ( )
print ' (Using SOCKS4a) Trying an outgoing connection to ' , HOST , ' : ' , PORT
printLock . release ( )
proxytype = socks . PROXY_TYPE_SOCKS4
sockshostname = config . get ( ' bitmessagesettings ' , ' sockshostname ' )
socksport = config . getint ( ' bitmessagesettings ' , ' socksport ' )
rdns = True #Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if config . getboolean ( ' bitmessagesettings ' , ' socksauthentication ' ) :
socksusername = config . get ( ' bitmessagesettings ' , ' socksusername ' )
sockspassword = config . get ( ' bitmessagesettings ' , ' sockspassword ' )
sock . setproxy ( proxytype , sockshostname , socksport , rdns , socksusername , sockspassword )
else :
sock . setproxy ( proxytype , sockshostname , socksport , rdns )
elif config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) == ' SOCKS5 ' :
printLock . acquire ( )
print ' (Using SOCKS5) Trying an outgoing connection to ' , HOST , ' : ' , PORT
printLock . release ( )
proxytype = socks . PROXY_TYPE_SOCKS5
sockshostname = config . get ( ' bitmessagesettings ' , ' sockshostname ' )
socksport = config . getint ( ' bitmessagesettings ' , ' socksport ' )
rdns = True #Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if config . getboolean ( ' bitmessagesettings ' , ' socksauthentication ' ) :
socksusername = config . get ( ' bitmessagesettings ' , ' socksusername ' )
sockspassword = config . get ( ' bitmessagesettings ' , ' sockspassword ' )
sock . setproxy ( proxytype , sockshostname , socksport , rdns , socksusername , sockspassword )
else :
sock . setproxy ( proxytype , sockshostname , socksport , rdns )
2012-11-19 20:45:05 +01:00
try :
sock . connect ( ( HOST , PORT ) )
rd = receiveDataThread ( )
self . emit ( SIGNAL ( " passObjectThrough(PyQt_PyObject) " ) , rd )
2013-02-03 06:16:50 +01:00
objectsOfWhichThisRemoteNodeIsAlreadyAware = { }
rd . setup ( sock , HOST , PORT , self . streamNumber , self . selfInitiatedConnectionList , objectsOfWhichThisRemoteNodeIsAlreadyAware )
2012-11-19 20:45:05 +01:00
rd . start ( )
2012-12-10 20:48:00 +01:00
printLock . acquire ( )
2012-11-19 20:45:05 +01:00
print self , ' connected to ' , HOST , ' during outgoing attempt. '
2012-12-10 20:48:00 +01:00
printLock . release ( )
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
sd = sendDataThread ( )
2013-02-03 06:16:50 +01:00
sd . setup ( sock , HOST , PORT , self . streamNumber , objectsOfWhichThisRemoteNodeIsAlreadyAware )
2012-11-19 20:45:05 +01:00
sd . start ( )
sd . sendVersionMessage ( )
2012-12-18 19:09:10 +01:00
except socks . GeneralProxyError , err :
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
2012-11-19 20:45:05 +01:00
print ' Could NOT connect to ' , HOST , ' during outgoing attempt. ' , err
2013-01-22 06:21:32 +01:00
printLock . release ( )
2012-11-19 20:45:05 +01:00
PORT , timeLastSeen = knownNodes [ self . streamNumber ] [ HOST ]
2012-12-18 19:09:10 +01:00
if ( int ( time . time ( ) ) - timeLastSeen ) > 172800 and len ( 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.
del knownNodes [ self . streamNumber ] [ HOST ]
print ' deleting ' , HOST , ' from knownNodes because it is more than 48 hours old and we could not connect to it. '
except socks . Socks5AuthError , err :
self . emit ( SIGNAL ( " updateStatusBar(PyQt_PyObject) " ) , " SOCKS5 Authentication problem: " + str ( err ) )
except socks . Socks5Error , err :
pass
print ' SOCKS5 error. (It is possible that the server wants authentication).) ' , str ( err )
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"SOCKS5 error. Server might require authentication. "+str(err))
except socks . Socks4Error , err :
print ' Socks4Error: ' , err
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"SOCKS4 error: "+str(err))
except socket . error , err :
if config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) [ 0 : 5 ] == ' SOCKS ' :
2012-12-18 22:36:37 +01:00
print ' Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str ( err )
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"Problem: Bitmessage can not connect to the SOCKS server. "+str(err))
2012-12-18 19:09:10 +01:00
else :
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
2012-12-18 19:09:10 +01:00
print ' Could NOT connect to ' , HOST , ' during outgoing attempt. ' , err
2013-01-22 06:21:32 +01:00
printLock . release ( )
2012-12-18 19:09:10 +01:00
PORT , timeLastSeen = knownNodes [ self . streamNumber ] [ HOST ]
if ( int ( time . time ( ) ) - timeLastSeen ) > 172800 and len ( 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.
2012-11-19 20:45:05 +01:00
del knownNodes [ self . streamNumber ] [ HOST ]
print ' deleting ' , HOST , ' from knownNodes because it is more than 48 hours old and we could not connect to it. '
2012-12-18 19:32:48 +01:00
except Exception , err :
2012-12-18 22:36:37 +01:00
print ' An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: ' , err
2013-02-03 06:16:50 +01:00
time . sleep ( 0.1 )
2012-11-19 20:45:05 +01:00
#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)
class singleListener ( QThread ) :
def __init__ ( self , parent = None ) :
QThread . __init__ ( self , parent )
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
def run ( self ) :
2012-12-18 19:09:10 +01:00
#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 start listening for connections.
while config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) [ 0 : 5 ] == ' SOCKS ' :
time . sleep ( 300 )
2012-11-19 20:45:05 +01:00
2013-02-03 06:16:50 +01:00
print ' Listening for incoming connections. '
2012-11-19 20:45:05 +01:00
HOST = ' ' # Symbolic name meaning all available interfaces
PORT = config . getint ( ' bitmessagesettings ' , ' port ' )
sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )
#This option apparently avoids the TIME_WAIT state so that we can rebind faster
sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
sock . bind ( ( HOST , PORT ) )
sock . listen ( 2 )
2012-12-18 19:09:10 +01:00
self . incomingConnectionList = [ ] #This list isn't used for anything. The reason it exists is because receiveData threads expect that a list be passed to them. They expect this because the outgoingSynSender thread DOES use a similar list to keep track of the number of outgoing connections it has created.
2012-11-19 20:45:05 +01:00
while True :
2013-01-22 06:21:32 +01:00
#We don't want to accept incoming connections if the user is using a SOCKS proxy. If the user eventually select proxy 'none' then this will start listening for connections.
2012-12-18 19:09:10 +01:00
while config . get ( ' bitmessagesettings ' , ' socksproxytype ' ) [ 0 : 5 ] == ' SOCKS ' :
time . sleep ( 10 )
2012-11-19 20:45:05 +01:00
a , ( HOST , PORT ) = sock . accept ( )
2013-01-22 06:21:32 +01:00
#Users are finding that if they run more than one node in the same network (thus with the same public IP), they can not connect with the second node. This is because this section of code won't accept the connection from the same IP. This problem will go away when the Bitmessage network grows beyond being tiny but in the mean time I'll comment out this code section.
2012-12-27 17:26:52 +01:00
""" while HOST in connectedHostsList:
2012-11-19 20:45:05 +01:00
print ' incoming connection is from a host in connectedHostsList (we are already connected to it). Ignoring it. '
a . close ( )
2012-12-27 17:26:52 +01:00
a , ( HOST , PORT ) = sock . accept ( ) """
2012-12-18 19:09:10 +01:00
rd = receiveDataThread ( )
2012-11-19 20:45:05 +01:00
self . emit ( SIGNAL ( " passObjectThrough(PyQt_PyObject) " ) , rd )
2013-02-03 06:16:50 +01:00
objectsOfWhichThisRemoteNodeIsAlreadyAware = { }
rd . setup ( a , HOST , PORT , - 1 , self . incomingConnectionList , objectsOfWhichThisRemoteNodeIsAlreadyAware )
2012-12-27 17:26:52 +01:00
printLock . acquire ( )
2012-11-19 20:45:05 +01:00
print self , ' connected to ' , HOST , ' during INCOMING request. '
2012-12-27 17:26:52 +01:00
printLock . release ( )
2012-11-19 20:45:05 +01:00
rd . start ( )
sd = sendDataThread ( )
2013-02-03 06:16:50 +01:00
sd . setup ( a , HOST , PORT , - 1 , objectsOfWhichThisRemoteNodeIsAlreadyAware )
2012-11-19 20:45:05 +01:00
sd . start ( )
#This thread is created either by the synSenderThread(for outgoing connections) or the singleListenerThread(for incoming connectiosn).
class receiveDataThread ( QThread ) :
def __init__ ( self , parent = None ) :
QThread . __init__ ( self , parent )
self . data = ' '
self . verackSent = False
self . verackReceived = False
2013-02-03 06:16:50 +01:00
def setup ( self , sock , HOST , port , streamNumber , selfInitiatedConnectionList , objectsOfWhichThisRemoteNodeIsAlreadyAware ) :
2012-11-19 20:45:05 +01:00
self . sock = sock
self . HOST = HOST
self . PORT = port
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.
self . streamNumber = streamNumber
self . selfInitiatedConnectionList = selfInitiatedConnectionList
self . selfInitiatedConnectionList . append ( self )
2013-01-22 06:21:32 +01:00
self . payloadLength = 0 #This is the protocol payload length thus it doesn't include the 24 byte message header
self . receivedgetbiginv = False #Gets set to true once we receive a getbiginv message from our peer. An abusive peer might request it too much so we use this variable to check whether they have already asked for a big inv message.
2013-02-04 22:49:02 +01:00
self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = { }
2013-01-22 06:21:32 +01:00
connectedHostsList [ 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 the outgoingSynSender thread doesn't try to connect to it.
2012-11-19 20:45:05 +01: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
2012-12-19 17:51:51 +01: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-02-03 06:16:50 +01:00
self . objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware
2012-11-19 20:45:05 +01:00
def run ( self ) :
while True :
try :
self . data = self . data + self . sock . recv ( 65536 )
except socket . timeout :
printLock . acquire ( )
2013-01-22 06:21:32 +01:00
print ' Timeout occurred waiting for data. Closing receiveData thread. '
2012-11-19 20:45:05 +01:00
printLock . release ( )
break
except Exception , err :
printLock . acquire ( )
2012-12-27 18:26:06 +01:00
print ' sock.recv error. Closing receiveData thread. ' , err
2012-11-19 20:45:05 +01:00
printLock . release ( )
break
#print 'Received', repr(self.data)
if self . data == " " :
printLock . acquire ( )
2013-01-22 06:21:32 +01:00
print ' Connection closed. Closing receiveData thread. '
2012-11-19 20:45:05 +01:00
printLock . release ( )
break
else :
self . processData ( )
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
try :
self . sock . close ( )
except Exception , err :
print ' Within receiveDataThread run(), self.sock.close() failed. ' , err
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
try :
self . selfInitiatedConnectionList . remove ( self )
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
print ' removed self (a receiveDataThread) from ConnectionList '
printLock . release ( )
2012-11-19 20:45:05 +01:00
except :
pass
2013-01-22 06:21:32 +01:00
broadcastToSendDataQueues ( ( 0 , ' shutdown ' , self . HOST ) )
2012-11-19 20:45:05 +01:00
if self . connectionIsOrWasFullyEstablished : #We don't want to decrement the number of connections and show the result if we never incremented it in the first place (which we only do if the connection is fully established- meaning that both nodes accepted each other's version packets.)
connectionsCountLock . acquire ( )
connectionsCount [ self . streamNumber ] - = 1
self . emit ( SIGNAL ( " updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject) " ) , self . streamNumber , connectionsCount [ self . streamNumber ] )
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
print ' Updating network status tab with current connections count: ' , connectionsCount [ self . streamNumber ]
printLock . release ( )
2012-11-19 20:45:05 +01:00
connectionsCountLock . release ( )
2012-12-18 19:09:10 +01:00
try :
del connectedHostsList [ self . HOST ]
except Exception , err :
print ' Could not delete ' , self . HOST , ' from connectedHostsList. ' , err
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
def processData ( self ) :
global verbose
2012-12-05 18:47:30 +01:00
#if verbose >= 2:
#printLock.acquire()
#print 'self.data is currently ', repr(self.data)
#printLock.release()
2013-02-12 21:00:04 +01:00
if len ( self . data ) < 20 : #if so little of the data has arrived that we can't even unpack the payload length
2012-11-19 20:45:05 +01:00
pass
elif self . data [ 0 : 4 ] != ' \xe9 \xbe \xb4 \xd9 ' :
if verbose > = 2 :
2012-12-05 18:47:30 +01:00
printLock . acquire ( )
2013-02-04 23:13:10 +01:00
sys . stderr . write ( ' The magic bytes were not correct. First 40 bytes of data: %s \n ' % repr ( self . data [ 0 : 40 ] ) )
2012-12-05 18:47:30 +01:00
printLock . release ( )
2013-02-12 21:00:04 +01:00
self . data = " "
2012-12-05 18:47:30 +01:00
else :
self . payloadLength , = unpack ( ' >L ' , self . data [ 16 : 20 ] )
2013-02-18 21:01:47 +01:00
if len ( self . data ) > = self . payloadLength + 24 : #check if the whole message has arrived yet. If it has,...
2012-12-05 18:47:30 +01:00
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 'message checksum is correct'
#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 : #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).
knownNodes [ self . streamNumber ] [ self . HOST ] = ( self . PORT , int ( time . time ( ) ) )
2013-02-06 22:17:49 +01:00
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 ]
2012-12-05 18:47:30 +01:00
printLock . acquire ( )
print ' remoteCommand ' , remoteCommand , ' from ' , self . HOST
printLock . release ( )
2013-02-06 22:17:49 +01:00
if remoteCommand == ' version \x00 \x00 \x00 \x00 \x00 ' :
self . recversion ( )
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 ( )
elif remoteCommand == ' getpubkey \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recgetpubkey ( )
elif remoteCommand == ' pubkey \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recpubkey ( )
elif remoteCommand == ' inv \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recinv ( )
elif remoteCommand == ' getdata \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recgetdata ( )
elif remoteCommand == ' getbiginv \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . sendBigInv ( )
elif remoteCommand == ' msg \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recmsg ( )
elif remoteCommand == ' broadcast \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . recbroadcast ( )
elif remoteCommand == ' getaddr \x00 \x00 \x00 \x00 \x00 ' and self . connectionIsOrWasFullyEstablished :
self . sendaddr ( )
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
2012-12-05 18:47:30 +01:00
self . data = self . data [ self . payloadLength + 24 : ] #take this message out and then process the next message
if self . data == ' ' :
2013-02-04 22:49:02 +01:00
while len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) > 0 :
2012-12-05 18:47:30 +01:00
random . seed ( )
2013-02-04 22:49:02 +01:00
objectHash , = random . sample ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave , 1 )
2012-12-05 18:47:30 +01:00
if objectHash in inventory :
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
2012-12-19 16:38:45 +01:00
print ' Inventory (in memory) already has object listed in inv message. '
2013-01-22 06:21:32 +01:00
printLock . release ( )
2013-02-04 22:49:02 +01:00
del self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave [ objectHash ]
2012-12-05 18:47:30 +01:00
elif isInSqlInventory ( objectHash ) :
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
2012-12-19 16:38:45 +01:00
print ' Inventory (SQL on disk) already has object listed in inv message. '
2013-01-22 06:21:32 +01:00
printLock . release ( )
2013-02-04 22:49:02 +01:00
del self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave [ objectHash ]
2012-12-05 18:47:30 +01:00
else :
2013-01-22 06:21:32 +01:00
#print 'processData function making request for object:', objectHash.encode('hex')
2012-12-05 18:47:30 +01:00
self . sendgetdata ( objectHash )
2013-02-04 22:49:02 +01:00
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.
2012-12-05 18:47:30 +01:00
break
2013-02-04 22:49:02 +01:00
if len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave ) > 0 :
2012-12-19 17:51:51 +01:00
printLock . acquire ( )
2013-02-04 22:49:02 +01:00
print ' within processData, number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now ' , len ( self . objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave )
2012-12-19 17:51:51 +01:00
printLock . release ( )
if len ( self . ackDataThatWeHaveYetToSend ) > 0 :
self . data = self . ackDataThatWeHaveYetToSend . pop ( )
2012-12-05 18:47:30 +01:00
self . processData ( )
else :
print ' Checksum incorrect. Clearing this message. '
self . data = self . data [ self . payloadLength + 24 : ]
2012-11-19 20:45:05 +01:00
2012-11-23 09:22:56 +01:00
def isProofOfWorkSufficient ( self ) :
POW , = unpack ( ' >Q ' , hashlib . sha512 ( hashlib . sha512 ( self . data [ 24 : 32 ] + hashlib . sha512 ( self . data [ 32 : 24 + self . payloadLength ] ) . digest ( ) ) . digest ( ) ) . digest ( ) [ 0 : 8 ] )
2012-12-05 18:47:30 +01:00
#print 'POW:', POW
2012-11-23 09:22:56 +01:00
#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.
return POW < 2 * * 64 / ( ( self . payloadLength + payloadLengthExtraBytes ) * ( averageProofOfWorkNonceTrialsPerByte / 2 ) )
2012-11-19 20:45:05 +01:00
def sendpong ( self ) :
print ' Sending pong '
2012-11-23 09:22:56 +01:00
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 ' )
2012-11-19 20:45:05 +01:00
def recverack ( self ) :
print ' verack received '
self . verackReceived = True
if self . verackSent == True :
#We have thus both sent and received a verack.
self . connectionFullyEstablished ( )
def connectionFullyEstablished ( self ) :
self . connectionIsOrWasFullyEstablished = True
if not self . initiatedConnection :
self . emit ( SIGNAL ( " setStatusIcon(PyQt_PyObject) " ) , ' green ' )
#Update the 'Network Status' tab
connectionsCountLock . acquire ( )
connectionsCount [ self . streamNumber ] + = 1
self . emit ( SIGNAL ( " updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject) " ) , self . streamNumber , connectionsCount [ self . streamNumber ] )
connectionsCountLock . release ( )
remoteNodeIncomingPort , remoteNodeSeenTime = knownNodes [ self . streamNumber ] [ self . HOST ]
2012-11-23 09:22:56 +01:00
printLock . acquire ( )
print ' Connection fully established with ' , self . HOST , remoteNodeIncomingPort
2012-11-19 20:45:05 +01:00
print ' broadcasting addr from within connectionFullyEstablished function. '
2012-11-23 09:22:56 +01:00
printLock . release ( )
self . broadcastaddr ( [ ( int ( time . time ( ) ) , self . streamNumber , 1 , self . HOST , remoteNodeIncomingPort ) ] ) #This lets all of our peers know about this new node.
2013-01-22 06:21:32 +01:00
self . sendaddr ( ) #This is one large addr message to this one peer.
2012-11-19 20:45:05 +01:00
if connectionsCount [ self . streamNumber ] > 150 :
2013-01-22 06:21:32 +01:00
printLock . acquire ( )
2012-11-19 20:45:05 +01:00
print ' We are connected to too many people. Closing connection. '
2013-01-22 06:21:32 +01:00
printLock . release ( )
2012-11-19 20:45:05 +01:00
self . sock . close ( )
return
self . sendBigInv ( )
def sendBigInv ( self ) : #I used capitals in for this function name because there is no such Bitmessage command as 'biginv'.
if self . receivedgetbiginv :
print ' We have already sent a big inv message to this peer. Ignoring request. '
return
else :
self . receivedgetbiginv = True
sqlLock . acquire ( )
#Select all hashes which are younger than two days old and in this stream.
2013-01-04 23:21:33 +01:00
t = ( int ( time . time ( ) ) - maximumAgeOfObjectsThatIAdvertiseToOthers , self . streamNumber )
2012-11-19 20:45:05 +01:00
sqlSubmitQueue . put ( ''' SELECT hash FROM inventory WHERE receivedtime>? and streamnumber=? ''' )
sqlSubmitQueue . put ( t )
queryreturn = sqlReturnQueue . get ( )
2013-02-18 21:22:48 +01:00
sqlLock . release ( )
2012-11-19 20:45:05 +01:00
bigInvList = { }
for row in queryreturn :
hash , = row
2013-02-03 06:16:50 +01:00
if hash not in self . objectsOfWhichThisRemoteNodeIsAlreadyAware :
bigInvList [ hash ] = 0
else :
printLock . acquire ( )
print ' Not including an object hash in a big inv message because the remote node is already aware of it. ' #This line is here to check that this feature is working.
printLock . release ( )
2013-01-22 06:21:32 +01:00
#We also have messages in our inventory in memory (which is a python dictionary). Let's fetch those too.
2012-11-19 20:45:05 +01:00
for hash , storedValue in inventory . items ( ) :
2013-02-03 06:16:50 +01:00
if hash not in self . objectsOfWhichThisRemoteNodeIsAlreadyAware :
objectType , streamNumber , payload , receivedTime = storedValue
if streamNumber == self . streamNumber and receivedTime > int ( time . time ( ) ) - maximumAgeOfObjectsThatIAdvertiseToOthers :
bigInvList [ hash ] = 0
else :
printLock . acquire ( )
print ' Not including an object hash in a big inv message because the remote node is already aware of it. ' #This line is here to check that this feature is working.
printLock . release ( )
2012-11-19 20:45:05 +01:00
numberOfObjectsInInvMessage = 0
payload = ' '
2013-01-22 06:21:32 +01:00
#Now let us start appending all of these hashes together. They will be sent out in a big inv message to our new peer.
2012-11-19 20:45:05 +01:00
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.
2013-01-22 06:21:32 +01:00
self . sendinvMessageToJustThisOnePeer ( numberOfObjectsInInvMessage , payload )
2012-11-19 20:45:05 +01:00
payload = ' '
numberOfObjectsInInvMessage = 0
if numberOfObjectsInInvMessage > 0 :
2012-11-23 09:22:56 +01:00
self . sendinvMessageToJustThisOnePeer ( numberOfObjectsInInvMessage , payload )
2013-02-18 21:22:48 +01:00
2012-11-23 09:22:56 +01:00
#Self explanatory. Notice that there is also a broadcastinv function for broadcasting invs to everyone in our stream.
def sendinvMessageToJustThisOnePeer ( self , numberOfObjects , payload ) :
2012-11-19 20:45:05 +01:00
payload = encodeVarint ( numberOfObjects ) + payload
headerData = ' \xe9 \xbe \xb4 \xd9 ' #magic bits, slighly different from Bitcoin's magic bits.
2013-02-04 22:49:02 +01:00
headerData + = ' inv \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 '
headerData + = pack ( ' >L ' , len ( payload ) )
headerData + = hashlib . sha512 ( payload ) . digest ( ) [ : 4 ]
2013-02-03 06:16:50 +01:00
print ' Sending huge inv message with ' , numberOfObjects , ' objects to just this one peer '
2012-11-19 20:45:05 +01:00
self . sock . send ( headerData + payload )
#We have received a broadcast message
def recbroadcast ( self ) :
2013-02-06 22:17:49 +01:00
self . messageProcessingStartTime = time . time ( )
2012-11-19 20:45:05 +01:00
#First we must check to make sure the proof of work is sufficient.
2012-11-23 09:22:56 +01:00
if not self . isProofOfWorkSufficient ( ) :
print ' Proof of work in broadcast message insufficient. '
2012-11-19 20:45:05 +01:00
return
embeddedTime , = unpack ( ' >I ' , self . data [ 32 : 36 ] )
if embeddedTime > ( int ( time . time ( ) ) + 10800 ) : #prevent funny business
print ' The embedded time in this broadcast message is more than three hours in the future. That doesn \' t make sense. Ignoring message. '
return
if embeddedTime < ( int ( time . time ( ) ) - maximumAgeOfAnObjectThatIAmWillingToAccept ) :
print ' The embedded time in this broadcast message is too old. Ignoring message. '
return
2013-02-12 21:00:04 +01:00
if self . payloadLength < 66 : #todo: When version 1 addresses are completely abandoned, this should be changed to 180
2012-11-19 20:45:05 +01:00
print ' The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message. '
return
2012-12-18 22:36:37 +01:00
inventoryLock . acquire ( )
2013-02-06 22:17:49 +01:00
self . inventoryHash = calculateInventoryHash ( self . data [ 24 : self . payloadLength + 24 ] )
if self . inventoryHash in inventory :
2012-11-19 20:45:05 +01:00
print ' We have already received this broadcast object. Ignoring. '
2012-12-18 22:36:37 +01:00
inventoryLock . release ( )
2012-11-19 20:45:05 +01:00
return
2013-02-06 22:17:49 +01:00
elif isInSqlInventory ( self . inventoryHash ) :
2012-11-19 20:45:05 +01:00
print ' We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it. '
2012-12-18 22:36:37 +01:00
inventoryLock . release ( )
2012-11-19 20:45:05 +01:00
return
#It is valid so far. Let's let our peers know about it.
objectType = ' broadcast '
2013-02-06 22:17:49 +01:00
inventory [ self . inventoryHash ] = ( objectType , self . streamNumber , self . data [ 24 : self . payloadLength + 24 ] , embeddedTime )
2012-12-18 22:36:37 +01:00
inventoryLock . release ( )
2013-02-06 22:17:49 +01:00
self . broadcastinv ( self . inventoryHash )
2012-11-19 20:45:05 +01:00
self . emit ( SIGNAL ( " incrementNumberOfBroadcastsProcessed() " ) )
2013-02-18 21:22:48 +01:00
2013-02-06 22:17:49 +01:00
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.
2013-02-18 21:22:48 +01:00
# 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.
2013-02-06 22:17:49 +01:00
if self . payloadLength > 100000000 : #Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 #seconds.
elif self . payloadLength > 10000000 : #Between 100 and 10 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 20 #seconds.
elif self . payloadLength > 1000000 : #Between 10 and 1 megabyte
2013-02-18 21:22:48 +01:00
lengthOfTimeWeShouldUseToProcessThisMessage = 3 #seconds.
2013-02-06 22:17:49 +01:00
else : #Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = .1 #seconds.
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - ( time . time ( ) - self . messageProcessingStartTime )
if sleepTime > 0 :
printLock . acquire ( )
print ' Timing attack mitigation: Sleeping for ' , sleepTime , ' seconds. '
printLock . release ( )
time . sleep ( sleepTime )
printLock . acquire ( )
print ' Total message processing time: ' , time . time ( ) - self . messageProcessingStartTime , ' seconds. '
printLock . release ( )
#A broadcast message has a valid time and POW and requires processing. The recbroadcast function calls this one.
def processbroadcast ( self ) :
2012-11-19 20:45:05 +01:00
readPosition = 36
broadcastVersion , broadcastVersionLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if broadcastVersion < > 1 :
#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
sendersAddressVersion , sendersAddressVersionLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
2013-01-24 20:52:48 +01:00
if sendersAddressVersion == 0 or sendersAddressVersion > = 3 :
#Cannot decode senderAddressVersion higher than 2. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.
2012-11-19 20:45:05 +01:00
return
readPosition + = sendersAddressVersionLength
2013-01-24 20:52:48 +01:00
if sendersAddressVersion == 2 :
sendersStream , sendersStreamLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if sendersStream < = 0 or sendersStream < > self . streamNumber :
return
readPosition + = sendersStreamLength
behaviorBitfield = self . data [ readPosition : readPosition + 4 ]
readPosition + = 4
sendersPubSigningKey = ' \x04 ' + self . data [ readPosition : readPosition + 64 ]
readPosition + = 64
sendersPubEncryptionKey = ' \x04 ' + self . data [ readPosition : readPosition + 64 ]
readPosition + = 64
sendersHash = self . data [ readPosition : readPosition + 20 ]
if sendersHash not in broadcastSendersForWhichImWatching :
2013-02-06 22:17:49 +01:00
#Display timing data
2013-02-05 22:53:56 +01:00
printLock . acquire ( )
2013-02-06 22:17:49 +01:00
print ' Time spent deciding that we are not interested in this broadcast: ' , time . time ( ) - self . messageProcessingStartTime
2013-02-05 22:53:56 +01:00
printLock . release ( )
2013-01-24 20:52:48 +01: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
2013-02-06 22:17:49 +01:00
2013-01-24 20:52:48 +01:00
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.
2013-02-06 22:17:49 +01:00
return
2013-01-24 20:52:48 +01:00
messageEncodingType , messageEncodingTypeLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if messageEncodingType == 0 :
return
readPosition + = messageEncodingTypeLength
messageLength , messageLengthLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
readPosition + = messageLengthLength
message = self . data [ readPosition : readPosition + messageLength ]
readPosition + = messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength , signatureLengthLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
readPosition + = signatureLengthLength
signature = self . data [ readPosition : readPosition + signatureLength ]
try :
highlevelcrypto . verify ( self . data [ 36 : readPositionAtBottomOfMessage ] , signature , sendersPubSigningKey . encode ( ' hex ' ) )
print ' ECDSA verify passed '
except Exception , err :
print ' ECDSA verify failed ' , err
return
#verify passed
fromAddress = encodeAddress ( sendersAddressVersion , sendersStream , ripe . digest ( ) )
print ' fromAddress: ' , fromAddress
if messageEncodingType == 2 :
bodyPositionIndex = string . find ( message , ' \n Body: ' )
if bodyPositionIndex > 1 :
subject = message [ 8 : bodyPositionIndex ]
body = message [ bodyPositionIndex + 6 : ]
else :
subject = ' '
body = message
elif messageEncodingType == 1 :
body = message
subject = ' '
elif messageEncodingType == 0 :
print ' messageEncodingType == 0. Doing nothing with the message. '
2012-12-04 18:11:14 +01:00
else :
2013-01-24 20:52:48 +01:00
body = ' Unknown encoding type. \n \n ' + repr ( message )
2012-12-04 18:11:14 +01:00
subject = ' '
2013-01-24 20:52:48 +01:00
toAddress = ' [Broadcast subscribers] '
if messageEncodingType < > 0 :
sqlLock . acquire ( )
2013-02-06 22:17:49 +01:00
t = ( self . inventoryHash , toAddress , fromAddress , subject , int ( time . time ( ) ) , body , ' inbox ' )
2013-01-24 20:52:48 +01:00
sqlSubmitQueue . put ( ''' INSERT INTO inbox VALUES (?,?,?,?,?,?,?) ''' )
sqlSubmitQueue . put ( t )
sqlReturnQueue . get ( )
sqlLock . release ( )
2013-02-26 00:09:32 +01:00
self . emit ( SIGNAL ( " displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject) " ) , self . inventoryHash , toAddress , fromAddress , subject , body )
2013-01-24 20:52:48 +01:00
2013-02-05 22:53:56 +01:00
#Display timing data
printLock . acquire ( )
2013-02-06 22:17:49 +01:00
print ' Time spent processing this interesting broadcast: ' , time . time ( ) - self . messageProcessingStartTime
2013-02-05 22:53:56 +01:00
printLock . release ( )
2013-01-24 20:52:48 +01:00
elif sendersAddressVersion == 1 :
sendersStream , sendersStreamLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if sendersStream < = 0 :
return
readPosition + = sendersStreamLength
sendersHash = self . data [ readPosition : readPosition + 20 ]
if sendersHash not in broadcastSendersForWhichImWatching :
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
nLength , nLengthLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if nLength < 1 :
return
readPosition + = nLengthLength
nString = self . data [ readPosition : readPosition + nLength ]
readPosition + = nLength
eLength , eLengthLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if eLength < 1 :
return
readPosition + = eLengthLength
eString = self . data [ readPosition : readPosition + eLength ]
#We are now ready to hash the public key and verify that its hash matches the hash claimed in the message
readPosition + = eLength
sha = hashlib . new ( ' sha512 ' )
sha . update ( nString + eString )
ripe = hashlib . new ( ' ripemd160 ' )
ripe . update ( sha . digest ( ) )
if ripe . digest ( ) != sendersHash :
#The sender of this message lied.
return
readPositionAtBeginningOfMessageEncodingType = readPosition
messageEncodingType , messageEncodingTypeLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if messageEncodingType == 0 :
return
readPosition + = messageEncodingTypeLength
messageLength , messageLengthLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
readPosition + = messageLengthLength
message = self . data [ readPosition : readPosition + messageLength ]
readPosition + = messageLength
signature = self . data [ readPosition : readPosition + nLength ]
sendersPubkey = rsa . PublicKey ( convertStringToInt ( nString ) , convertStringToInt ( eString ) )
#print 'senders Pubkey', sendersPubkey
try :
rsa . verify ( self . data [ readPositionAtBeginningOfMessageEncodingType : readPositionAtBeginningOfMessageEncodingType + messageEncodingTypeLength + messageLengthLength + messageLength ] , signature , sendersPubkey )
print ' verify passed '
except Exception , err :
print ' verify failed ' , err
return
#verify passed
fromAddress = encodeAddress ( sendersAddressVersion , sendersStream , ripe . digest ( ) )
print ' fromAddress: ' , fromAddress
if messageEncodingType == 2 :
bodyPositionIndex = string . find ( message , ' \n Body: ' )
if bodyPositionIndex > 1 :
subject = message [ 8 : bodyPositionIndex ]
body = message [ bodyPositionIndex + 6 : ]
else :
subject = ' '
body = message
elif messageEncodingType == 1 :
2012-12-04 18:11:14 +01:00
body = message
2013-01-24 20:52:48 +01:00
subject = ' '
elif messageEncodingType == 0 :
print ' messageEncodingType == 0. Doing nothing with the message. '
else :
body = ' Unknown encoding type. \n \n ' + repr ( message )
subject = ' '
2012-11-19 20:45:05 +01:00
2013-01-24 20:52:48 +01:00
toAddress = ' [Broadcast subscribers] '
if messageEncodingType < > 0 :
sqlLock . acquire ( )
2013-02-06 22:17:49 +01:00
t = ( self . inventoryHash , toAddress , fromAddress , subject , int ( time . time ( ) ) , body , ' inbox ' )
2013-01-24 20:52:48 +01:00
sqlSubmitQueue . put ( ''' INSERT INTO inbox VALUES (?,?,?,?,?,?,?) ''' )
sqlSubmitQueue . put ( t )
sqlReturnQueue . get ( )
sqlLock . release ( )
2013-02-26 00:09:32 +01:00
self . emit ( SIGNAL ( " displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject) " ) , self . inventoryHash , toAddress , fromAddress , subject , body )
2013-02-06 22:17:49 +01:00
2012-11-19 20:45:05 +01:00
#We have received a msg message.
def recmsg ( self ) :
2013-02-06 22:17:49 +01:00
self . messageProcessingStartTime = time . time ( )
2012-11-19 20:45:05 +01:00
#First we must check to make sure the proof of work is sufficient.
2012-11-23 09:22:56 +01:00
if not self . isProofOfWorkSufficient ( ) :
2012-11-19 20:45:05 +01:00
print ' Proof of work in msg message insufficient. '
return
2013-02-18 21:22:48 +01:00
2012-11-19 20:45:05 +01:00
readPosition = 32
embeddedTime , = unpack ( ' >I ' , self . data [ readPosition : readPosition + 4 ] )
if embeddedTime > int ( time . time ( ) ) + 10800 :
print ' The time in the msg message is too new. Ignoring it. Time: ' , embeddedTime
return
if embeddedTime < int ( time . time ( ) ) - maximumAgeOfAnObjectThatIAmWillingToAccept :
print ' The time in the msg message is too old. Ignoring it. Time: ' , embeddedTime
return
readPosition + = 4
2012-12-18 22:36:37 +01:00
streamNumberAsClaimedByMsg , streamNumberAsClaimedByMsgLength = decodeVarint ( self . data [ readPosition : readPosition + 9 ] )
if streamNumberAsClaimedByMsg != self . streamNumber :
2013-02-04 22:49:02 +01:00
print ' The stream number encoded in this msg ( ' + str ( streamNumberAsClaimedByMsg ) + ' ) message does not match the stream number on which it was received. Ignoring it. '
2012-12-18 22:36:37 +01:00
return
readPosition + = streamNumberAsClaimedByMsgLength
2013-02-06 22:17:49 +01:00
self . inventoryHash = calculateInventoryHash ( self . data [ 24 : self . payloadLength + 24 ] )
2012-12-18 22:36:37 +01:00
inventoryLock . acquire ( )
2013-02-06 22:17:49 +01:00
if self . inventoryHash in inventory :
2012-11-19 20:45:05 +01:00
print ' We have already received this msg message. Ignoring. '
2012-12-18 22:36:37 +01:00
inventoryLock . release ( )
2012-11-19 20:45:05 +01:00
return
2013-02-06 22:17:49 +01:00
elif isInSqlInventory ( self . inventoryHash ) :
2012-11-19 20:45:05 +01:00
print ' We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it. '
2012-12-18 22:36:37 +01:00
inventoryLock . release ( )
2012-11-19 20:45:05 +01:00
return