2013-07-28 22:43:00 +02:00
softwareVersion = ' 0.3.5 '
2013-06-24 21:51:01 +02:00
verbose = 1
maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # Equals two days and 12 hours.
lengthOfTimeToLeaveObjectsInInventory = 237600 # Equals two days and 18 hours. This should be longer than maximumAgeOfAnObjectThatIAmWillingToAccept so that we don't process messages twice.
lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time.
maximumAgeOfObjectsThatIAdvertiseToOthers = 216000 # Equals two days and 12 hours
maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours
useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the normal network, you won't be able to send or sometimes receive messages.
2013-05-02 17:53:54 +02:00
2013-07-08 22:21:29 +02:00
# Libraries.
2013-07-30 22:23:18 +02:00
import collections
2013-06-23 21:52:39 +02:00
import ConfigParser
2013-07-08 22:21:29 +02:00
import os
import pickle
import Queue
2013-06-24 21:51:01 +02:00
import random
2013-07-08 22:21:29 +02:00
import socket
import sys
import stat
import threading
import time
# Project imports.
from addresses import *
2013-06-24 21:51:01 +02:00
import highlevelcrypto
import shared
2013-07-14 22:12:59 +02:00
import helper_startup
2013-05-02 17:53:54 +02:00
2013-06-23 21:52:39 +02:00
config = ConfigParser . SafeConfigParser ( )
2013-05-02 17:53:54 +02:00
myECCryptorObjects = { }
MyECSubscriptionCryptorObjects = { }
myAddressesByHash = { } #The key in this dictionary is the RIPE hash which is encoded in an address and value is the address itself.
broadcastSendersForWhichImWatching = { }
workerQueue = Queue . Queue ( )
sqlSubmitQueue = Queue . Queue ( ) #SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks. SQL objects can only be called from one thread.
sqlReturnQueue = Queue . Queue ( )
sqlLock = threading . Lock ( )
UISignalQueue = Queue . Queue ( )
addressGeneratorQueue = Queue . Queue ( )
knownNodesLock = threading . Lock ( )
knownNodes = { }
sendDataQueues = [ ] #each sendData thread puts its queue in this list.
inventory = { } #of objects (like msg payloads and pubkey payloads) Does not include protocol headers (the first 24 bytes of each packet).
inventoryLock = threading . Lock ( ) #Guarantees that two receiveDataThreads don't receive and process the same message concurrently (probably sent by a malicious individual)
printLock = threading . Lock ( )
appdata = ' ' #holds the location of the application data storage directory
statusIconColor = ' red '
2013-05-03 18:05:57 +02:00
connectedHostsList = { } #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice.
2013-05-30 22:25:42 +02:00
shutdown = 0 #Set to 1 by the doCleanShutdown function. Used to tell the proof of work worker threads to exit.
2013-06-24 21:51:01 +02:00
alreadyAttemptedConnectionsList = {
} # This is a list of nodes to which we have already attempted a connection
alreadyAttemptedConnectionsListLock = threading . Lock ( )
alreadyAttemptedConnectionsListResetTime = int (
time . time ( ) ) # used to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect.
numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer = { }
neededPubkeys = { }
eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack (
' >Q ' , random . randrange ( 1 , 18446744073709551615 ) )
successfullyDecryptMessageTimings = [
] # A list of the amounts of time it took to successfully decrypt msg messages
apiAddressGeneratorReturnQueue = Queue . Queue (
) # The address generator thread uses this queue to get information back to the API thread.
ackdataForWhichImWatching = { }
2013-08-25 01:40:48 +02:00
clientHasReceivedIncomingConnections = False #used by API command clientStatus
numberOfMessagesProcessed = 0
numberOfBroadcastsProcessed = 0
numberOfPubkeysProcessed = 0
2013-05-02 17:53:54 +02:00
2013-05-02 21:59:10 +02:00
#If changed, these values will cause particularly unexpected behavior: You won't be able to either send or receive messages because the proof of work you do (or demand) won't match that done or demanded by others. Don't change them!
networkDefaultProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work.
networkDefaultPayloadLengthExtraBytes = 14000 #To make sending short messages a little more difficult, this value is added to the payload length for use in calculating the proof of work target.
2013-07-17 18:33:26 +02:00
# Remember here the RPC port read from namecoin.conf so we can restore to
# it as default whenever the user changes the "method" selection for
# namecoin integration to "namecoind".
namecoinDefaultRpcPort = " 8336 "
2013-06-24 21:51:01 +02:00
def isInSqlInventory ( hash ) :
t = ( hash , )
shared . sqlLock . acquire ( )
shared . sqlSubmitQueue . put ( ''' select hash from inventory where hash=? ''' )
shared . sqlSubmitQueue . put ( t )
queryreturn = shared . sqlReturnQueue . get ( )
shared . sqlLock . release ( )
if queryreturn == [ ] :
return False
else :
return True
def assembleVersionMessage ( remoteHost , remotePort , myStreamNumber ) :
payload = ' '
payload + = pack ( ' >L ' , 2 ) # protocol version.
payload + = pack ( ' >q ' , 1 ) # bitflags of the services I offer.
payload + = pack ( ' >q ' , int ( time . time ( ) ) )
payload + = pack (
' >q ' , 1 ) # boolservices of remote connection. How can I even know this for sure? This is probably ignored by the remote host.
payload + = ' \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \xFF \xFF ' + \
socket . inet_aton ( remoteHost )
payload + = pack ( ' >H ' , remotePort ) # remote IPv6 and port
payload + = pack ( ' >q ' , 1 ) # bitflags of the services I offer.
payload + = ' \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \xFF \xFF ' + pack (
' >L ' , 2130706433 ) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
payload + = pack ( ' >H ' , shared . config . getint (
' bitmessagesettings ' , ' port ' ) ) # my external IPv6 and port
random . seed ( )
payload + = eightBytesOfRandomDataUsedToDetectConnectionsToSelf
2013-08-07 21:15:49 +02:00
userAgent = ' /PyBitmessage: ' + shared . softwareVersion + ' / '
payload + = encodeVarint ( len ( userAgent ) )
2013-06-24 21:51:01 +02:00
payload + = userAgent
payload + = encodeVarint (
1 ) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection.
payload + = encodeVarint ( myStreamNumber )
datatosend = ' \xe9 \xbe \xb4 \xd9 ' # magic bits, slighly different from Bitcoin's magic bits.
datatosend = datatosend + ' version \x00 \x00 \x00 \x00 \x00 ' # version command
datatosend = datatosend + pack ( ' >L ' , len ( payload ) ) # payload length
datatosend = datatosend + hashlib . sha512 ( payload ) . digest ( ) [ 0 : 4 ]
return datatosend + payload
2013-05-02 17:53:54 +02:00
def lookupAppdataFolder ( ) :
APPNAME = " PyBitmessage "
from os import path , environ
if sys . platform == ' darwin ' :
if " HOME " in environ :
2013-06-21 20:26:33 +02:00
dataFolder = path . join ( os . environ [ " HOME " ] , " Library/Application Support/ " , APPNAME ) + ' / '
2013-05-02 17:53:54 +02:00
else :
2013-07-15 11:56:13 +02:00
stringToLog = ' Could not find home folder, please report this message and your OS X version to the BitMessage Github. '
2013-07-15 11:49:01 +02:00
if ' logger ' in globals ( ) :
2013-07-15 11:56:13 +02:00
logger . critical ( stringToLog )
else :
print stringToLog
2013-05-02 17:53:54 +02:00
sys . exit ( )
elif ' win32 ' in sys . platform or ' win64 ' in sys . platform :
2013-05-03 21:53:38 +02:00
dataFolder = path . join ( environ [ ' APPDATA ' ] , APPNAME ) + ' \\ '
2013-05-02 17:53:54 +02:00
else :
2013-06-26 11:11:32 +02:00
from shutil import move
try :
dataFolder = path . join ( environ [ " XDG_CONFIG_HOME " ] , APPNAME )
except KeyError :
dataFolder = path . join ( environ [ " HOME " ] , " .config " , APPNAME )
2013-07-10 20:50:18 +02:00
2013-06-26 11:11:32 +02:00
# Migrate existing data to the proper location if this is an existing install
2013-07-10 21:15:04 +02:00
try :
2013-07-15 18:19:53 +02:00
move ( path . join ( environ [ " HOME " ] , " . %s " % APPNAME ) , dataFolder )
2013-07-15 11:56:13 +02:00
stringToLog = " Moving data folder to %s " % ( dataFolder )
2013-07-15 11:49:01 +02:00
if ' logger ' in globals ( ) :
2013-07-15 11:56:13 +02:00
logger . info ( stringToLog )
else :
print stringToLog
2013-07-10 21:15:04 +02:00
except IOError :
2013-07-12 00:58:10 +02:00
# Old directory may not exist.
2013-07-10 21:15:04 +02:00
pass
2013-07-10 20:50:18 +02:00
dataFolder = dataFolder + ' / '
2013-05-03 21:53:38 +02:00
return dataFolder
2013-05-02 17:53:54 +02:00
def isAddressInMyAddressBook ( address ) :
2013-06-14 04:16:37 +02:00
t = ( address , )
2013-05-02 17:53:54 +02:00
sqlLock . acquire ( )
sqlSubmitQueue . put ( ''' select address from addressbook where address=? ''' )
sqlSubmitQueue . put ( t )
queryreturn = sqlReturnQueue . get ( )
sqlLock . release ( )
return queryreturn != [ ]
2013-06-14 03:55:38 +02:00
#At this point we should really just have a isAddressInMy(book, address)...
def isAddressInMySubscriptionsList ( address ) :
2013-06-14 04:27:14 +02:00
t = ( str ( address ) , ) # As opposed to Qt str
2013-06-14 03:55:38 +02:00
sqlLock . acquire ( )
sqlSubmitQueue . put ( ''' select * from subscriptions where address=? ''' )
sqlSubmitQueue . put ( t )
queryreturn = sqlReturnQueue . get ( )
sqlLock . release ( )
return queryreturn != [ ]
2013-06-14 04:03:03 +02:00
2013-05-02 17:53:54 +02:00
def isAddressInMyAddressBookSubscriptionsListOrWhitelist ( address ) :
if isAddressInMyAddressBook ( address ) :
return True
sqlLock . acquire ( )
sqlSubmitQueue . put ( ''' SELECT address FROM whitelist where address=? and enabled = ' 1 ' ''' )
sqlSubmitQueue . put ( ( address , ) )
queryreturn = sqlReturnQueue . get ( )
sqlLock . release ( )
if queryreturn < > [ ] :
return True
sqlLock . acquire ( )
sqlSubmitQueue . put ( ''' select address from subscriptions where address=? and enabled = ' 1 ' ''' )
sqlSubmitQueue . put ( ( address , ) )
queryreturn = sqlReturnQueue . get ( )
sqlLock . release ( )
if queryreturn < > [ ] :
return True
return False
def safeConfigGetBoolean ( section , field ) :
2013-06-27 12:02:52 +02:00
try :
return config . getboolean ( section , field )
2013-07-22 07:10:22 +02:00
except Exception , err :
return False
2013-05-02 17:53:54 +02:00
def decodeWalletImportFormat ( WIFstring ) :
fullString = arithmetic . changebase ( WIFstring , 58 , 256 )
privkey = fullString [ : - 4 ]
if fullString [ - 4 : ] != hashlib . sha256 ( hashlib . sha256 ( privkey ) . digest ( ) ) . digest ( ) [ : 4 ] :
2013-08-08 21:37:48 +02:00
logger . critical ( ' Major problem! When trying to decode one of your private keys, the checksum '
' failed. Here is the PRIVATE key: %s ' % str ( WIFstring ) )
2013-05-02 17:53:54 +02:00
return " "
else :
#checksum passed
if privkey [ 0 ] == ' \x80 ' :
return privkey [ 1 : ]
else :
2013-08-08 21:37:48 +02:00
logger . critical ( ' Major problem! When trying to decode one of your private keys, the '
2013-07-10 10:43:18 +02:00
' checksum passed but the key doesn \' t begin with hex 80. Here is the '
2013-08-08 21:37:48 +02:00
' PRIVATE key: %s ' % str ( WIFstring ) )
2013-05-02 17:53:54 +02:00
return " "
def reloadMyAddressHashes ( ) :
2013-07-10 20:50:18 +02:00
logger . debug ( ' reloading keys from keys.dat file ' )
2013-05-02 17:53:54 +02:00
myECCryptorObjects . clear ( )
myAddressesByHash . clear ( )
#myPrivateKeys.clear()
2013-06-27 12:02:52 +02:00
keyfileSecure = checkSensitiveFilePermissions ( appdata + ' keys.dat ' )
2013-05-02 17:53:54 +02:00
configSections = config . sections ( )
2013-06-27 12:02:52 +02:00
hasEnabledKeys = False
2013-05-02 17:53:54 +02:00
for addressInKeysFile in configSections :
if addressInKeysFile < > ' bitmessagesettings ' :
isEnabled = config . getboolean ( addressInKeysFile , ' enabled ' )
if isEnabled :
2013-06-27 12:44:49 +02:00
hasEnabledKeys = True
2013-05-02 17:53:54 +02:00
status , addressVersionNumber , streamNumber , hash = decodeAddress ( addressInKeysFile )
if addressVersionNumber == 2 or addressVersionNumber == 3 :
2013-06-27 12:44:49 +02:00
# Returns a simple 32 bytes of information encoded in 64 Hex characters,
# or null if there was an error.
privEncryptionKey = decodeWalletImportFormat (
config . get ( addressInKeysFile , ' privencryptionkey ' ) ) . encode ( ' hex ' )
2013-05-02 17:53:54 +02:00
if len ( privEncryptionKey ) == 64 : #It is 32 bytes encoded as 64 hex characters
myECCryptorObjects [ hash ] = highlevelcrypto . makeCryptor ( privEncryptionKey )
myAddressesByHash [ hash ] = addressInKeysFile
2013-06-27 12:44:49 +02:00
2013-05-02 17:53:54 +02:00
else :
2013-08-06 19:19:26 +02:00
logger . error ( ' Error in reloadMyAddressHashes: Can \' t handle address versions other than 2 or 3. \n ' )
2013-06-27 12:44:49 +02:00
if not keyfileSecure :
fixSensitiveFilePermissions ( appdata + ' keys.dat ' , hasEnabledKeys )
2013-05-02 17:53:54 +02:00
def reloadBroadcastSendersForWhichImWatching ( ) :
2013-07-10 20:50:18 +02:00
logger . debug ( ' reloading subscriptions... ' )
2013-05-02 17:53:54 +02:00
broadcastSendersForWhichImWatching . clear ( )
MyECSubscriptionCryptorObjects . clear ( )
sqlLock . acquire ( )
sqlSubmitQueue . put ( ' SELECT address FROM subscriptions where enabled=1 ' )
sqlSubmitQueue . put ( ' ' )
queryreturn = sqlReturnQueue . get ( )
sqlLock . release ( )
for row in queryreturn :
address , = row
status , addressVersionNumber , streamNumber , hash = decodeAddress ( address )
if addressVersionNumber == 2 :
broadcastSendersForWhichImWatching [ hash ] = 0
#Now, for all addresses, even version 2 addresses, we should create Cryptor objects in a dictionary which we will use to attempt to decrypt encrypted broadcast messages.
privEncryptionKey = hashlib . sha512 ( encodeVarint ( addressVersionNumber ) + encodeVarint ( streamNumber ) + hash ) . digest ( ) [ : 32 ]
MyECSubscriptionCryptorObjects [ hash ] = highlevelcrypto . makeCryptor ( privEncryptionKey . encode ( ' hex ' ) )
def doCleanShutdown ( ) :
2013-05-30 22:25:42 +02:00
global shutdown
shutdown = 1 #Used to tell proof of work worker threads to exit.
2013-05-02 17:53:54 +02:00
knownNodesLock . acquire ( )
UISignalQueue . put ( ( ' updateStatusBar ' , ' Saving the knownNodes list of peers to disk... ' ) )
output = open ( appdata + ' knownnodes.dat ' , ' wb ' )
2013-07-10 20:50:18 +02:00
logger . info ( ' finished opening knownnodes.dat. Now pickle.dump ' )
2013-05-02 17:53:54 +02:00
pickle . dump ( knownNodes , output )
2013-07-10 20:50:18 +02:00
logger . info ( ' Completed pickle.dump. Closing output... ' )
2013-05-02 17:53:54 +02:00
output . close ( )
knownNodesLock . release ( )
2013-07-10 20:50:18 +02:00
logger . info ( ' Finished closing knownnodes.dat output file. ' )
2013-05-02 17:53:54 +02:00
UISignalQueue . put ( ( ' updateStatusBar ' , ' Done saving the knownNodes list of peers to disk. ' ) )
broadcastToSendDataQueues ( ( 0 , ' shutdown ' , ' all ' ) )
2013-07-10 20:50:18 +02:00
logger . info ( ' Flushing inventory in memory out to disk... ' )
2013-07-10 21:15:04 +02:00
UISignalQueue . put ( (
' updateStatusBar ' ,
' Flushing inventory in memory out to disk. This should normally only take a second... ' ) )
2013-05-02 17:53:54 +02:00
flushInventory ( )
2013-07-10 20:50:18 +02:00
# This one last useless query will guarantee that the previous flush committed before we close
# the program.
2013-05-02 17:53:54 +02:00
sqlLock . acquire ( )
sqlSubmitQueue . put ( ' SELECT address FROM subscriptions ' )
sqlSubmitQueue . put ( ' ' )
sqlReturnQueue . get ( )
2013-05-16 18:41:04 +02:00
sqlSubmitQueue . put ( ' exit ' )
2013-05-07 22:31:18 +02:00
sqlLock . release ( )
2013-07-10 20:50:18 +02:00
logger . info ( ' Finished flushing inventory. ' )
2013-05-30 22:25:42 +02:00
2013-07-10 20:50:18 +02:00
# Wait long enough to guarantee that any running proof of work worker threads will check the
# shutdown variable and exit. If the main thread closes before they do then they won't stop.
time . sleep ( .25 )
2013-05-02 17:53:54 +02:00
if safeConfigGetBoolean ( ' bitmessagesettings ' , ' daemon ' ) :
2013-07-10 20:50:18 +02:00
logger . info ( ' Clean shutdown complete. ' )
2013-05-02 17:53:54 +02:00
os . _exit ( 0 )
2013-07-10 20:50:18 +02:00
# When you want to command a sendDataThread to do something, like shutdown or send some data, this
# function puts your data into the queues for each of the sendDataThreads. The sendDataThreads are
# responsible for putting their queue into (and out of) the sendDataQueues list.
2013-05-02 17:53:54 +02:00
def broadcastToSendDataQueues ( data ) :
2013-07-10 20:50:18 +02:00
# logger.debug('running broadcastToSendDataQueues')
2013-05-02 17:53:54 +02:00
for q in sendDataQueues :
q . put ( ( data ) )
def flushInventory ( ) :
#Note that the singleCleanerThread clears out the inventory dictionary from time to time, although it only clears things that have been in the dictionary for a long time. This clears the inventory dictionary Now.
sqlLock . acquire ( )
for hash , storedValue in inventory . items ( ) :
objectType , streamNumber , payload , receivedTime = storedValue
2013-08-06 19:19:26 +02:00
t = ( hash , objectType , streamNumber , payload , receivedTime , ' ' )
sqlSubmitQueue . put ( ''' INSERT INTO inventory VALUES (?,?,?,?,?,?) ''' )
2013-05-02 17:53:54 +02:00
sqlSubmitQueue . put ( t )
sqlReturnQueue . get ( )
del inventory [ hash ]
sqlSubmitQueue . put ( ' commit ' )
2013-06-11 00:53:15 +02:00
sqlLock . release ( )
def fixPotentiallyInvalidUTF8Data ( text ) :
try :
unicode ( text , ' utf-8 ' )
return text
except :
output = ' Part of the message is corrupt. The message cannot be displayed the normal way. \n \n ' + repr ( text )
2013-06-14 04:03:03 +02:00
return output
2013-07-14 22:12:59 +02:00
2013-06-27 12:44:49 +02:00
# Checks sensitive file permissions for inappropriate umask during keys.dat creation.
# (Or unwise subsequent chmod.)
2013-07-10 10:43:18 +02:00
#
2013-06-27 12:44:49 +02:00
# Returns true iff file appears to have appropriate permissions.
2013-06-27 12:02:52 +02:00
def checkSensitiveFilePermissions ( filename ) :
if sys . platform == ' win32 ' :
# TODO: This might deserve extra checks by someone familiar with
# Windows systems.
2013-06-27 12:44:49 +02:00
return True
2013-06-27 12:02:52 +02:00
else :
2013-08-05 22:06:46 +02:00
try :
# Skip known problems for non-Win32 filesystems without POSIX permissions.
import subprocess
fstype = subprocess . check_output ( ' stat -f -c " %% T " %s ' % ( filename ) ,
shell = True ,
stderr = subprocess . STDOUT )
if ' fuseblk ' in fstype :
logger . info ( ' Skipping file permissions check for %s . Filesystem fuseblk detected. ' ,
filename )
return True
except :
# Swallow exception here, but we might run into trouble later!
2013-08-13 02:32:13 +02:00
logger . error ( ' Could not determine filesystem type. %s ' , filename )
2013-06-27 12:44:49 +02:00
present_permissions = os . stat ( filename ) [ 0 ]
disallowed_permissions = stat . S_IRWXG | stat . S_IRWXO
return present_permissions & disallowed_permissions == 0
2013-06-27 12:02:52 +02:00
# Fixes permissions on a sensitive file.
2013-06-27 12:44:49 +02:00
def fixSensitiveFilePermissions ( filename , hasEnabledKeys ) :
if hasEnabledKeys :
2013-07-08 22:21:29 +02:00
logger . warning ( ' Keyfile had insecure permissions, and there were enabled keys. '
' The truly paranoid should stop using them immediately. ' )
2013-06-27 12:44:49 +02:00
else :
2013-07-08 22:21:29 +02:00
logger . warning ( ' Keyfile had insecure permissions, but there were no enabled keys. ' )
2013-06-27 12:44:49 +02:00
try :
present_permissions = os . stat ( filename ) [ 0 ]
disallowed_permissions = stat . S_IRWXG | stat . S_IRWXO
allowed_permissions = ( ( 1 << 32 ) - 1 ) ^ disallowed_permissions
new_permissions = (
allowed_permissions & present_permissions )
os . chmod ( filename , new_permissions )
2013-07-08 22:21:29 +02:00
logger . info ( ' Keyfile permissions automatically fixed. ' )
2013-06-27 12:44:49 +02:00
except Exception , e :
2013-07-08 22:21:29 +02:00
logger . exception ( ' Keyfile permissions could not be fixed. ' )
2013-06-27 12:44:49 +02:00
raise
2013-08-08 21:37:48 +02:00
def isBitSetWithinBitfield ( fourByteString , n ) :
# Uses MSB 0 bit numbering across 4 bytes of data
n = 31 - n
x , = unpack ( ' >L ' , fourByteString )
return x & 2 * * n != 0
2013-06-26 14:28:01 +02:00
2013-07-30 22:23:18 +02:00
Peer = collections . namedtuple ( ' Peer ' , [ ' host ' , ' port ' ] )
2013-07-14 22:12:59 +02:00
helper_startup . loadConfig ( )
2013-07-30 22:23:18 +02:00
from debug import logger