PyBitmessage-2021-04-27/bitmessagemain.py

4320 lines
256 KiB
Python
Raw Normal View History

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-01-18 23:38:09 +01:00
softwareVersion = '0.2.0'
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.
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-18 23:38:09 +01:00
userVeryEasyProofOfWorkForTesting = True #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:
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 *
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-01-18 23:38:09 +01:00
#time.sleep(999999)#I'm using 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)
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)
rd.setup(sock,HOST,PORT,self.streamNumber,self.selfInitiatedConnectionList)
rd.start()
printLock.acquire()
2012-11-19 20:45:05 +01:00
print self, 'connected to', HOST, 'during outgoing attempt.'
printLock.release()
2012-11-19 20:45:05 +01:00
sd = sendDataThread()
sd.setup(sock,HOST,PORT,self.streamNumber)
sd.start()
sd.sendVersionMessage()
2012-12-18 19:09:10 +01:00
except socks.GeneralProxyError, err:
2012-11-19 20:45:05 +01:00
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
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':
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:
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
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:
print 'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types:', err
2012-11-19 20:45:05 +01:00
time.sleep(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)
class singleListener(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
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
print 'bitmessage listener running'
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:
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(10)
2012-11-19 20:45:05 +01:00
a,(HOST,PORT) = sock.accept()
#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 behond being tiny but in the mean time, I'll comment out this code section.
"""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()
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)
rd.setup(a,HOST,PORT,-1,self.incomingConnectionList)
printLock.acquire()
2012-11-19 20:45:05 +01:00
print self, 'connected to', HOST,'during INCOMING request.'
printLock.release()
2012-11-19 20:45:05 +01:00
rd.start()
sd = sendDataThread()
sd.setup(a,HOST,PORT,-1)
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
def setup(self,sock,HOST,port,streamNumber,selfInitiatedConnectionList):
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)
self.payloadLength = 0
self.receivedgetbiginv = False
self.objectsThatWeHaveYetToGet = {}
connectedHostsList[self.HOST] = 0
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
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.
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()
print 'Timeout occurred waiting for data. Closing thread.'
printLock.release()
break
except Exception, err:
printLock.acquire()
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()
print 'Connection closed.'
2012-11-19 20:45:05 +01:00
printLock.release()
break
else:
self.processData()
try:
self.sock.close()
except Exception, err:
print 'Within receiveDataThread run(), self.sock.close() failed.', err
try:
self.selfInitiatedConnectionList.remove(self)
print 'removed self from ConnectionList'
except:
pass
broadcastToSendDataQueues((self.streamNumber, 'shutdown', self.HOST))
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])
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
2012-11-19 20:45:05 +01:00
def processData(self):
global verbose
#if verbose >= 2:
#printLock.acquire()
#print 'self.data is currently ', repr(self.data)
#printLock.release()
2012-11-19 20:45:05 +01:00
if self.data == "":
pass
elif self.data[0:4] != '\xe9\xbe\xb4\xd9':
self.data = ""
if verbose >= 2:
printLock.acquire()
sys.stderr.write('The magic bytes were not correct.\n')
printLock.release()
elif len(self.data) < 20: #if so little of the data has arrived that we can't even unpack the payload length
pass
else:
self.payloadLength, = unpack('>L',self.data[16:20])
if len(self.data) >= self.payloadLength: #check if the whole message has arrived yet. If it has,...
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()))
remoteCommand = self.data[4:16]
if verbose >= 2:
printLock.acquire()
print 'remoteCommand ', remoteCommand, 'from', self.HOST
printLock.release()
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
self.data = self.data[self.payloadLength+24:]#take this message out and then process the next message
if self.data == '':
while len(self.objectsThatWeHaveYetToGet) > 0:
random.seed()
objectHash, = random.sample(self.objectsThatWeHaveYetToGet, 1)
if objectHash in inventory:
print 'Inventory (in memory) already has object listed in inv message.'
del self.objectsThatWeHaveYetToGet[objectHash]
elif isInSqlInventory(objectHash):
print 'Inventory (SQL on disk) already has object listed in inv message.'
del self.objectsThatWeHaveYetToGet[objectHash]
else:
2013-01-18 23:38:09 +01:00
print 'processData function making request for object:', objectHash.encode('hex')
self.sendgetdata(objectHash)
del self.objectsThatWeHaveYetToGet[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.
break
if len(self.objectsThatWeHaveYetToGet) > 0:
printLock.acquire()
print 'within processData, number of objectsThatWeHaveYetToGet is now', len(self.objectsThatWeHaveYetToGet)
printLock.release()
if len(self.ackDataThatWeHaveYetToSend) > 0:
self.data = self.ackDataThatWeHaveYetToSend.pop()
self.processData()
else:
print 'Checksum incorrect. Clearing this message.'
self.data = self.data[self.payloadLength+24:]
2012-11-19 20:45:05 +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])
#print 'POW:', POW
#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'
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]
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.'
printLock.release()
self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.HOST, remoteNodeIncomingPort)]) #This lets all of our peers know about this new node.
self.sendaddr() #This is one addr message to this one peer.
2012-11-19 20:45:05 +01:00
if connectionsCount[self.streamNumber] > 150:
print 'We are connected to too many people. Closing connection.'
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()
sqlLock.release()
print 'sendBigInv pulled', len(queryreturn), 'items from SQL inventory.'
bigInvList = {}
for row in queryreturn:
hash, = row
bigInvList[hash] = 0
#print 'bigInvList:', bigInvList
for hash, storedValue in inventory.items():
objectType, streamNumber, payload, receivedTime = storedValue
2013-01-04 23:21:33 +01:00
if streamNumber == self.streamNumber and receivedTime > int(time.time())-maximumAgeOfObjectsThatIAdvertiseToOthers:
2012-11-19 20:45:05 +01:00
bigInvList[hash] = 0
numberOfObjectsInInvMessage = 0
payload = ''
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.
sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload)
2012-11-19 20:45:05 +01:00
payload = ''
numberOfObjectsInInvMessage = 0
if numberOfObjectsInInvMessage > 0:
self.sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload)
2012-11-19 20:45:05 +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.
headerData = headerData + 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00'
headerData = headerData + pack('>L',len(payload))
2012-11-23 01:06:42 +01:00
headerData = headerData + hashlib.sha512(payload).digest()[:4]
print 'Sending inv message 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):
#First we must check to make sure the proof of work is sufficient.
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
if self.payloadLength < 66:
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
return
inventoryLock.acquire()
2012-11-19 20:45:05 +01:00
inventoryHash = calculateInventoryHash(self.data[24:self.payloadLength+24])
if inventoryHash in inventory:
print 'We have already received this broadcast object. Ignoring.'
inventoryLock.release()
2012-11-19 20:45:05 +01:00
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
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'
inventory[inventoryHash] = (objectType, self.streamNumber, self.data[24:self.payloadLength+24], embeddedTime)
inventoryLock.release()
2012-11-19 20:45:05 +01:00
self.broadcastinv(inventoryHash)
self.emit(SIGNAL("incrementNumberOfBroadcastsProcessed()"))
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])
if sendersAddressVersion <> 1:
#Cannot decode senderAddressVersion higher than 1. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.
return
readPosition += sendersAddressVersionLength
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:
#You may notice that this signature doesn't cover any information that identifies the RECEIVER of the message. This makes it vulnerable to a malicious receiver Bob forwarding the message from Alice to Charlie, making it look like Alice sent the message to Charlie. This will be fixed in the next version.
#See http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
2012-11-19 20:45:05 +01:00
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:
2012-12-04 18:11:14 +01:00
bodyPositionIndex = string.find(message,'\nBody:')
if bodyPositionIndex > 1:
subject = message[8:bodyPositionIndex]
body = message[bodyPositionIndex+6:]
else:
subject = ''
body = message
2012-11-19 20:45:05 +01: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:
sqlLock.acquire()
t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox')
sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''')
2012-11-19 20:45:05 +01:00
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlLock.release()
self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body)
2012-11-19 20:45:05 +01:00
#We have received a msg message.
def recmsg(self):
#First we must check to make sure the proof of work is sufficient.
if not self.isProofOfWorkSufficient():
2012-11-19 20:45:05 +01:00
print 'Proof of work in msg message insufficient.'
return
initialDecryptionSuccessful = False
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
2013-01-18 23:38:09 +01:00
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(self.data[readPosition:readPosition+9])
if streamNumberAsClaimedByMsg != self.streamNumber:
print 'The stream number encoded in this msg (' + streamNumberAsClaimedByMsg + ') message does not match the stream number on which it was received. Ignoring it.'
return
readPosition += streamNumberAsClaimedByMsgLength
2013-01-18 23:38:09 +01:00
inventoryHash = calculateInventoryHash(self.data[24:self.payloadLength+24])
inventoryLock.acquire()
2012-11-19 20:45:05 +01:00
if inventoryHash in inventory:
print 'We have already received this msg message. Ignoring.'
inventoryLock.release()
2012-11-19 20:45:05 +01:00
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
2012-11-19 20:45:05 +01:00
return
#This msg message is valid. Let's let our peers know about it.
objectType = 'msg'
inventory[inventoryHash] = (objectType, self.streamNumber, self.data[24:self.payloadLength+24], embeddedTime)
inventoryLock.release()
2012-11-19 20:45:05 +01:00
self.broadcastinv(inventoryHash)
self.emit(SIGNAL("incrementNumberOfMessagesProcessed()"))
#Let's check whether this is a message acknowledgement bound for us.
if self.data[readPosition:24+self.payloadLength] in ackdataForWhichImWatching:
printLock.acquire()
print 'This msg IS an acknowledgement bound for me.'
2012-11-19 20:45:05 +01:00
printLock.release()
del ackdataForWhichImWatching[self.data[readPosition:24+self.payloadLength]]
t = ('ackreceived',self.data[readPosition:24+self.payloadLength])
sqlLock.acquire()
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.')
flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage soon.
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 'ackdataForWhichImWatching', ackdataForWhichImWatching
2012-11-19 20:45:05 +01:00
printLock.release()
#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.
2013-01-18 23:38:09 +01:00
for key, cryptorObject in myECAddressHashes.items():
try:
data = cryptorObject.decrypt(self.data[readPosition:self.payloadLength+24])
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
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
break
except Exception, err:
pass
#print 'cryptorObject.decrypt Exception:', err
if initialDecryptionSuccessful:
#This is a message bound for me.
flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage violently.
readPosition = 0
messageVersion, messageVersionLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += messageVersionLength
if messageVersion != 1:
print 'Cannot understand message versions other than one. Ignoring message.'
return
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += sendersAddressVersionNumberLength
if sendersAddressVersionNumber == 0:
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
return
if sendersAddressVersionNumber >= 3:
print 'Sender\'s address version number', sendersAddressVersionNumber, ' not yet supported. Ignoring message.'
return
if len(data) < 170:
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
return
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += sendersStreamNumberLength
behaviorBitfield = data[readPosition:readPosition+4]
print 'behaviorBitfield',behaviorBitfield.encode('hex')
readPosition += 4
pubSigningKey = '\x04' + data[readPosition:readPosition+64]
readPosition += 64
pubEncryptionKey = '\x04' + data[readPosition:readPosition+64]
readPosition += 64
endOfThePublicKeyPosition = readPosition #needed for when we store the pubkey in our database of pubkeys for later use.
if toRipe != data[readPosition:readPosition+20]:
printLock.acquire()
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
print 'See: http://tools.ietf.org/html/draft-ietf-smime-sender-auth-00'
print 'your toRipe:', toRipe.encode('hex')
print 'embedded destination toRipe:', data[readPosition:readPosition+20].encode('hex')
printLock.release()
return
readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += messageEncodingTypeLength
print 'Message Encoding Type:', messageEncodingType
messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+10])
print 'message length:', messageLength
readPosition += messageLengthLength
message = data[readPosition:readPosition+messageLength]
#print 'First 150 characters of message:', repr(message[:150])
readPosition += messageLength
ackLength, ackLengthLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += ackLengthLength
ackData = data[readPosition:readPosition+ackLength]
readPosition += ackLength
positionOfBottomOfAckData = readPosition #needed to mark the end of what is covered by the signature
signatureLength, signatureLengthLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += signatureLengthLength
signature = data[readPosition:readPosition+signatureLength]
try:
highlevelcrypto.verify(data[:positionOfBottomOfAckData],signature,pubSigningKey.encode('hex'))
print 'ECDSA verify passed'
except Exception, err:
print 'ECDSA verify failed', err
return
printLock.acquire()
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', calculateBitcoinAddressFromPubkey(pubSigningKey)
print 'And here is the testnet address:',calculateTestnetAddressFromPubkey(pubSigningKey),'. Be aware that the other person must take their private signing key from Bitmessage and import it into Bitcoin for it to be of any use. Do not use this unless you know what you are doing. Using testnet is recommended as no warranty is offered.'
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 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(),False,'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+data[messageVersionLength:endOfThePublicKeyPosition],int(time.time())+2419200) #after one month we may remove this pub key from our database. (2419200 = a month)
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlLock.release()
blockMessage = False #Gets set to True if the user shouldn't see the message according to black or white lists.
fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest())
if config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist
t = (fromAddress,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT label, enabled FROM blacklist where address=?''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
for row in queryreturn:
label, enabled = row
if enabled:
print 'Message ignored because address is in blacklist.'
blockMessage = True
else: #We're using a whitelist
t = (fromAddress,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT label, enabled FROM whitelist where address=?''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
if queryreturn == []:
print 'Message ignored because address not in whitelist.'
blockMessage = True
for row in queryreturn: #It could be in the whitelist but disabled. Let's check.
label, enabled = row
if not enabled:
print 'Message ignored because address in whitelist but not enabled.'
blockMessage = True
if not blockMessage:
print 'fromAddress:', fromAddress
print 'First 150 characters of message:', repr(message[:150])
#Look up the destination address (my address) based on the destination ripe hash.
#I realize that I could have a data structure devoted to this task, or maintain an indexed table
#in the sql database, but I would prefer to minimize the number of data structures this program
#uses. Searching linearly through the user's short list of addresses doesn't take very long anyway.
configSections = config.sections()
for addressInKeysFile in configSections:
if addressInKeysFile <> 'bitmessagesettings':
status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile)
if hash == key:
toAddress = addressInKeysFile
toLabel = config.get(addressInKeysFile, 'label')
if toLabel == '':
toLabel = addressInKeysFile
if messageEncodingType == 2:
bodyPositionIndex = string.find(message,'\nBody:')
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. They probably just sent it so that we would store their public key or send their ack data for them.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
print 'within recmsg, inventoryHash is', inventoryHash.encode('hex')
if messageEncodingType <> 0:
sqlLock.acquire()
t = (inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox')
sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlLock.release()
self.emit(SIGNAL("displayNewMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),inventoryHash,toAddress,fromAddress,subject,body)
#Now let's send the acknowledgement
#POW, = unpack('>Q',hashlib.sha512(hashlib.sha512(ackData[24:]).digest()).digest()[4:12])
#if POW <= 2**64 / ((len(ackData[24:])+payloadLengthExtraBytes) * averageProofOfWorkNonceTrialsPerByte):
#print 'The POW is strong enough that this ackdataPayload will be accepted by the Bitmessage network.'
#Currently PyBitmessage only supports sending a message with the acknowledgement in the form of a msg message. But future versions, and other clients, could send any object and this software will relay them. This can be used to relay identifying information, like your public key, through another Bitmessage host in case you believe that your Internet connection is being individually watched. You may pick a random address, hope its owner is online, and send a message with encoding type 0 so that they ignore the message but send your acknowledgement data over the network. If you send and receive many messages, it would also be clever to take someone else's acknowledgement data and use it for your own. Assuming that your message is delivered successfully, both will be acknowledged simultaneously (though if it is not delivered successfully, you will be in a pickle.)
#print 'self.data before:', repr(self.data)
#We'll need to make sure that our client will properly process the ackData; if the packet is malformed, we could clear out self.data and an attacker could use that behavior to determine that we were capable of decoding this message.
ackDataValidThusFar = True
if len(ackData) < 24:
print 'The length of ackData is unreasonably short. Not sending ackData.'
ackDataValidThusFar = False
if ackData[0:4] != '\xe9\xbe\xb4\xd9':
print 'Ackdata magic bytes were wrong. Not sending ackData.'
ackDataValidThusFar = False
if ackDataValidThusFar:
ackDataPayloadLength, = unpack('>L',ackData[16:20])
if len(ackData)-24 != ackDataPayloadLength:
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
ackDataValidThusFar = False
if ackDataValidThusFar:
print 'ackData is valid. Will process it.'
#self.data = self.data[:self.payloadLength+24] + ackData + self.data[self.payloadLength+24:]
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.
#print 'self.data after:', repr(self.data)
#This section is for my RSA keys (version 1 addresses). If we don't have any version 1 addresses, then it won't matter.
initialDecryptionSuccessful = False
2012-11-19 20:45:05 +01:00
infile = cStringIO.StringIO(self.data[readPosition:self.payloadLength+24])
outfile = cStringIO.StringIO()
2013-01-18 23:38:09 +01:00
#print 'len(myRSAAddressHashes.items()):', len(myRSAAddressHashes.items())
for key, value in myRSAAddressHashes.items():
2012-11-19 20:45:05 +01:00
try:
decrypt_bigfile(infile, outfile, value)
#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
except Exception, 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).
if initialDecryptionSuccessful and outfile.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.
flushInventory() #so that we won't accidentially receive this message twice if the user restarts Bitmessage soon.
outfile.seek(0)
data = outfile.getvalue()
readPosition = 20 #To start reading past the 20 zero bytes
messageVersion, messageVersionLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += messageVersionLength
if messageVersion == 1:
bitfieldBehavior = data[readPosition:readPosition+4]
readPosition += 4
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(data[readPosition:readPosition+10])
if sendersAddressVersionNumber == 1:
readPosition += sendersAddressVersionNumberLength
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += sendersStreamNumberLength
sendersNLength, sendersNLengthLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += sendersNLengthLength
sendersN = data[readPosition:readPosition+sendersNLength]
readPosition += sendersNLength
sendersELength, sendersELengthLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += sendersELengthLength
sendersE = data[readPosition:readPosition+sendersELength]
readPosition += sendersELength
endOfThePublicKeyPosition = readPosition
messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += messageEncodingTypeLength
print 'Message Encoding Type:', messageEncodingType
messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+10])
print 'message length:', messageLength
readPosition += messageLengthLength
message = data[readPosition:readPosition+messageLength]
#print 'First 150 characters of message:', repr(message[:150])
readPosition += messageLength
ackLength, ackLengthLength = decodeVarint(data[readPosition:readPosition+10])
#print 'ackLength:', ackLength
readPosition += ackLengthLength
ackData = data[readPosition:readPosition+ackLength]
readPosition += ackLength
payloadSigniture = data[readPosition:readPosition+sendersNLength] #We're using the length of the sender's n because it should match the signiture size.
sendersPubkey = rsa.PublicKey(convertStringToInt(sendersN),convertStringToInt(sendersE))
print 'sender\'s Pubkey', sendersPubkey
#Check the cryptographic signiture