Exemple #1
0
 def setType(self):
     if shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = "chan"
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = "mailinglist"
     else:
         self.type = "normal"
Exemple #2
0
 def setType(self):
     if shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = "chan"
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = "mailinglist"
     else:
         self.type = "normal"
Exemple #3
0
    def updateText(self):
        text = unicode(shared.config.get(self.address, 'label'), 'utf-8)') + ' (' + self.address + ')'
        
        font = QtGui.QFont()
        if self.unreadCount > 0:
            # only show message count if the child doesn't show
            if not self.isExpanded():
                text += " (" + str(self.unreadCount) + ")"
            font.setBold(True)
        else:
            font.setBold(False)
        self.setFont(0, font)
            
        #set text color
        if shared.safeConfigGetBoolean(self.address, 'enabled'):
            if shared.safeConfigGetBoolean(self.address, 'mailinglist'):
                brush = QtGui.QBrush(QtGui.QColor(137, 04, 177))
            else:
                brush = QtGui.QBrush(QtGui.QApplication.palette().text().color())
            #self.setExpanded(True)        
        else:
            brush = QtGui.QBrush(QtGui.QColor(128, 128, 128))
            #self.setExpanded(False)
        brush.setStyle(QtCore.Qt.NoBrush)
        self.setForeground(0, brush)

        self.setIcon(0, avatarize(self.address))
        self.setText(0, text)
        self.setToolTip(0, text)
 def setType(self):
     if self.address is None:
         self.type = self.ALL
     elif shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = self.CHAN
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = self.MAILINGLIST
     else:
         self.type = self.NORMAL
Exemple #5
0
 def setType(self):
     self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
     if self.address is None:
         self.type = self.ALL
         self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)
     elif shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = self.CHAN
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = self.MAILINGLIST
     else:
         self.type = self.NORMAL
Exemple #6
0
 def setType(self):
     self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
     if self.address is None:
         self.type = self.ALL
         self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)
     elif shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = self.CHAN
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = self.MAILINGLIST
     else:
         self.type = self.NORMAL
Exemple #7
0
 def run(self):
     from debug import logger
     
     logger.debug("Starting UPnP thread")
     logger.debug("Local IP: %s", self.localIP)
     lastSent = 0
     while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
         if time.time() - lastSent > self.sendSleep and len(self.routers) == 0:
             try:
                 self.sendSearchRouter()
             except:
                 pass
             lastSent = time.time()
         try:
             while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
                 resp,(ip,port) = self.sock.recvfrom(1000)
                 if resp is None:
                     continue
                 newRouter = Router(resp, ip)
                 for router in self.routers:
                     if router.location == newRouter.location:
                         break
                 else:
                     logger.debug("Found UPnP router at %s", ip)
                     self.routers.append(newRouter)
                     self.createPortMapping(newRouter)
                     shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'UPnP port mapping established on port %1').arg(str(self.extPort))))
                     break
         except socket.timeout as e:
             pass
         except:
             logger.error("Failure running UPnP router search.", exc_info=True)
         for router in self.routers:
             if router.extPort is None:
                 self.createPortMapping(router)
     try:
         self.sock.shutdown(socket.SHUT_RDWR)
     except:
         pass
     try:
         self.sock.close()
     except:
         pass
     deleted = False
     for router in self.routers:
         if router.extPort is not None:
             deleted = True
             self.deletePortMapping(router)
     shared.extPort = None
     if deleted:
         shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'UPnP port mapping removed')))
     logger.debug("UPnP thread done")
Exemple #8
0
 def setType(self):
     self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
     if self.address is None:
         self.type = self.ALL
         self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)
     elif shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = self.CHAN
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = self.MAILINGLIST
     elif sqlQuery('''select label from subscriptions where address=?''',
                   self.address):
         self.type = AccountMixin.SUBSCRIPTION
     else:
         self.type = self.NORMAL
Exemple #9
0
 def __init__(self, address=None):
     self.address = address
     self.type = AccountMixin.NORMAL
     if shared.config.has_section(address):
         if shared.safeConfigGetBoolean(self.address, "chan"):
             self.type = AccountMixin.CHAN
         elif shared.safeConfigGetBoolean(self.address, "mailinglist"):
             self.type = AccountMixin.MAILINGLIST
     elif self.address == str_broadcast_subscribers:
         self.type = AccountMixin.BROADCAST
     else:
         queryreturn = sqlQuery("""select label from subscriptions where address=?""", self.address)
         if queryreturn:
             self.type = AccountMixin.SUBSCRIPTION
Exemple #10
0
 def setType(self):
     self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
     if self.address is None:
         self.type = self.ALL
         self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)
     elif shared.safeConfigGetBoolean(self.address, 'chan'):
         self.type = self.CHAN
     elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
         self.type = self.MAILINGLIST
     elif sqlQuery(
         '''select label from subscriptions where address=?''', self.address):
         self.type = AccountMixin.SUBSCRIPTION
     else:
         self.type = self.NORMAL
Exemple #11
0
 def __init__(self, address = None):
     self.address = address
     self.type = AccountMixin.NORMAL
     if shared.config.has_section(address):
         if shared.safeConfigGetBoolean(self.address, 'chan'):
             self.type = AccountMixin.CHAN
         elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
             self.type = AccountMixin.MAILINGLIST
     elif self.address == str_broadcast_subscribers:
         self.type = AccountMixin.BROADCAST
     else:
         queryreturn = sqlQuery(
             '''select label from subscriptions where address=?''', self.address)
         if queryreturn:
             self.type = AccountMixin.SUBSCRIPTION
Exemple #12
0
 def __init__(self, address, type = None):
     self.isEnabled = True
     self.address = address
     if type is None:
         if shared.safeConfigGetBoolean(self.address, 'mailinglist'):
             self.type = "mailinglist"
         elif shared.safeConfigGetBoolean(self.address, 'chan'):
             self.type = "chan"
         elif sqlQuery(
             '''select label from subscriptions where address=?''', self.address):
             self.type = 'subscription'
         else:
             self.type = "normal"
     else:
         self.type = type
Exemple #13
0
 def __init__(self, address = None):
     self.address = address
     self.type = 'normal'
     if shared.config.has_section(address):
         if shared.safeConfigGetBoolean(self.address, 'chan'):
             self.type = "chan"
         elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
             self.type = "mailinglist"
     elif self.address == str_broadcast_subscribers:
         self.type = 'broadcast'
     else:
         queryreturn = sqlQuery(
             '''select label from subscriptions where address=?''', self.address)
         if queryreturn:
             self.type = 'subscription'
Exemple #14
0
 def run(self):
     from debug import logger
     
     logger.debug("Starting UPnP thread")
     lastSent = 0
     while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
         if time.time() - lastSent > self.sendSleep and len(self.routers) == 0:
             self.sendSearchRouter()
             lastSent = time.time()
         try:
             while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
                 resp,(ip,port) = self.sock.recvfrom(1000)
                 if resp is None:
                     continue
                 newRouter = Router(resp, ip)
                 for router in self.routers:
                     if router.location == newRouter.location:
                         break
                 else:
                     logger.debug("Found UPnP router at %s", ip)
                     self.routers.append(newRouter)
                     self.createPortMapping(newRouter)
                     shared.UISignalQueue.put(('updateStatusBar', tr.translateText("MainWindow",'UPnP port mapping established on port %1').arg(str(self.extPort))))
                     break
         except socket.timeout as e:
             pass
         except:
             logger.error("Failure running UPnP router search.", exc_info=True)
         for router in self.routers:
             if router.extPort is None:
                 self.createPortMapping(router)
     try:
         self.sock.shutdown(socket.SHUT_RDWR)
     except:
         pass
     try:
         self.sock.close()
     except:
         pass
     deleted = False
     for router in self.routers:
         if router.extPort is not None:
             deleted = True
             self.deletePortMapping(router)
     shared.extPort = None
     if deleted:
         shared.UISignalQueue.put(('updateStatusBar', tr.translateText("MainWindow",'UPnP port mapping removed')))
     logger.debug("UPnP thread done")
def signal_handler(signal, frame):
    if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
        shared.doCleanShutdown()
        sys.exit(0)
    else:
        print('Unfortunately you cannot use Ctrl+C ' +
              'when running the UI because the UI captures the signal.')
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if shared.trustedPeer:
            return

        while shared.safeConfigGetBoolean("bitmessagesettings", "dontconnect"):
            time.sleep(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections.
        while shared.config.get("bitmessagesettings", "socksproxytype")[
            0:5
        ] == "SOCKS" and not shared.config.getboolean("bitmessagesettings", "sockslisten"):
            time.sleep(5)

        with shared.printLock:
            print "Listening for incoming connections."

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error, e:
            if isinstance(e.args, tuple) and e.args[0] in (errno.EAFNOSUPPORT, errno.EPFNOSUPPORT, errno.ENOPROTOOPT):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise
Exemple #17
0
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if shared.trustedPeer:
            return

        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
            time.sleep(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections.
        while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not shared.config.getboolean('bitmessagesettings', 'sockslisten'):
            time.sleep(5)

        with shared.printLock:
            print 'Listening for incoming connections.'

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error, e:
            if (isinstance(e.args, tuple) and
                e.args[0] in (errno.EAFNOSUPPORT,
                              errno.EPFNOSUPPORT,
                              errno.ENOPROTOOPT)):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise
Exemple #18
0
 def __init__(self, address, type=None):
     self.isEnabled = True
     self.address = address
     if type is None:
         if address is None:
             self.type = AccountMixin.ALL
         elif shared.safeConfigGetBoolean(self.address, "mailinglist"):
             self.type = AccountMixin.MAILINGLIST
         elif shared.safeConfigGetBoolean(self.address, "chan"):
             self.type = AccountMixin.CHAN
         elif sqlQuery("""select label from subscriptions where address=?""", self.address):
             self.type = AccountMixin.SUBSCRIPTION
         else:
             self.type = AccountMixin.NORMAL
     else:
         self.type = type
Exemple #19
0
def getPowType():
    if safeConfigGetBoolean('bitmessagesettings',
                            'opencl') and openclpow.has_opencl():
        return "OpenCL"
    if bmpow:
        return "C"
    return "python"
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if shared.trustedPeer:
            return

        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect') and shared.shutdown == 0:
            self.stop.wait(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections.
        while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not shared.config.getboolean('bitmessagesettings', 'sockslisten') and shared.shutdown == 0:
            self.stop.wait(5)

        logger.info('Listening for incoming connections.')

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error, e:
            if (isinstance(e.args, tuple) and
                e.args[0] in (errno.EAFNOSUPPORT,
                              errno.EPFNOSUPPORT,
                              errno.ENOPROTOOPT)):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise
Exemple #21
0
def run(target, initialHash):
    target = int(target)
    if safeConfigGetBoolean('bitmessagesettings',
                            'opencl') and openclpow.has_opencl():
        #        trialvalue1, nonce1 = _doGPUPoW(target, initialHash)
        #        trialvalue, nonce = _doFastPoW(target, initialHash)
        #        print "GPU: %s, %s" % (trialvalue1, nonce1)
        #        print "Fast: %s, %s" % (trialvalue, nonce)
        #        return [trialvalue, nonce]
        try:
            return _doGPUPoW(target, initialHash)
        except:
            pass  # fallback
    if bmpow:
        try:
            return _doCPoW(target, initialHash)
        except:
            pass  # fallback
    if frozen == "macosx_app" or not frozen:
        # on my (Peter Surda) Windows 10, Windows Defender
        # does not like this and fights with PyBitmessage
        # over CPU, resulting in very slow PoW
        # added on 2015-11-29: multiprocesing.freeze_support() doesn't help
        try:
            return _doFastPoW(target, initialHash)
        except:
            pass  #fallback
    return _doSafePoW(target, initialHash)
Exemple #22
0
def getBitfield(address):
    # bitfield of features supported by me (see the wiki).
    bitfield = 0
    # send ack
    if not shared.safeConfigGetBoolean(address, 'dontsendack'):
        bitfield |= shared.BITFIELD_DOESACK
    return struct.pack('>I', bitfield)
def run(target, initialHash):
    target = int(target)
    if safeConfigGetBoolean('bitmessagesettings', 'opencl') and openclpow.has_opencl():
#        trialvalue1, nonce1 = _doGPUPoW(target, initialHash)
#        trialvalue, nonce = _doFastPoW(target, initialHash)
#        print "GPU: %s, %s" % (trialvalue1, nonce1)
#        print "Fast: %s, %s" % (trialvalue, nonce)
#        return [trialvalue, nonce]
        try:
            return _doGPUPoW(target, initialHash)
        except:
            pass # fallback
    if bmpow:
        try:
            return _doCPoW(target, initialHash)
        except:
            pass # fallback
    if frozen == "macosx_app" or not frozen:
        # on my (Peter Surda) Windows 10, Windows Defender
        # does not like this and fights with PyBitmessage
        # over CPU, resulting in very slow PoW
        # added on 2015-11-29: multiprocesing.freeze_support() doesn't help
        try:
            return _doFastPoW(target, initialHash)
        except:
            pass #fallback
    return _doSafePoW(target, initialHash)
Exemple #24
0
def getBitfield(address):
    # bitfield of features supported by me (see the wiki).
    bitfield = 0
    # send ack
    if not shared.safeConfigGetBoolean(address, "dontsendack"):
        bitfield |= shared.BITFIELD_DOESACK
    return struct.pack(">I", bitfield)
Exemple #25
0
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if shared.trustedPeer:
            return

        while shared.safeConfigGetBoolean(
                'bitmessagesettings', 'dontconnect') and shared.shutdown == 0:
            self.stop.wait(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections. But if on SOCKS and have an onionhostname, listen
        # (socket is then only opened for localhost)
        while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
            (not shared.config.getboolean('bitmessagesettings', 'sockslisten') and \
            ".onion" not in shared.config.get('bitmessagesettings', 'onionhostname')) and \
            shared.shutdown == 0:
            self.stop.wait(5)

        logger.info('Listening for incoming connections.')

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket(socket.AF_INET6)
        except socket.error, e:
            if (isinstance(e.args, tuple)
                    and e.args[0] in (errno.EAFNOSUPPORT, errno.EPFNOSUPPORT,
                                      errno.EADDRNOTAVAIL, errno.ENOPROTOOPT)):
                sock = self._createListenSocket(socket.AF_INET)
            else:
                raise
Exemple #26
0
def checkHasNormalAddress():
    for address in account.getSortedAccounts():
        acct = account.accountClass(address)
        if acct.type == AccountMixin.NORMAL and shared.safeConfigGetBoolean(
                address, 'enabled'):
            return address
    return False
    def run(self):
        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
            time.sleep(1)
        helper_bootstrap.dns()
        # We typically don't want to accept incoming connections if the user is using a
        # SOCKS proxy, unless they have configured otherwise. If they eventually select
        # proxy 'none' or configure SOCKS listening then this will start listening for
        # connections.
        while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not shared.config.getboolean('bitmessagesettings', 'sockslisten'):
            time.sleep(5)

        logger.info('Listening for incoming connections.')

        HOST = ''  # Symbolic name meaning all available interfaces
        PORT = shared.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)

        while True:
            # We typically don't want to accept incoming connections if the user is using a
            # SOCKS proxy, unless they have configured otherwise. If they eventually select
            # proxy 'none' or configure SOCKS listening then this will start listening for
            # connections.
            while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not shared.config.getboolean('bitmessagesettings', 'sockslisten'):
                time.sleep(10)
            while len(shared.connectedHostsList) > 220:
                logger.info('We are connected to too many people. Not accepting further incoming connections for ten seconds.')

                time.sleep(10)
            a, (HOST, PORT) = sock.accept()

            # The following code will, unfortunately, block an incoming
            # connection if someone else on the same LAN is already connected
            # because the two computers will share the same external IP. This
            # is here to prevent connection flooding.
            while HOST in shared.connectedHostsList:
                logger.info('We are already connected to %s . Ignoring connection.'%HOST)

                a.close()
                a, (HOST, PORT) = sock.accept()
            someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory.
            a.settimeout(20)

            sd = sendDataThread()
            sd.setup(
                a, HOST, PORT, -1, someObjectsOfWhichThisRemoteNodeIsAlreadyAware)
            sd.start()

            rd = receiveDataThread()
            rd.daemon = True  # close the main program even if there are threads left
            rd.setup(
                a, HOST, PORT, -1, someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections)
            rd.start()

            logger.info('%s connected to %s during INCOMING request.'%(self,HOST))
Exemple #28
0
 def __init__(self, address, type = None):
     self.isEnabled = True
     self.address = address
     if type is None:
         if address is None:
             self.type = AccountMixin.ALL
         elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
             self.type = AccountMixin.MAILINGLIST
         elif shared.safeConfigGetBoolean(self.address, 'chan'):
             self.type = AccountMixin.CHAN
         elif sqlQuery(
             '''select label from subscriptions where address=?''', self.address):
             self.type = AccountMixin.SUBSCRIPTION
         else:
             self.type = AccountMixin.NORMAL
     else:
         self.type = type
 def get_api_address():
     if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
         return None
     address = shared.config.get('bitmessagesettings', 'apiinterface')
     port = shared.config.getint('bitmessagesettings', 'apiport')
     return {
         'address': address,
         'port': port
     }
def getMyAddresses():
    """
    Generator which returns all your addresses.
    """
    configSections = shared.config.sections()
    for addressInKeysFile in configSections:
        if addressInKeysFile != 'bitmessagesettings' and not shared.safeConfigGetBoolean(addressInKeysFile, 'chan'):
            isEnabled = shared.config.getboolean(
                addressInKeysFile, 'enabled')  # I realize that this is poor programming practice but I don't care. It's easier for others to read.
            if isEnabled:
                yield addressInKeysFile
Exemple #31
0
def run(target, initialHash):
    target = int(target)
    if shared.safeConfigGetBoolean('bitmessagesettings', 'opencl') and openclpow.has_opencl():
#        trialvalue1, nonce1 = _doGPUPoW(target, initialHash)
#        trialvalue, nonce = _doFastPoW(target, initialHash)
#        print "GPU: %s, %s" % (trialvalue1, nonce1)
#        print "Fast: %s, %s" % (trialvalue, nonce)
#        return [trialvalue, nonce]
        return _doGPUPoW(target, initialHash)
    elif frozen == "macosx_app" or not frozen:
        return _doFastPoW(target, initialHash)
    else:
        return _doSafePoW(target, initialHash)
def getMyAddresses():
    """
    Generator which returns all your addresses.
    """
    configSections = shared.config.sections()
    for addressInKeysFile in configSections:
        if addressInKeysFile != 'bitmessagesettings' and not shared.safeConfigGetBoolean(
                addressInKeysFile, 'chan'):
            isEnabled = shared.config.getboolean(
                addressInKeysFile, 'enabled'
            )  # I realize that this is poor programming practice but I don't care. It's easier for others to read.
            if isEnabled:
                yield addressInKeysFile
Exemple #33
0
def signal_handler(signal, frame):
    logger.error("Got signal %i in %s/%s", signal,
                 current_process().name,
                 current_thread().name)
    if current_process().name != "MainProcess":
        raise StopIteration("Interrupted")
    if current_thread().name != "MainThread":
        return
    logger.error("Got signal %i", signal)
    if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
        shared.doCleanShutdown()
    else:
        print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.'
Exemple #34
0
def createSupportMessage(myapp):
    checkAddressBook(myapp)
    address = createAddressIfNeeded(myapp)
    if shared.shutdown:
        return

    myapp.ui.lineEditSubject.setText(str(QtGui.QApplication.translate("Support", SUPPORT_SUBJECT)))
    addrIndex = myapp.ui.comboBoxSendFrom.findData(address, QtCore.Qt.UserRole, QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive)
    if addrIndex == -1: # something is very wrong
        return
    myapp.ui.comboBoxSendFrom.setCurrentIndex(addrIndex)
    myapp.ui.lineEditTo.setText(SUPPORT_ADDRESS)
    
    version = shared.softwareVersion
    os = sys.platform
    if os == "win32":
        windowsversion = sys.getwindowsversion()
        os = "Windows " + str(windowsversion[0]) + "." + str(windowsversion[1])
    else:
        try:
            from os import uname
            unixversion = uname()
            os = unixversion[0] + " " + unixversion[2]
        except:
            pass
    architecture = "32" if ctypes.sizeof(ctypes.c_voidp) == 4 else "64"
    frozen = "N/A"
    if shared.frozen:
        frozen = shared.frozen
    portablemode = "True" if shared.appdata == shared.lookupExeFolder() else "False"
    cpow = "True" if bmpow else "False"
    #cpow = QtGui.QApplication.translate("Support", cpow)
    openclpow = "True" if shared.safeConfigGetBoolean('bitmessagesettings', 'opencl') and has_opencl() else "False"
    #openclpow = QtGui.QApplication.translate("Support", openclpow)
    locale = getTranslationLanguage()
    try:
        socks = shared.config.get('bitmessagesettings', 'socksproxytype')
    except:
        socks = "N/A"
    try:
        upnp = shared.config.get('bitmessagesettings', 'upnp')
    except:
        upnp = "N/A"
    connectedhosts = len(shared.connectedHostsList)

    myapp.ui.textEditMessage.setText(str(QtGui.QApplication.translate("Support", SUPPORT_MESSAGE)).format(version, os, architecture, frozen, portablemode, cpow, openclpow, locale, socks, upnp, connectedhosts))

    # single msg tab
    myapp.ui.tabWidgetSend.setCurrentIndex(0)
    # send tab
    myapp.ui.tabWidget.setCurrentIndex(1)
Exemple #35
0
def translateText(context, text):
    if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
        try:
            from PyQt4 import QtCore, QtGui
        except Exception as err:
            print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download   or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
            print 'Error message:', err
            os._exit(0)
        return QtGui.QApplication.translate(context, text)
    else:
        if '%' in text:
            return translateClass(context, text.replace('%','',1))
        else:
            return text
    def processgetpubkey(self, data):
        readPosition = 20  # bypass the nonce, time, and object type
        requestedAddressVersionNumber, addressVersionLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += addressVersionLength
        streamNumber, streamNumberLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += streamNumberLength

        myAddress = ''
        if requestedAddressVersionNumber <= 3 :
            requestedHash = data[readPosition:readPosition + 20]
            if len(requestedHash) != 20:
                return
            if requestedHash in shared.myAddressesByHash:  # if this address hash is one of mine
                myAddress = shared.myAddressesByHash[requestedHash]
        elif requestedAddressVersionNumber >= 4:
            requestedTag = data[readPosition:readPosition + 32]
            if len(requestedTag) != 32:
                return
            if requestedTag in shared.myAddressesByTag:
                myAddress = shared.myAddressesByTag[requestedTag]

        if myAddress == '':
            return

        if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
            return
        if decodeAddress(myAddress)[2] != streamNumber:
            return
        if shared.safeConfigGetBoolean(myAddress, 'chan'):
            return
        try:
            lastPubkeySendTime = int(shared.config.get(
                myAddress, 'lastpubkeysendtime'))
        except:
            lastPubkeySendTime = 0
        if lastPubkeySendTime > time.time() - 2419200:  # If the last time we sent our pubkey was more recent than 28 days ago...
            return
        if requestedAddressVersionNumber == 2:
            shared.workerQueue.put((
                'doPOWForMyV2Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 3:
            shared.workerQueue.put((
                'sendOutOrStoreMyV3Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 4:
            shared.workerQueue.put((
                'sendOutOrStoreMyV4Pubkey', myAddress))
 def _createListenSocket(self, family):
     HOST = ''  # Symbolic name meaning all available interfaces
     # If not sockslisten, but onionhostname defined, only listen on localhost
     if not shared.safeConfigGetBoolean('bitmessagesettings', 'sockslisten') and ".onion" in shared.config.get('bitmessagesettings', 'onionhostname'):
         HOST = shared.config.get('bitmessagesettings', 'onionbindip')
     PORT = shared.config.getint('bitmessagesettings', 'port')
     sock = socket.socket(family, socket.SOCK_STREAM)
     if family == socket.AF_INET6:
         # Make sure we can accept both IPv4 and IPv6 connections.
         # This is the default on everything apart from Windows
         sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
     # 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)
     return sock
Exemple #38
0
 def _createListenSocket(self, family):
     HOST = ''  # Symbolic name meaning all available interfaces
     # If not sockslisten, but onionhostname defined, only listen on localhost
     if not shared.safeConfigGetBoolean(
             'bitmessagesettings',
             'sockslisten') and ".onion" in shared.config.get(
                 'bitmessagesettings', 'onionhostname'):
         HOST = shared.config.get('bitmessagesettings', 'onionbindip')
     PORT = shared.config.getint('bitmessagesettings', 'port')
     sock = socket.socket(family, socket.SOCK_STREAM)
     if family == socket.AF_INET6:
         # Make sure we can accept both IPv4 and IPv6 connections.
         # This is the default on everything apart from Windows
         sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
     # 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)
     return sock
Exemple #39
0
 def data(self, role):
     if role == QtCore.Qt.DisplayRole:
         return self.label
     elif role == QtCore.Qt.EditRole:
         return self.label
     elif role == QtCore.Qt.ToolTipRole:
         return self.label + " (" + self.address + ")"
     elif role == QtCore.Qt.DecorationRole:
         if shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons'):
             if self.address is None:
                 return avatarize(self.label)
             else:
                 return avatarize(self.address)
     elif role == QtCore.Qt.FontRole:
         font = QtGui.QFont()
         return font
     elif role == QtCore.Qt.ForegroundRole:
         return self.accountBrush()
     elif role == QtCore.Qt.UserRole:
         return self.type
     return super(Ui_AddressBookWidgetItem, self).data(role)
Exemple #40
0
def translateText(context, text, n=None):
    if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
        try:
            from PyQt4 import QtCore, QtGui
        except Exception as err:
            print('PyBitmessage requires PyQt unless you want to run ' +
                  'it as a daemon and interact with it using the API. ' +
                  'You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download ' +
                  'or by installing \'python-qt4\' via your package manager. ' +
                  'If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon')
            print 'Error message:', err
            os._exit(0)
        if n is None:
            return QtGui.QApplication.translate(context, text)
        else:
            return QtGui.QApplication.translate(context, text, None, QtCore.QCoreApplication.CodecForTr, n)
    else:
        if '%' in text:
            return translateClass(context, text.replace('%', '', 1))
        else:
            return text
    def run(self):
        # If there is a trusted peer then we don't want to accept
        # incoming connections so we'll just abandon the thread
        if shared.trustedPeer:
            return

        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
            time.sleep(1)

        # First try listening on an IPv6 socket. This should also be
        # able to accept connections on IPv4. If that's not available
        # we'll fall back to IPv4-only.
        try:
            sock = self._createListenSocket()
        except socket.Error, e:
            if (isinstance(e.args, tuple) and
                e.args[0] in (errno.EAFNOSUPPORT,
                              errno.EPFNOSUPPORT,
                              errno.ENOPROTOOPT)):
                sock = self._createListenSocket()
            else:
                raise
Exemple #42
0
 def data(self, role):
     if role == QtCore.Qt.DisplayRole:
         return self.label
     elif role == QtCore.Qt.EditRole:
         return self.label
     elif role == QtCore.Qt.ToolTipRole:
         return self.label + " (" + self.address + ")"
     elif role == QtCore.Qt.DecorationRole:
         if shared.safeConfigGetBoolean('bitmessagesettings',
                                        'useidenticons'):
             if self.address is None:
                 return avatarize(self.label)
             else:
                 return avatarize(self.address)
     elif role == QtCore.Qt.FontRole:
         font = QtGui.QFont()
         return font
     elif role == QtCore.Qt.ForegroundRole:
         return self.accountBrush()
     elif role == QtCore.Qt.UserRole:
         return self.type
     return super(Ui_AddressBookWidgetItem, self).data(role)
    def run(self):
        timeWeLastClearedInventoryAndPubkeysTables = 0

        while True:
            shared.sqlLock.acquire()
            shared.UISignalQueue.put((
                'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)'))
            for hash, storedValue in shared.inventory.items():
                objectType, streamNumber, payload, receivedTime = storedValue
                if int(time.time()) - 3600 > receivedTime:
                    t = (hash, objectType, streamNumber, payload, receivedTime,'')
                    shared.sqlSubmitQueue.put(
                        '''INSERT INTO inventory VALUES (?,?,?,?,?,?)''')
                    shared.sqlSubmitQueue.put(t)
                    shared.sqlReturnQueue.get()
                    del shared.inventory[hash]
            shared.sqlSubmitQueue.put('commit')
            shared.UISignalQueue.put(('updateStatusBar', ''))
            shared.sqlLock.release()
            shared.broadcastToSendDataQueues((
                0, 'pong', 'no data'))  # commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes.
            # If we are running as a daemon then we are going to fill up the UI
            # queue which will never be handled by a UI. We should clear it to
            # save memory.
            if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
                shared.UISignalQueue.queue.clear()
            if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380:
                timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
                # inventory (moves data from the inventory data structure to
                # the on-disk sql database)
                shared.sqlLock.acquire()
                # inventory (clears pubkeys after 28 days and everything else
                # after 2 days and 12 hours)
                t = (int(time.time()) - shared.lengthOfTimeToLeaveObjectsInInventory, int(
                    time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys)
                shared.sqlSubmitQueue.put(
                    '''DELETE FROM inventory WHERE (receivedtime<? AND objecttype<>'pubkey') OR (receivedtime<?  AND objecttype='pubkey') ''')
                shared.sqlSubmitQueue.put(t)
                shared.sqlReturnQueue.get()

                # pubkeys
                t = (int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys,)
                shared.sqlSubmitQueue.put(
                    '''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''')
                shared.sqlSubmitQueue.put(t)
                shared.sqlReturnQueue.get()
                shared.sqlSubmitQueue.put('commit')

                t = ()
                shared.sqlSubmitQueue.put(
                    '''select toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, pubkeyretrynumber, msgretrynumber FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent') ''')  # If the message's folder='trash' then we'll ignore it.
                shared.sqlSubmitQueue.put(t)
                queryreturn = shared.sqlReturnQueue.get()
                for row in queryreturn:
                    if len(row) < 5:
                        with shared.printLock:
                            sys.stderr.write(
                                'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row))
                        time.sleep(3)

                        break
                    toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, pubkeyretrynumber, msgretrynumber = row
                    if status == 'awaitingpubkey':
                        if int(time.time()) - lastactiontime > (shared.maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))):
                            print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.'
                            try:
                                del shared.neededPubkeys[
                                    toripe]  # We need to take this entry out of the shared.neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently.
                            except:
                                pass

                            shared.UISignalQueue.put((
                                'updateStatusBar', 'Doing work necessary to again attempt to request a public key...'))
                            t = (int(
                                time.time()), pubkeyretrynumber + 1, toripe)
                            shared.sqlSubmitQueue.put(
                                '''UPDATE sent SET lastactiontime=?, pubkeyretrynumber=?, status='msgqueued' WHERE toripe=?''')
                            shared.sqlSubmitQueue.put(t)
                            shared.sqlReturnQueue.get()
                            shared.sqlSubmitQueue.put('commit')
                            shared.workerQueue.put(('sendmessage', ''))
                    else:  # status == msgsent
                        if int(time.time()) - lastactiontime > (shared.maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (msgretrynumber))):
                            print 'It has been a long time and we haven\'t heard an acknowledgement to our msg. Sending again.'
                            t = (int(
                                time.time()), msgretrynumber + 1, 'msgqueued', ackdata)
                            shared.sqlSubmitQueue.put(
                                '''UPDATE sent SET lastactiontime=?, msgretrynumber=?, status=? WHERE ackdata=?''')
                            shared.sqlSubmitQueue.put(t)
                            shared.sqlReturnQueue.get()
                            shared.sqlSubmitQueue.put('commit')
                            shared.workerQueue.put(('sendmessage', ''))
                            shared.UISignalQueue.put((
                                'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...'))
                shared.sqlSubmitQueue.put('commit')
                shared.sqlLock.release()
            time.sleep(300)
    def run(self):
        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
            time.sleep(2)
        while shared.safeConfigGetBoolean('bitmessagesettings', 'sendoutgoingconnections'):
            maximumConnections = 1 if shared.trustedPeer else 8 # maximum number of outgoing connections = 8
            while len(self.selfInitiatedConnections[self.streamNumber]) >= maximumConnections:
                time.sleep(10)
            if shared.shutdown:
                break
            random.seed()
            peer = self._getPeer()
            shared.alreadyAttemptedConnectionsListLock.acquire()
            while peer in shared.alreadyAttemptedConnectionsList or peer.host in shared.connectedHostsList:
                shared.alreadyAttemptedConnectionsListLock.release()
                # print 'choosing new sample'
                random.seed()
                peer = self._getPeer()
                time.sleep(1)
                # Clear out the shared.alreadyAttemptedConnectionsList every half
                # hour so that this program will again attempt a connection
                # to any nodes, even ones it has already tried.
                if (time.time() - shared.alreadyAttemptedConnectionsListResetTime) > 1800:
                    shared.alreadyAttemptedConnectionsList.clear()
                    shared.alreadyAttemptedConnectionsListResetTime = int(
                        time.time())
                shared.alreadyAttemptedConnectionsListLock.acquire()
            shared.alreadyAttemptedConnectionsList[peer] = 0
            shared.alreadyAttemptedConnectionsListLock.release()
            if peer.host.find(':') == -1:
                address_family = socket.AF_INET
            else:
                address_family = socket.AF_INET6
            try:
                sock = socks.socksocket(address_family, socket.SOCK_STREAM)
            except:
                """
                The line can fail on Windows systems which aren't
                64-bit compatiable:
                      File "C:\Python27\lib\socket.py", line 187, in __init__
                        _sock = _realsocket(family, type, proto)
                      error: [Errno 10047] An address incompatible with the requested protocol was used
                      
                So let us remove the offending address from our knownNodes file.
                """
                shared.knownNodesLock.acquire()
                try:
                    del shared.knownNodes[self.streamNumber][peer]
                except:
                    pass
                shared.knownNodesLock.release()
                with shared.printLock:
                    print 'deleting ', peer, 'from shared.knownNodes because it caused a socks.socksocket exception. We must not be 64-bit compatible.'
                continue
            # This option apparently avoids the TIME_WAIT state so that we
            # can rebind faster
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.settimeout(20)
            if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2:
                with shared.printLock:
                    print 'Trying an outgoing connection to', peer

                # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
                if shared.verbose >= 2:
                    with shared.printLock:
                        print '(Using SOCKS4a) Trying an outgoing connection to', peer

                proxytype = socks.PROXY_TYPE_SOCKS4
                sockshostname = shared.config.get(
                    'bitmessagesettings', 'sockshostname')
                socksport = shared.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 shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = shared.config.get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = shared.config.get(
                        'bitmessagesettings', 'sockspassword')
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)
            elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
                if shared.verbose >= 2:
                    with shared.printLock:
                        print '(Using SOCKS5) Trying an outgoing connection to', peer

                proxytype = socks.PROXY_TYPE_SOCKS5
                sockshostname = shared.config.get(
                    'bitmessagesettings', 'sockshostname')
                socksport = shared.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 shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = shared.config.get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = shared.config.get(
                        'bitmessagesettings', 'sockspassword')
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)

            try:
                sock.connect((peer.host, peer.port))
                rd = receiveDataThread()
                rd.daemon = True  # close the main program even if there are threads left
                someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory.
                sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection. 
                rd.setup(sock, 
                         peer.host, 
                         peer.port, 
                         self.streamNumber,
                         someObjectsOfWhichThisRemoteNodeIsAlreadyAware, 
                         self.selfInitiatedConnections, 
                         sendDataThreadQueue)
                rd.start()
                with shared.printLock:
                    print self, 'connected to', peer, 'during an outgoing attempt.'


                sd = sendDataThread(sendDataThreadQueue)
                sd.setup(sock, peer.host, peer.port, self.streamNumber,
                         someObjectsOfWhichThisRemoteNodeIsAlreadyAware)
                sd.start()
                sd.sendVersionMessage()

            except socks.GeneralProxyError as err:
                if shared.verbose >= 2:
                    with shared.printLock:
                        print 'Could NOT connect to', peer, 'during outgoing attempt.', err

                deletedPeer = None
                with shared.knownNodesLock:
                    """
                    It is remotely possible that peer is no longer in shared.knownNodes.
                    This could happen if two outgoingSynSender threads both try to 
                    connect to the same peer, both fail, and then both try to remove
                    it from shared.knownNodes. This is unlikely because of the
                    alreadyAttemptedConnectionsList but because we clear that list once
                    every half hour, it can happen.
                    """
                    if peer in shared.knownNodes[self.streamNumber]:
                        timeLastSeen = shared.knownNodes[self.streamNumber][peer]
                        if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure.
                            del shared.knownNodes[self.streamNumber][peer]
                            deletedPeer = peer
                if deletedPeer:
                    with shared.printLock:
                        print 'deleting', peer, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'

            except socks.Socks5AuthError as err:
                shared.UISignalQueue.put((
                    'updateStatusBar', tr.translateText(
                    "MainWindow", "SOCKS5 Authentication problem: %1").arg(str(err))))
            except socks.Socks5Error as err:
                pass
                print 'SOCKS5 error. (It is possible that the server wants authentication).)', str(err)
            except socks.Socks4Error as err:
                print 'Socks4Error:', err
            except socket.error as err:
                if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
                    print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err)
                else:
                    if shared.verbose >= 1:
                        with shared.printLock:
                            print 'Could NOT connect to', peer, 'during outgoing attempt.', err

                deletedPeer = None
                with shared.knownNodesLock:
                    """
                    It is remotely possible that peer is no longer in shared.knownNodes.
                    This could happen if two outgoingSynSender threads both try to 
                    connect to the same peer, both fail, and then both try to remove
                    it from shared.knownNodes. This is unlikely because of the
                    alreadyAttemptedConnectionsList but because we clear that list once
                    every half hour, it can happen.
                    """
                    if peer in shared.knownNodes[self.streamNumber]:
                        timeLastSeen = shared.knownNodes[self.streamNumber][peer]
                        if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure.
                            del shared.knownNodes[self.streamNumber][peer]
                            deletedPeer = peer
                if deletedPeer:
                    with shared.printLock:
                        print 'deleting', peer, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'

            except Exception as err:
                sys.stderr.write(
                    'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: ')
                import traceback
                traceback.print_exc()
            time.sleep(0.1)
    def processbroadcast(self, data):
        messageProcessingStartTime = time.time()
        shared.numberOfBroadcastsProcessed += 1
        shared.UISignalQueue.put(
            ('updateNumberOfBroadcastsProcessed', 'no data'))
        inventoryHash = calculateInventoryHash(data)
        readPosition = 20  # bypass the nonce, time, and object type
        broadcastVersion, broadcastVersionLength = decodeVarint(
            data[readPosition:readPosition + 9])
        readPosition += broadcastVersionLength
        if broadcastVersion < 4 or broadcastVersion > 5:
            logger.info(
                'Cannot decode incoming broadcast versions less than 4 or higher than 5. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
            )
            return
        cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += cleartextStreamNumberLength
        if broadcastVersion == 4:
            """
            v4 broadcasts are encrypted the same way the msgs are encrypted. To see if we are interested in a
            v4 broadcast, we try to decrypt it. This was replaced with v5 broadcasts which include a tag which 
            we check instead, just like we do with v4 pubkeys. 
            """
            signedData = data[8:readPosition]
            initialDecryptionSuccessful = False
            for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items(
            ):
                try:
                    decryptedData = cryptorObject.decrypt(data[readPosition:])
                    toRipe = key  # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
                    initialDecryptionSuccessful = True
                    logger.info(
                        'EC decryption successful using key associated with ripe hash: %s'
                        % key.encode('hex'))
                    break
                except Exception as err:
                    pass
                    # print 'cryptorObject.decrypt Exception:', err
            if not initialDecryptionSuccessful:
                # This is not a broadcast I am interested in.
                logger.debug(
                    'Length of time program spent failing to decrypt this v4 broadcast: %s seconds.'
                    % (time.time() - messageProcessingStartTime, ))
                return
        elif broadcastVersion == 5:
            embeddedTag = data[readPosition:readPosition + 32]
            readPosition += 32
            if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
                logger.debug('We\'re not interested in this broadcast.')
                return
            # We are interested in this broadcast because of its tag.
            signedData = data[
                8:
                readPosition]  # We're going to add some more data which is signed further down.
            cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
            try:
                decryptedData = cryptorObject.decrypt(data[readPosition:])
                logger.debug('EC decryption successful')
            except Exception as err:
                logger.debug('Broadcast version %s decryption Unsuccessful.' %
                             broadcastVersion)
                return
        # At this point this is a broadcast I have decrypted and am
        # interested in.
        readPosition = 0
        sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if broadcastVersion == 4:
            if sendersAddressVersion < 2 or sendersAddressVersion > 3:
                logger.warning(
                    'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
                )
                return
        elif broadcastVersion == 5:
            if sendersAddressVersion < 4:
                logger.info(
                    'Cannot decode senderAddressVersion less than 4 for broadcast version number 5. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
                )
                return
        readPosition += sendersAddressVersionLength
        sendersStream, sendersStreamLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if sendersStream != cleartextStreamNumber:
            logger.info(
                'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
            )
            return
        readPosition += sendersStreamLength
        behaviorBitfield = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        sendersPubSigningKey = '\x04' + \
            decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        sendersPubEncryptionKey = '\x04' + \
            decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        if sendersAddressVersion >= 3:
            requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.debug(
                'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s'
                % requiredAverageProofOfWorkNonceTrialsPerByte)
            requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.debug('sender\'s requiredPayloadLengthExtraBytes is %s' %
                         requiredPayloadLengthExtraBytes)
        endOfPubkeyPosition = readPosition

        sha = hashlib.new('sha512')
        sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
        ripeHasher = hashlib.new('ripemd160')
        ripeHasher.update(sha.digest())
        calculatedRipe = ripeHasher.digest()

        if broadcastVersion == 4:
            if toRipe != calculatedRipe:
                logger.info(
                    'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
                )
                return
        elif broadcastVersion == 5:
            calculatedTag = hashlib.sha512(
                hashlib.sha512(
                    encodeVarint(sendersAddressVersion) +
                    encodeVarint(sendersStream) +
                    calculatedRipe).digest()).digest()[32:]
            if calculatedTag != embeddedTag:
                logger.debug(
                    'The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
                )
                return
        messageEncodingType, messageEncodingTypeLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if messageEncodingType == 0:
            return
        readPosition += messageEncodingTypeLength
        messageLength, messageLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        readPosition += messageLengthLength
        message = decryptedData[readPosition:readPosition + messageLength]
        readPosition += messageLength
        readPositionAtBottomOfMessage = readPosition
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        readPosition += signatureLengthLength
        signature = decryptedData[readPosition:readPosition + signatureLength]
        signedData += decryptedData[:readPositionAtBottomOfMessage]
        if not highlevelcrypto.verify(signedData, signature,
                                      sendersPubSigningKey.encode('hex')):
            logger.debug('ECDSA verify failed')
            return
        logger.debug('ECDSA verify passed')

        fromAddress = encodeAddress(sendersAddressVersion, sendersStream,
                                    calculatedRipe)
        logger.info('fromAddress: %s' % fromAddress)

        # Let's store the public key in case we want to reply to this person.
        sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
                   calculatedRipe,
                   sendersAddressVersion, decryptedData[:endOfPubkeyPosition],
                   int(time.time()), 'yes')

        # Check to see whether we happen to be awaiting this
        # pubkey in order to send a message. If we are, it will do the POW
        # and send it.
        if broadcastVersion == 4:
            self.possibleNewPubkey(ripe=calculatedRipe)
        elif broadcastVersion == 5:
            self.possibleNewPubkey(address=fromAddress)

        fromAddress = encodeAddress(sendersAddressVersion, sendersStream,
                                    calculatedRipe)
        with shared.printLock:
            print 'fromAddress:', fromAddress

        if messageEncodingType == 2:
            subject, body = self.decodeType2Message(message)
            logger.info('Broadcast subject (first 100 characters): %s' %
                        repr(subject)[:100])
        elif messageEncodingType == 1:
            body = message
            subject = ''
        elif messageEncodingType == 0:
            logger.info(
                'messageEncodingType == 0. Doing nothing with the message.')
        else:
            body = 'Unknown encoding type.\n\n' + repr(message)
            subject = ''

        toAddress = '[Broadcast subscribers]'
        if messageEncodingType != 0:
            if helper_inbox.isMessageAlreadyInInbox(toAddress, fromAddress,
                                                    subject, body,
                                                    messageEncodingType):
                logger.info(
                    'This broadcast is already in our inbox. Ignoring it.')
            else:
                t = (inventoryHash, toAddress, fromAddress, subject,
                     int(time.time()), body, 'inbox', messageEncodingType, 0)
                helper_inbox.insert(t)

                shared.UISignalQueue.put(
                    ('displayNewInboxMessage', (inventoryHash, toAddress,
                                                fromAddress, subject, body)))

                # If we are behaving as an API then we might need to run an
                # outside command to let some program know that a new message
                # has arrived.
                if shared.safeConfigGetBoolean('bitmessagesettings',
                                               'apienabled'):
                    try:
                        apiNotifyPath = shared.config.get(
                            'bitmessagesettings', 'apinotifypath')
                    except:
                        apiNotifyPath = ''
                    if apiNotifyPath != '':
                        call([apiNotifyPath, "newBroadcast"])

        # Display timing data
        logger.info('Time spent processing this interesting broadcast: %s' %
                    (time.time() - messageProcessingStartTime, ))
Exemple #46
0
    def start(self, daemon=False):
        _fixWinsock()

        shared.daemon = daemon
        # is the application already running?  If yes then exit.
        thisapp = singleton.singleinstance()

        # get curses flag
        curses = False
        if '-c' in sys.argv:
            curses = True

        signal.signal(signal.SIGINT, helper_generic.signal_handler)
        # signal.signal(signal.SIGINT, signal.SIG_DFL)

        helper_bootstrap.knownNodes()
        # Start the address generation thread
        addressGeneratorThread = addressGenerator()
        addressGeneratorThread.daemon = True  # close the main program even if there are threads left
        addressGeneratorThread.start()

        # Start the thread that calculates POWs
        singleWorkerThread = singleWorker()
        singleWorkerThread.daemon = True  # close the main program even if there are threads left
        singleWorkerThread.start()

        # Start the SQL thread
        sqlLookup = sqlThread()
        sqlLookup.daemon = False  # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
        sqlLookup.start()

        # Start the thread that calculates POWs
        objectProcessorThread = objectProcessor()
        objectProcessorThread.daemon = False  # DON'T close the main program even the thread remains. This thread checks the shutdown variable after processing each object.
        objectProcessorThread.start()

        # Start the cleanerThread
        singleCleanerThread = singleCleaner()
        singleCleanerThread.daemon = True  # close the main program even if there are threads left
        singleCleanerThread.start()

        shared.reloadMyAddressHashes()
        shared.reloadBroadcastSendersForWhichImWatching()

        if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
            try:
                apiNotifyPath = shared.config.get(
                    'bitmessagesettings', 'apinotifypath')
            except:
                apiNotifyPath = ''
            if apiNotifyPath != '':
                with shared.printLock:
                    print 'Trying to call', apiNotifyPath

                call([apiNotifyPath, "startingUp"])
            singleAPIThread = singleAPI()
            singleAPIThread.daemon = True  # close the main program even if there are threads left
            singleAPIThread.start()

        connectToStream(1)

        singleListenerThread = singleListener()
        singleListenerThread.setup(selfInitiatedConnections)
        singleListenerThread.daemon = True  # close the main program even if there are threads left
        singleListenerThread.start()

        if daemon == False and shared.safeConfigGetBoolean('bitmessagesettings', 'daemon') == False:
            if curses == False:
                try:
                    from PyQt4 import QtCore, QtGui
                except Exception as err:
                    print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download   or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
                    print 'Error message:', err
                    print 'You can also run PyBitmessage with the new curses interface by providing \'-c\' as a commandline argument.'
                    os._exit(0)

                import bitmessageqt
                bitmessageqt.run()
            else:
                print 'Running with curses'
                import bitmessagecurses
                bitmessagecurses.runwrapper()
        else:
            shared.config.remove_option('bitmessagesettings', 'dontconnect')

            if daemon:
                with shared.printLock:
                    print 'Running as a daemon. The main program should exit this thread.'
            else:
                with shared.printLock:
                    print 'Running as a daemon. You can use Ctrl+C to exit.'
                while True:
                    time.sleep(20)
    def processgetpubkey(self, data):
        readPosition = 20  # bypass the nonce, time, and object type
        requestedAddressVersionNumber, addressVersionLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += addressVersionLength
        streamNumber, streamNumberLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += streamNumberLength

        if requestedAddressVersionNumber == 0:
            logger.debug(
                'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
            )
            return
        elif requestedAddressVersionNumber == 1:
            logger.debug(
                'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
            )
            return
        elif requestedAddressVersionNumber > 4:
            logger.debug(
                'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
            )
            return

        myAddress = ''
        if requestedAddressVersionNumber <= 3:
            requestedHash = data[readPosition:readPosition + 20]
            if len(requestedHash) != 20:
                logger.debug(
                    'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
                )
                return
            logger.info('the hash requested in this getpubkey request is: %s' %
                        requestedHash.encode('hex'))
            if requestedHash in shared.myAddressesByHash:  # if this address hash is one of mine
                myAddress = shared.myAddressesByHash[requestedHash]
        elif requestedAddressVersionNumber >= 4:
            requestedTag = data[readPosition:readPosition + 32]
            if len(requestedTag) != 32:
                logger.debug(
                    'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
                )
                return
            logger.debug('the tag requested in this getpubkey request is: %s' %
                         requestedTag.encode('hex'))
            if requestedTag in shared.myAddressesByTag:
                myAddress = shared.myAddressesByTag[requestedTag]

        if myAddress == '':
            logger.info('This getpubkey request is not for any of my keys.')
            return

        if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
            logger.warning(
                '(Within the processgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.'
            )
            return
        if decodeAddress(myAddress)[2] != streamNumber:
            logger.warning(
                '(Within the processgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.'
            )
            return
        if shared.safeConfigGetBoolean(myAddress, 'chan'):
            logger.info(
                'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
            )
            return
        try:
            lastPubkeySendTime = int(
                shared.config.get(myAddress, 'lastpubkeysendtime'))
        except:
            lastPubkeySendTime = 0
        if lastPubkeySendTime > time.time(
        ) - 2419200:  # If the last time we sent our pubkey was more recent than 28 days ago...
            logger.info(
                'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is: %s'
                % lastPubkeySendTime)
            return
        logger.info(
            'Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.'
        )
        if requestedAddressVersionNumber == 2:
            shared.workerQueue.put(('doPOWForMyV2Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 3:
            shared.workerQueue.put(('sendOutOrStoreMyV3Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 4:
            shared.workerQueue.put(('sendOutOrStoreMyV4Pubkey', myAddress))
    def processmsg(self, data):
        messageProcessingStartTime = time.time()
        shared.numberOfMessagesProcessed += 1
        shared.UISignalQueue.put(
            ('updateNumberOfMessagesProcessed', 'no data'))
        readPosition = 20  # bypass the nonce, time, and object type
        msgVersion, msgVersionLength = decodeVarint(
            data[readPosition:readPosition + 9])
        if msgVersion != 1:
            logger.info(
                'Cannot understand message versions other than one. Ignoring message.'
            )
            return
        readPosition += msgVersionLength

        streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
            data[readPosition:readPosition + 9])
        readPosition += streamNumberAsClaimedByMsgLength
        inventoryHash = calculateInventoryHash(data)
        initialDecryptionSuccessful = False
        # Let's check whether this is a message acknowledgement bound for us.
        if data[-32:] in shared.ackdataForWhichImWatching:
            logger.info('This msg IS an acknowledgement bound for me.')
            del shared.ackdataForWhichImWatching[data[-32:]]
            sqlExecute('UPDATE sent SET status=? WHERE ackdata=?',
                       'ackreceived', data[-32:])
            shared.UISignalQueue.put(
                ('updateSentItemStatusByAckdata',
                 (data[-32:],
                  tr.translateText(
                      "MainWindow",
                      'Acknowledgement of the message received. %1').arg(
                          l10n.formatTimestamp()))))
            return
        else:
            logger.info('This was NOT an acknowledgement bound for me.')

        # 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.

        for key, cryptorObject in shared.myECCryptorObjects.items():
            try:
                decryptedData = cryptorObject.decrypt(data[readPosition:])
                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
                logger.info(
                    'EC decryption successful using key associated with ripe hash: %s.'
                    % key.encode('hex'))
                break
            except Exception as err:
                pass
        if not initialDecryptionSuccessful:
            # This is not a message bound for me.
            logger.info(
                'Length of time program spent failing to decrypt this message: %s seconds.'
                % (time.time() - messageProcessingStartTime, ))
            return

        # This is a message bound for me.
        toAddress = shared.myAddressesByHash[
            toRipe]  # Look up my address based on the RIPE hash.
        readPosition = 0
        sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += sendersAddressVersionNumberLength
        if sendersAddressVersionNumber == 0:
            logger.info(
                'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
            )
            return
        if sendersAddressVersionNumber > 4:
            logger.info(
                'Sender\'s address version number %s not yet supported. Ignoring message.'
                % sendersAddressVersionNumber)
            return
        if len(decryptedData) < 170:
            logger.info(
                'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
            )
            return
        sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        if sendersStreamNumber == 0:
            logger.info('sender\'s stream number is 0. Ignoring message.')
            return
        readPosition += sendersStreamNumberLength
        behaviorBitfield = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        pubSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        pubEncryptionKey = '\x04' + decryptedData[readPosition:readPosition +
                                                  64]
        readPosition += 64
        if sendersAddressVersionNumber >= 3:
            requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.info(
                'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s'
                % requiredAverageProofOfWorkNonceTrialsPerByte)
            requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.info('sender\'s requiredPayloadLengthExtraBytes is %s' %
                        requiredPayloadLengthExtraBytes)
        endOfThePublicKeyPosition = readPosition  # needed for when we store the pubkey in our database of pubkeys for later use.
        if toRipe != decryptedData[readPosition:readPosition + 20]:
            logger.info(
                'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.\n\
                See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html \n\
                your toRipe: %s\n\
                embedded destination toRipe: %s' %
                (toRipe.encode('hex'),
                 decryptedData[readPosition:readPosition + 20].encode('hex')))
            return
        readPosition += 20
        messageEncodingType, messageEncodingTypeLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += messageEncodingTypeLength
        messageLength, messageLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += messageLengthLength
        message = decryptedData[readPosition:readPosition + messageLength]
        # print 'First 150 characters of message:', repr(message[:150])
        readPosition += messageLength
        ackLength, ackLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += ackLengthLength
        ackData = decryptedData[readPosition:readPosition + ackLength]
        readPosition += ackLength
        positionOfBottomOfAckData = readPosition  # needed to mark the end of what is covered by the signature
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += signatureLengthLength
        signature = decryptedData[readPosition:readPosition + signatureLength]
        signedData = data[8:20] + encodeVarint(
            1) + encodeVarint(streamNumberAsClaimedByMsg
                              ) + decryptedData[:positionOfBottomOfAckData]

        if not highlevelcrypto.verify(signedData, signature,
                                      pubSigningKey.encode('hex')):
            logger.debug('ECDSA verify failed')
            return
        logger.debug('ECDSA verify passed')
        logger.debug(
            'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person: %s  ..and here is the testnet address: %s. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
            %
            (helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey),
             helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey)))

        # calculate the fromRipe.
        sha = hashlib.new('sha512')
        sha.update(pubSigningKey + pubEncryptionKey)
        ripe = hashlib.new('ripemd160')
        ripe.update(sha.digest())
        fromAddress = encodeAddress(sendersAddressVersionNumber,
                                    sendersStreamNumber, ripe.digest())

        # Let's store the public key in case we want to reply to this
        # person.
        sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', ripe.digest(),
                   sendersAddressVersionNumber,
                   decryptedData[:endOfThePublicKeyPosition], int(time.time()),
                   'yes')

        # Check to see whether we happen to be awaiting this
        # pubkey in order to send a message. If we are, it will do the POW
        # and send it.
        if sendersAddressVersionNumber <= 3:
            self.possibleNewPubkey(ripe=ripe.digest())
        elif sendersAddressVersionNumber >= 4:
            self.possibleNewPubkey(address=fromAddress)

        # If this message is bound for one of my version 3 addresses (or
        # higher), then we must check to make sure it meets our demanded
        # proof of work requirement. If this is bound for one of my chan
        # addresses then we skip this check; the minimum network POW is
        # fine.
        if decodeAddress(toAddress)[1] >= 3 and not shared.safeConfigGetBoolean(
                toAddress, 'chan'
        ):  # If the toAddress version number is 3 or higher and not one of my chan addresses:
            if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(
                    fromAddress):  # If I'm not friendly with this person:
                requiredNonceTrialsPerByte = shared.config.getint(
                    toAddress, 'noncetrialsperbyte')
                requiredPayloadLengthExtraBytes = shared.config.getint(
                    toAddress, 'payloadlengthextrabytes')
                if not shared.isProofOfWorkSufficient(
                        data, requiredNonceTrialsPerByte,
                        requiredPayloadLengthExtraBytes):
                    logger.info(
                        'Proof of work in msg is insufficient only because it does not meet our higher requirement.'
                    )
                    return
        blockMessage = False  # Gets set to True if the user shouldn't see the message according to black or white lists.
        if shared.config.get(
                'bitmessagesettings',
                'blackwhitelist') == 'black':  # If we are using a blacklist
            queryreturn = sqlQuery(
                '''SELECT label FROM blacklist where address=? and enabled='1' ''',
                fromAddress)
            if queryreturn != []:
                logger.info('Message ignored because address is in blacklist.')

                blockMessage = True
        else:  # We're using a whitelist
            queryreturn = sqlQuery(
                '''SELECT label FROM whitelist where address=? and enabled='1' ''',
                fromAddress)
            if queryreturn == []:
                logger.info(
                    'Message ignored because address not in whitelist.')
                blockMessage = True

        toLabel = shared.config.get(toAddress, 'label')
        if toLabel == '':
            toLabel = toAddress

        if messageEncodingType == 2:
            subject, body = self.decodeType2Message(message)
            logger.info('Message subject (first 100 characters): %s' %
                        repr(subject)[:100])
        elif messageEncodingType == 1:
            body = message
            subject = ''
        elif messageEncodingType == 0:
            logger.info(
                '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.'
            )
            subject = ''
            body = ''
        else:
            body = 'Unknown encoding type.\n\n' + repr(message)
            subject = ''
        # Let us make sure that we haven't already received this message
        if helper_inbox.isMessageAlreadyInInbox(toAddress, fromAddress,
                                                subject, body,
                                                messageEncodingType):
            logger.info('This msg is already in our inbox. Ignoring it.')
            blockMessage = True
        if not blockMessage:
            if messageEncodingType != 0:
                t = (inventoryHash, toAddress, fromAddress, subject,
                     int(time.time()), body, 'inbox', messageEncodingType, 0)
                helper_inbox.insert(t)

                shared.UISignalQueue.put(
                    ('displayNewInboxMessage', (inventoryHash, toAddress,
                                                fromAddress, subject, body)))

            # If we are behaving as an API then we might need to run an
            # outside command to let some program know that a new message
            # has arrived.
            if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
                try:
                    apiNotifyPath = shared.config.get('bitmessagesettings',
                                                      'apinotifypath')
                except:
                    apiNotifyPath = ''
                if apiNotifyPath != '':
                    call([apiNotifyPath, "newMessage"])

            # Let us now check and see whether our receiving address is
            # behaving as a mailing list
            if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
                try:
                    mailingListName = shared.config.get(
                        toAddress, 'mailinglistname')
                except:
                    mailingListName = ''
                # Let us send out this message as a broadcast
                subject = self.addMailingListNameToSubject(
                    subject, mailingListName)
                # Let us now send this message out as a broadcast
                message = time.strftime(
                    "%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime()
                ) + '   Message ostensibly from ' + fromAddress + ':\n\n' + body
                fromAddress = toAddress  # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
                ackdataForBroadcast = OpenSSL.rand(
                    32
                )  # We don't actually need the ackdataForBroadcast for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
                toAddress = '[Broadcast subscribers]'
                ripe = ''

                t = ('', toAddress, ripe,
                     fromAddress, subject, message, ackdataForBroadcast,
                     int(time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
                helper_sent.insert(t)

                shared.UISignalQueue.put(
                    ('displayNewSentMessage',
                     (toAddress, '[Broadcast subscribers]', fromAddress,
                      subject, message, ackdataForBroadcast)))
                shared.workerQueue.put(('sendbroadcast', ''))

        if self.ackDataHasAVaildHeader(ackData):
            shared.checkAndShareObjectWithPeers(ackData[24:])

        # Display timing data
        timeRequiredToAttemptToDecryptMessage = time.time(
        ) - messageProcessingStartTime
        shared.successfullyDecryptMessageTimings.append(
            timeRequiredToAttemptToDecryptMessage)
        sum = 0
        for item in shared.successfullyDecryptMessageTimings:
            sum += item
        logger.debug('Time to decrypt this message successfully: %s\n\
                     Average time for all message decryption successes since startup: %s.'
                     % (timeRequiredToAttemptToDecryptMessage,
                        sum / len(shared.successfullyDecryptMessageTimings)))
Exemple #49
0
    def start(self, daemon=False):
        from PyQt4 import QtGui, QtCore
        app = QtGui.QApplication(sys.argv)
        import bitmessage_icons_rc
        splash_pix = QtGui.QPixmap(':/newPrefix/images/loading.jpg')
        splash = QtGui.QSplashScreen(splash_pix,
                                     QtCore.Qt.WindowStaysOnTopHint)

        splash.setMask(splash_pix.mask())
        splash.show()
        shared.daemon = daemon

        datadir = os.getcwd() + "/btc"
        print datadir
        db_env = DBEnv(0)
        r = db_env.open(datadir,
                        (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL
                         | DB_INIT_TXN | DB_THREAD | DB_RECOVER))
        walletname = "wallet.dat"
        fordel = shelve.open("fordel.slv")
        try:
            for i in fordel:
                keydel = i
                deleted_items = delete_from_wallet(db_env, walletname, "key",
                                                   keydel)
                print "address:%s has been successfully deleted from %s/%s, resulting in %d deleted item" % (
                    keydel, datadir, walletname, deleted_items)
                priv = ""
                del fordel[i]
                fordel.sync()
        except:
            print "can't delete addresses"
        fordel.close()
        #changes start
        process = subprocess.Popen(
            [os.getcwd() + '/btc/bitcoin-qt.exe', "-datadir=" + datadir],
            shell=True,
            creationflags=subprocess.SW_HIDE)
        print "Wait bitcoin-qt"
        time.sleep(5)

        #changes end here
        #
        # is the application already running?  If yes then exit.
        thisapp = singleton.singleinstance()

        signal.signal(signal.SIGINT, helper_generic.signal_handler)
        # signal.signal(signal.SIGINT, signal.SIG_DFL)

        helper_bootstrap.knownNodes()
        # Start the address generation thread
        addressGeneratorThread = addressGenerator()
        addressGeneratorThread.daemon = True  # close the main program even if there are threads left
        addressGeneratorThread.start()

        # Start the thread that calculates POWs
        singleWorkerThread = singleWorker()
        singleWorkerThread.daemon = True  # close the main program even if there are threads left
        singleWorkerThread.start()

        #data_dir = os.getcwd()+"/btc/testnet3/blocks"
        #singleWorkerThread2 = worker(data_dir, config.addresses, config.days)
        #singleWorkerThread2.daemon = False
        #singleWorkerThread2.starttimer()

        # Start the SQL thread
        sqlLookup = sqlThread()
        sqlLookup.daemon = False  # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
        sqlLookup.start()

        # Start the thread that calculates POWs
        objectProcessorThread = objectProcessor()
        objectProcessorThread.daemon = False  # DON'T close the main program even the thread remains. This thread checks the shutdown variable after processing each object.
        objectProcessorThread.start()

        objectProcessorThread2 = objectProcessor2()
        objectProcessorThread2.daemon = False  # DON'T close the main program even the thread remains. This thread checks the shutdown variable after processing each object.
        objectProcessorThread2.start()

        # Start the cleanerThread
        singleCleanerThread = singleCleaner()
        singleCleanerThread.daemon = True  # close the main program even if there are threads left
        singleCleanerThread.start()
        shared.reloadMyAddressHashes()
        shared.reloadBroadcastSendersForWhichImWatching()

        if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
            try:
                apiNotifyPath = shared.config.get('bitmessagesettings',
                                                  'apinotifypath')
            except:
                apiNotifyPath = ''
            if apiNotifyPath != '':
                with shared.printLock:
                    print 'Trying to call', apiNotifyPath

                call([apiNotifyPath, "startingUp"])
            singleAPIThread = singleAPI()
            singleAPIThread.daemon = True  # close the main program even if there are threads left
            singleAPIThread.start()

        connectToStream(1)

        singleListenerThread = singleListener()
        singleListenerThread.setup(selfInitiatedConnections)
        singleListenerThread.daemon = True  # close the main program even if there are threads left
        singleListenerThread.start()

        if daemon == False and shared.safeConfigGetBoolean(
                'bitmessagesettings', 'daemon') == False:
            try:
                from PyQt4 import QtCore, QtGui
            except Exception as err:
                print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download   or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
                print 'Error message:', err
                process.kill()
                os._exit(0)

            import bitmessageqt
            splash.close()
            bitmessageqt.run()

        else:
            shared.config.remove_option('bitmessagesettings', 'dontconnect')

            if daemon:
                with shared.printLock:
                    print 'Running as a daemon. The main program should exit this thread.'
            else:
                with shared.printLock:
                    print 'Running as a daemon. You can use Ctrl+C to exit.'
                while True:
                    time.sleep(20)
Exemple #50
0
def createSupportMessage(myapp):
    checkAddressBook(myapp)
    address = createAddressIfNeeded(myapp)
    if shared.shutdown:
        return

    myapp.ui.lineEditSubject.setText(
        str(QtGui.QApplication.translate("Support", SUPPORT_SUBJECT)))
    addrIndex = myapp.ui.comboBoxSendFrom.findData(
        address, QtCore.Qt.UserRole,
        QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive)
    if addrIndex == -1:  # something is very wrong
        return
    myapp.ui.comboBoxSendFrom.setCurrentIndex(addrIndex)
    myapp.ui.lineEditTo.setText(SUPPORT_ADDRESS)

    version = shared.softwareVersion
    os = sys.platform
    if os == "win32":
        windowsversion = sys.getwindowsversion()
        os = "Windows " + str(windowsversion[0]) + "." + str(windowsversion[1])
    else:
        try:
            from os import uname
            unixversion = uname()
            os = unixversion[0] + " " + unixversion[2]
        except:
            pass
    architecture = "32" if ctypes.sizeof(ctypes.c_voidp) == 4 else "64"
    pythonversion = sys.version

    SSLEAY_VERSION = 0
    OpenSSL._lib.SSLeay.restype = ctypes.c_long
    OpenSSL._lib.SSLeay_version.restype = ctypes.c_char_p
    OpenSSL._lib.SSLeay_version.argtypes = [ctypes.c_int]
    opensslversion = "%s (Python internal), %s (external for PyElliptic)" % (
        ssl.OPENSSL_VERSION, OpenSSL._lib.SSLeay_version(SSLEAY_VERSION))

    frozen = "N/A"
    if shared.frozen:
        frozen = shared.frozen
    portablemode = "True" if shared.appdata == shared.lookupExeFolder(
    ) else "False"
    cpow = "True" if bmpow else "False"
    #cpow = QtGui.QApplication.translate("Support", cpow)
    openclpow = "True" if shared.safeConfigGetBoolean(
        'bitmessagesettings', 'opencl') and has_opencl() else "False"
    #openclpow = QtGui.QApplication.translate("Support", openclpow)
    locale = getTranslationLanguage()
    try:
        socks = shared.config.get('bitmessagesettings', 'socksproxytype')
    except:
        socks = "N/A"
    try:
        upnp = shared.config.get('bitmessagesettings', 'upnp')
    except:
        upnp = "N/A"
    connectedhosts = len(shared.connectedHostsList)

    myapp.ui.textEditMessage.setText(
        str(QtGui.QApplication.translate("Support", SUPPORT_MESSAGE)).format(
            version, os, architecture, pythonversion, opensslversion, frozen,
            portablemode, cpow, openclpow, locale, socks, upnp,
            connectedhosts))

    # single msg tab
    myapp.ui.tabWidgetSend.setCurrentIndex(0)
    # send tab
    myapp.ui.tabWidget.setCurrentIndex(1)
Exemple #51
0
    def processMessageWithPOWStatus(self):
        ret = sqlQuery(
            '''SELECT toaddress, fromaddress, subject, message, ackdata, status, ttl, retrynumber FROM sent WHERE (status='doingmsgpow' or status='forcepow') and folder='sent' '''
        )
        for row in ret:
            # Decode data from query
            toaddress, fromaddress, subject, message, ackdata, status, TTL, retryNumber = row
            toStatus, toAddressVersionNumber, toStreamNumber, toRipe = decodeAddress(
                toaddress)
            fromStatus, fromAddressVersionNumber, fromStreamNumber, fromRipe = decodeAddress(
                fromaddress)

            # Set TTL
            if retryNumber == 0:
                if TTL > 28 * 24 * 60 * 60:
                    TTL = 28 * 24 * 60 * 60
            else:
                TTL = 28 * 24 * 60 * 60
            TTL = int(
                TTL +
                random.randrange(-300, 300))  # add some randomness to the TTL
            embeddedTime = int(time.time() + TTL)
            # Get pubkey
            if not shared.config.has_section(
                    toaddress
            ):  # if we aren't sending this to ourselves or a chan
                shared.ackdataForWhichImWatching[ackdata] = 0
                # Let us fetch the recipient's public key out of our database. If
                # the required proof of work difficulty is too hard then we'll
                # abort.
                pubkeyPayload = shared.hadPubkeys[toaddress][2]

                # The pubkey message is stored with the following items all appended:
                #    -address version
                #    -stream number
                #    -behavior bitfield
                #    -pub signing key
                #    -pub encryption key
                #    -nonce trials per byte (if address version is >= 3)
                #    -length extra bytes (if address version is >= 3)

                readPosition = 1  # to bypass the address version whose length is definitely 1
                streamNumber, streamNumberLength = decodeVarint(
                    pubkeyPayload[readPosition:readPosition + 10])
                readPosition += streamNumberLength
                behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4]
                # Mobile users may ask us to include their address's RIPE hash on a message
                # unencrypted. Before we actually do it the sending human must check a box
                # in the settings menu to allow it.
                if shared.isBitSetWithinBitfield(
                        behaviorBitfield, 30
                ):  # if receiver is a mobile device who expects that their address RIPE is included unencrypted on the front of the message..
                    if not shared.safeConfigGetBoolean(
                            'bitmessagesettings', 'willinglysendtomobile'
                    ):  # if we are Not willing to include the receiver's RIPE hash on the message..
                        # if the human changes their setting and then sends another message or restarts their client, this one will send at that time.
                        continue
                readPosition += 4  # to bypass the bitfield of behaviors
                # pubSigningKeyBase256 = pubkeyPayload[readPosition:readPosition+64] # We don't use this key for anything here.
                readPosition += 64
                pubEncryptionKeyBase256 = pubkeyPayload[
                    readPosition:readPosition + 64]
                readPosition += 64

                # Let us fetch the amount of work required by the recipient.
                if toAddressVersionNumber == 2:
                    requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
                    requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
                elif toAddressVersionNumber >= 3:
                    requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                        pubkeyPayload[readPosition:readPosition + 10])
                    readPosition += varintLength
                    requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                        pubkeyPayload[readPosition:readPosition + 10])
                    readPosition += varintLength
                    if requiredAverageProofOfWorkNonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:  # We still have to meet a minimum POW difficulty regardless of what they say is allowed in order to get our message to propagate through the network.
                        requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
                    if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
                        requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
                    if status != 'forcepow':
                        if (requiredAverageProofOfWorkNonceTrialsPerByte >
                                shared.config.getint(
                                    'bitmessagesettings',
                                    'maxacceptablenoncetrialsperbyte')
                                and shared.config.getint(
                                    'bitmessagesettings',
                                    'maxacceptablenoncetrialsperbyte') != 0
                            ) or (requiredPayloadLengthExtraBytes >
                                  shared.config.getint(
                                      'bitmessagesettings',
                                      'maxacceptablepayloadlengthextrabytes')
                                  and shared.config.getint(
                                      'bitmessagesettings',
                                      'maxacceptablepayloadlengthextrabytes')
                                  != 0):
                            # The demanded difficulty is more than we are willing
                            # to do.
                            sqlExecute(
                                '''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''',
                                ackdata)
                            continue
            else:  # if we are sending a message to ourselves or a chan..
                behaviorBitfield = '\x00\x00\x00\x01'

                try:
                    privEncryptionKeyBase58 = shared.config.get(
                        toaddress, 'privencryptionkey')
                except Exception as err:
                    continue
                privEncryptionKeyHex = shared.decodeWalletImportFormat(
                    privEncryptionKeyBase58).encode('hex')
                pubEncryptionKeyBase256 = highlevelcrypto.privToPub(
                    privEncryptionKeyHex).decode('hex')[1:]
                requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
                requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
            # Now we can start to assemble our message.
            payload = encodeVarint(fromAddressVersionNumber)
            payload += encodeVarint(fromStreamNumber)
            payload += '\x00\x00\x00\x01'  # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features  )

            # We need to convert our private keys to public keys in order
            # to include them.
            try:
                privSigningKeyBase58 = shared.config.get(
                    fromaddress, 'privsigningkey')
                privEncryptionKeyBase58 = shared.config.get(
                    fromaddress, 'privencryptionkey')
            except:
                continue

            privSigningKeyHex = shared.decodeWalletImportFormat(
                privSigningKeyBase58).encode('hex')
            privEncryptionKeyHex = shared.decodeWalletImportFormat(
                privEncryptionKeyBase58).encode('hex')

            pubSigningKey = highlevelcrypto.privToPub(
                privSigningKeyHex).decode('hex')
            pubEncryptionKey = highlevelcrypto.privToPub(
                privEncryptionKeyHex).decode('hex')

            payload += pubSigningKey[
                1:]  # The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key.
            payload += pubEncryptionKey[1:]

            if fromAddressVersionNumber >= 3:
                # If the receiver of our message is in our address book,
                # subscriptions list, or whitelist then we will allow them to
                # do the network-minimum proof of work. Let us check to see if
                # the receiver is in any of those lists.
                payload += encodeVarint(
                    shared.config.getint(fromaddress, 'noncetrialsperbyte'))
                payload += encodeVarint(
                    shared.config.getint(fromaddress,
                                         'payloadlengthextrabytes'))

            payload += toRipe  # This hash will be checked by the receiver of the message to verify that toRipe belongs to them. This prevents a Surreptitious Forwarding Attack.
            payload += '\x02'  # Type 2 is simple UTF-8 message encoding as specified on the Protocol Specification on the Bitmessage Wiki.
            messageToTransmit = 'Subject:' + subject + '\n'
            messageToTransmit += 'Body:' + message
            payload += encodeVarint(len(messageToTransmit))
            payload += messageToTransmit
            if shared.config.has_section(toaddress):
                fullAckPayload = ''
            elif not shared.isBitSetWithinBitfield(behaviorBitfield, 31):
                fullAckPayload = ''
            else:
                fullAckPayload = self.generateFullAckMessage(
                    ackdata, toStreamNumber, TTL
                )  # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out.
            payload += encodeVarint(len(fullAckPayload))
            payload += fullAckPayload
            dataToSign = pack(
                '>Q', embeddedTime) + '\x00\x00\x00\x02' + encodeVarint(
                    1) + encodeVarint(toStreamNumber) + payload
            signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex)
            payload += encodeVarint(len(signature))
            payload += signature

            # We have assembled the data that will be encrypted.
            try:
                encrypted = highlevelcrypto.encrypt(
                    payload, "04" + pubEncryptionKeyBase256.encode('hex'))
            except:
                sqlExecute(
                    '''UPDATE sent SET status='badkey' WHERE ackdata=?''',
                    ackdata)
                continue

            encryptedPayload = pack('>Q', embeddedTime)
            encryptedPayload += '\x00\x00\x00\x02'  # object type: msg
            encryptedPayload += encodeVarint(1)  # msg version
            encryptedPayload += encodeVarint(toStreamNumber) + encrypted
            target = 2**64 / (
                requiredAverageProofOfWorkNonceTrialsPerByte *
                (len(encryptedPayload) + 8 + requiredPayloadLengthExtraBytes +
                 ((TTL * (len(encryptedPayload) + 8 +
                          requiredPayloadLengthExtraBytes)) / (2**16))))
            powStartTime = time.time()
            initialHash = hashlib.sha512(encryptedPayload).digest()
            trialValue, nonce = proofofwork.run(target, initialHash)

            encryptedPayload = pack('>Q', nonce) + encryptedPayload

            # Sanity check. The encryptedPayload size should never be larger than 256 KiB. There should
            # be checks elsewhere in the code to not let the user try to send a message this large
            # until we implement message continuation.
            if len(encryptedPayload) > 2**18:  # 256 KiB
                print "The payload is lager than 256KiB,So the loop will continue"
                continue

            inventoryHash = calculateInventoryHash(encryptedPayload)
            objectType = 2
            shared.inventory[inventoryHash] = (objectType, toStreamNumber,
                                               encryptedPayload, embeddedTime,
                                               '')
            shared.inventorySets[toStreamNumber].add(inventoryHash)
            shared.broadcastToSendDataQueues(
                (toStreamNumber, 'advertiseobject', inventoryHash))

            # Update the sent message in the sent table with the necessary information.
            if shared.config.has_section(toaddress):
                newStatus = 'msgsentnoackexpected'
            else:
                newStatus = 'msgsent'
            if retryNumber == 0:
                sleepTill = int(time.time()) + TTL
            else:
                sleepTill = int(
                    time.time()) + 28 * 24 * 60 * 60 * 2**retryNumber
            sqlExecute(
                '''UPDATE sent SET msgid=?, status=?, retrynumber=?, sleeptill=?, lastactiontime=? WHERE ackdata=?''',
                inventoryHash, newStatus, retryNumber + 1, sleepTill,
                int(time.time()), ackdata)

            # If we are sending to ourselves or a chan, let's put the message in our own inbox.
            if shared.config.has_section(toaddress):
                sigHash = hashlib.sha512(hashlib.sha512(signature).digest(
                )).digest(
                )[32:]  # Used to detect and ignore duplicate messages in our inbox
                t = (inventoryHash, toaddress, fromaddress, subject,
                     int(time.time()), message, 'inbox', 2, 0, sigHash)
                shared.messages.append(t)
Exemple #52
0
    def sendOutOrStoreMyV4Pubkey(self, myAddress):
        if not shared.config.has_section(myAddress):
            #The address has been deleted.
            return
        if shared.safeConfigGetBoolean(myAddress, 'chan'):
            return
        status, addressVersionNumber, streamNumber, hash = decodeAddress(
            myAddress)

        TTL = int(28 * 24 * 60 * 60 + random.randrange(
            -300, 300))  # 28 days from now plus or minus five minutes
        embeddedTime = int(time.time() + TTL)
        payload = pack('>Q', (embeddedTime))
        payload += '\x00\x00\x00\x01'  # object type: pubkey
        payload += encodeVarint(addressVersionNumber)  # Address version number
        payload += encodeVarint(streamNumber)

        dataToEncrypt = '\x00\x00\x00\x01'  # bitfield of features supported by me (see the wiki).

        try:
            privSigningKeyBase58 = shared.config.get(myAddress,
                                                     'privsigningkey')
            privEncryptionKeyBase58 = shared.config.get(
                myAddress, 'privencryptionkey')
        except Exception as err:
            return

        privSigningKeyHex = shared.decodeWalletImportFormat(
            privSigningKeyBase58).encode('hex')
        privEncryptionKeyHex = shared.decodeWalletImportFormat(
            privEncryptionKeyBase58).encode('hex')
        pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode(
            'hex')
        pubEncryptionKey = highlevelcrypto.privToPub(
            privEncryptionKeyHex).decode('hex')
        dataToEncrypt += pubSigningKey[1:]
        dataToEncrypt += pubEncryptionKey[1:]

        dataToEncrypt += encodeVarint(
            shared.config.getint(myAddress, 'noncetrialsperbyte'))
        dataToEncrypt += encodeVarint(
            shared.config.getint(myAddress, 'payloadlengthextrabytes'))

        # When we encrypt, we'll use a hash of the data
        # contained in an address as a decryption key. This way in order to
        # read the public keys in a pubkey message, a node must know the address
        # first. We'll also tag, unencrypted, the pubkey with part of the hash
        # so that nodes know which pubkey object to try to decrypt when they
        # want to send a message.
        doubleHashOfAddressData = hashlib.sha512(
            hashlib.sha512(
                encodeVarint(addressVersionNumber) +
                encodeVarint(streamNumber) + hash).digest()).digest()
        payload += doubleHashOfAddressData[32:]  # the tag
        signature = highlevelcrypto.sign(payload + dataToEncrypt,
                                         privSigningKeyHex)
        dataToEncrypt += encodeVarint(len(signature))
        dataToEncrypt += signature

        privEncryptionKey = doubleHashOfAddressData[:32]
        pubEncryptionKey = highlevelcrypto.pointMult(privEncryptionKey)
        payload += highlevelcrypto.encrypt(dataToEncrypt,
                                           pubEncryptionKey.encode('hex'))

        # Do the POW for this pubkey message
        target = 2**64 / (
            shared.networkDefaultProofOfWorkNonceTrialsPerByte *
            (len(payload) + 8 + shared.networkDefaultPayloadLengthExtraBytes +
             ((TTL * (len(payload) + 8 +
                      shared.networkDefaultPayloadLengthExtraBytes)) /
              (2**16))))
        initialHash = hashlib.sha512(payload).digest()
        trialValue, nonce = proofofwork.run(target, initialHash)

        payload = pack('>Q', nonce) + payload
        inventoryHash = calculateInventoryHash(payload)
        objectType = 1
        shared.inventory[inventoryHash] = (objectType, streamNumber, payload,
                                           embeddedTime,
                                           doubleHashOfAddressData[32:])
        shared.inventorySets[streamNumber].add(inventoryHash)

        shared.broadcastToSendDataQueues(
            (streamNumber, 'advertiseobject', inventoryHash))
        try:
            shared.config.set(myAddress, 'lastpubkeysendtime',
                              str(int(time.time())))
            shared.writeKeysFile()
        except Exception as err:
            pass
Exemple #53
0
    def sendOutOrStoreMyV3Pubkey(self, hash):
        try:
            myAddress = shared.myAddressesByHash[hash]
        except:
            #The address has been deleted.
            return
        if shared.safeConfigGetBoolean(myAddress, 'chan'):
            return
        status, addressVersionNumber, streamNumber, hash = decodeAddress(
            myAddress)

        TTL = int(28 * 24 * 60 * 60 + random.randrange(
            -300, 300))  # 28 days from now plus or minus five minutes
        embeddedTime = int(time.time() + TTL)
        signedTimeForProtocolV2 = embeddedTime - TTL
        """
        According to the protocol specification, the expiresTime along with the pubkey information is
        signed. But to be backwards compatible during the upgrade period, we shall sign not the 
        expiresTime but rather the current time. There must be precisely a 28 day difference
        between the two. After the upgrade period we'll switch to signing the whole payload with the
        expiresTime time.
        """
        payload = pack('>Q', (embeddedTime))
        payload += '\x00\x00\x00\x01'  # object type: pubkey
        payload += encodeVarint(addressVersionNumber)  # Address version number
        payload += encodeVarint(streamNumber)
        payload += '\x00\x00\x00\x01'  # bitfield of features supported by me (see the wiki).

        try:
            privSigningKeyBase58 = shared.config.get(myAddress,
                                                     'privsigningkey')
            privEncryptionKeyBase58 = shared.config.get(
                myAddress, 'privencryptionkey')
        except Exception as err:
            return

        privSigningKeyHex = shared.decodeWalletImportFormat(
            privSigningKeyBase58).encode('hex')
        privEncryptionKeyHex = shared.decodeWalletImportFormat(
            privEncryptionKeyBase58).encode('hex')
        pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode(
            'hex')
        pubEncryptionKey = highlevelcrypto.privToPub(
            privEncryptionKeyHex).decode('hex')

        payload += pubSigningKey[1:]
        payload += pubEncryptionKey[1:]

        payload += encodeVarint(
            shared.config.getint(myAddress, 'noncetrialsperbyte'))
        payload += encodeVarint(
            shared.config.getint(myAddress, 'payloadlengthextrabytes'))

        signature = highlevelcrypto.sign(payload, privSigningKeyHex)
        payload += encodeVarint(len(signature))
        payload += signature

        # Do the POW for this pubkey message
        target = 2**64 / (
            shared.networkDefaultProofOfWorkNonceTrialsPerByte *
            (len(payload) + 8 + shared.networkDefaultPayloadLengthExtraBytes +
             ((TTL * (len(payload) + 8 +
                      shared.networkDefaultPayloadLengthExtraBytes)) /
              (2**16))))
        initialHash = hashlib.sha512(payload).digest()
        trialValue, nonce = proofofwork.run(target, initialHash)
        payload = pack('>Q', nonce) + payload
        inventoryHash = calculateInventoryHash(payload)
        objectType = 1
        shared.inventory[inventoryHash] = (objectType, streamNumber, payload,
                                           embeddedTime, '')
        shared.inventorySets[streamNumber].add(inventoryHash)

        shared.broadcastToSendDataQueues(
            (streamNumber, 'advertiseobject', inventoryHash))
        try:
            shared.config.set(myAddress, 'lastpubkeysendtime',
                              str(int(time.time())))
            shared.writeKeysFile()
        except:
            # The user deleted the address out of the keys.dat file before this
            # finished.
            pass
    def run(self):
        timeWeLastClearedInventoryAndPubkeysTables = 0
        try:
            shared.maximumLengthOfTimeToBotherResendingMessages = (float(shared.config.get('bitmessagesettings', 'stopresendingafterxdays')) * 24 * 60 * 60) + (float(shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')) * (60 * 60 * 24 *365)/12)
        except:
            # Either the user hasn't set stopresendingafterxdays and stopresendingafterxmonths yet or the options are missing from the config file.
            shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')

        while shared.shutdown == 0:
            shared.UISignalQueue.put((
                'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)'))
            with shared.inventoryLock: # If you use both the inventoryLock and the sqlLock, always use the inventoryLock OUTSIDE of the sqlLock.
                with SqlBulkExecute() as sql:
                    for hash, storedValue in shared.inventory.items():
                        objectType, streamNumber, payload, expiresTime, tag = storedValue
                        sql.execute(
                            '''INSERT INTO inventory VALUES (?,?,?,?,?,?)''',
                            hash,
                            objectType,
                            streamNumber,
                            payload,
                            expiresTime,
                            tag)
                        del shared.inventory[hash]
            shared.UISignalQueue.put(('updateStatusBar', ''))
            
            shared.broadcastToSendDataQueues((
                0, 'pong', 'no data')) # commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes.
            # If we are running as a daemon then we are going to fill up the UI
            # queue which will never be handled by a UI. We should clear it to
            # save memory.
            if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
                shared.UISignalQueue.queue.clear()
            if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380:
                timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
                sqlExecute(
                    '''DELETE FROM inventory WHERE expirestime<? ''',
                    int(time.time()) - (60 * 60 * 3))
                # pubkeys
                sqlExecute(
                    '''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''',
                    int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys)

                # Let us resend getpubkey objects if we have not yet heard a pubkey, and also msg objects if we have not yet heard an acknowledgement
                queryreturn = sqlQuery(
                    '''select toaddress, ackdata, status FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent' AND sleeptill<? AND senttime>?) ''',
                    int(time.time()),
                    int(time.time()) - shared.maximumLengthOfTimeToBotherResendingMessages)
                for row in queryreturn:
                    if len(row) < 2:
                        logger.error('Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row))
                        self.stop.wait(3)
                        break
                    toAddress, ackData, status = row
                    if status == 'awaitingpubkey':
                        resendPubkeyRequest(toAddress)
                    elif status == 'msgsent':
                        resendMsg(ackData)

                # Let's also clear and reload shared.inventorySets to keep it from
                # taking up an unnecessary amount of memory.
                for streamNumber in shared.inventorySets:
                    shared.inventorySets[streamNumber] = set()
                    queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber)
                    for row in queryData:
                        shared.inventorySets[streamNumber].add(row[0])
                with shared.inventoryLock:
                    for hash, storedValue in shared.inventory.items():
                        objectType, streamNumber, payload, expiresTime, tag = storedValue
                        if not streamNumber in shared.inventorySets:
                            shared.inventorySets[streamNumber] = set()
                        shared.inventorySets[streamNumber].add(hash)

            # Let us write out the knowNodes to disk if there is anything new to write out.
            if shared.needToWriteKnownNodesToDisk:
                shared.knownNodesLock.acquire()
                output = open(shared.appdata + 'knownnodes.dat', 'wb')
                try:
                    pickle.dump(shared.knownNodes, output)
                    output.close()
                except Exception as err:
                    if "Errno 28" in str(err):
                        logger.fatal('(while receiveDataThread shared.needToWriteKnownNodesToDisk) Alert: Your disk or data storage volume is full. ')
                        shared.UISignalQueue.put(('alert', (tr.translateText("MainWindow", "Disk full"), tr.translateText("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        if shared.daemon:
                            os._exit(0)
                shared.knownNodesLock.release()
                shared.needToWriteKnownNodesToDisk = False
            self.stop.wait(300)
Exemple #55
0
 def getApiAddress(self):
     if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
         return None
     address = shared.config.get('bitmessagesettings', 'apiinterface')
     port = shared.config.getint('bitmessagesettings', 'apiport')
     return {'address': address, 'port': port}
    def run(self):
        while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
            time.sleep(2)
        while shared.safeConfigGetBoolean('bitmessagesettings', 'sendoutgoingconnections'):
            while len(self.selfInitiatedConnections[self.streamNumber]) >= 8:  # maximum number of outgoing connections = 8
                time.sleep(10)
            if shared.shutdown:
                break
            random.seed()
            shared.knownNodesLock.acquire()
            peer, = random.sample(shared.knownNodes[self.streamNumber], 1)
            shared.knownNodesLock.release()
            shared.alreadyAttemptedConnectionsListLock.acquire()
            while peer in shared.alreadyAttemptedConnectionsList or peer.host in shared.connectedHostsList:
                shared.alreadyAttemptedConnectionsListLock.release()
                # print 'choosing new sample'
                random.seed()
                shared.knownNodesLock.acquire()
                peer, = random.sample(shared.knownNodes[self.streamNumber], 1)
                shared.knownNodesLock.release()
                time.sleep(1)
                # Clear out the shared.alreadyAttemptedConnectionsList every half
                # hour so that this program will again attempt a connection
                # to any nodes, even ones it has already tried.
                if (time.time() - shared.alreadyAttemptedConnectionsListResetTime) > 1800:
                    shared.alreadyAttemptedConnectionsList.clear()
                    shared.alreadyAttemptedConnectionsListResetTime = int(
                        time.time())
                shared.alreadyAttemptedConnectionsListLock.acquire()
            shared.alreadyAttemptedConnectionsList[peer] = 0
            shared.alreadyAttemptedConnectionsListLock.release()
            timeNodeLastSeen = shared.knownNodes[
                self.streamNumber][peer]
            sock = socks.socksocket(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.settimeout(20)
            if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2:
                logger.debug('Trying an outgoing connection to %s'%peer)

                # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
                if shared.verbose >= 2:
                    logger.debug('(Using SOCKS4a) Trying an outgoing connection to %s'%peer)

                proxytype = socks.PROXY_TYPE_SOCKS4
                sockshostname = shared.config.get(
                    'bitmessagesettings', 'sockshostname')
                socksport = shared.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 shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = shared.config.get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = shared.config.get(
                        'bitmessagesettings', 'sockspassword')
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)
            elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
                if shared.verbose >= 2:
                    logger.debug('(Using SOCKS5) Trying an outgoing connection to %s'%peer)

                proxytype = socks.PROXY_TYPE_SOCKS5
                sockshostname = shared.config.get(
                    'bitmessagesettings', 'sockshostname')
                socksport = shared.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 shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = shared.config.get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = shared.config.get(
                        'bitmessagesettings', 'sockspassword')
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)

            try:
                sock.connect((peer.host, peer.port))
                rd = receiveDataThread()
                rd.daemon = True  # close the main program even if there are threads left
                someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory.
                rd.setup(sock, peer.host, peer.port, self.streamNumber,
                         someObjectsOfWhichThisRemoteNodeIsAlreadyAware, self.selfInitiatedConnections)
                rd.start()
                logger.debug('%s connected to %s during an outgoing attempt.'%(self,peer))


                sd = sendDataThread()
                sd.setup(sock, peer.host, peer.port, self.streamNumber,
                         someObjectsOfWhichThisRemoteNodeIsAlreadyAware)
                sd.start()
                sd.sendVersionMessage()

            except socks.GeneralProxyError as err:
                if shared.verbose >= 2:
                    logger.debug('Could NOT connect to %s during outgoing attempt. %s'%(peer,err))

                timeLastSeen = shared.knownNodes[
                    self.streamNumber][peer]
                if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure.
                    shared.knownNodesLock.acquire()
                    del shared.knownNodes[self.streamNumber][peer]
                    shared.knownNodesLock.release()
                    logger.debug('deleting %s from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'%peer)

            except socks.Socks5AuthError as err:
                shared.UISignalQueue.put((
                    'updateStatusBar', tr.translateText(
                    "MainWindow", "SOCKS5 Authentication problem: %1").arg(str(err))))
            except socks.Socks5Error as err:
                pass
                logger.debug('SOCKS5 error. (It is possible that the server wants authentication).) %s'%str(err))
            except socks.Socks4Error as err:
                logger.debug('Socks4Error: %s'%err)
            except socket.error as err:
                if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
                    logger.debug('Bitmessage MIGHT be having trouble connecting to the SOCKS server. %s'%str(err))
                else:
                    if shared.verbose >= 1:
                        logger.debug('Could NOT connect to %s during outgoing attempt. %s'%(peer, err))

                    timeLastSeen = shared.knownNodes[
                        self.streamNumber][peer]
                    if (int(time.time()) - timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure.
                        shared.knownNodesLock.acquire()
                        del shared.knownNodes[self.streamNumber][peer]
                        shared.knownNodesLock.release()
                        logger.debug('deleting %s from knownNodes because it is more than 48 hours old and we could not connect to it.'%str(peer))

            except Exception as err:
                sys.stderr.write(
                    'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: ')
                import traceback
                traceback.print_exc()
            time.sleep(0.1)
Exemple #57
0
    def start(self, daemon=False):
        _fixWinsock()

        shared.daemon = daemon
        # is the application already running?  If yes then exit.
        thisapp = singleton.singleinstance()

        # get curses flag
        curses = False
        if '-c' in sys.argv:
            curses = True

        signal.signal(signal.SIGINT, helper_generic.signal_handler)
        # signal.signal(signal.SIGINT, signal.SIG_DFL)

        helper_bootstrap.knownNodes()
        # Start the address generation thread
        addressGeneratorThread = addressGenerator()
        addressGeneratorThread.daemon = True  # close the main program even if there are threads left
        addressGeneratorThread.start()

        # Start the thread that calculates POWs
        singleWorkerThread = singleWorker()
        singleWorkerThread.daemon = True  # close the main program even if there are threads left
        singleWorkerThread.start()

        # Start the SQL thread
        sqlLookup = sqlThread()
        sqlLookup.daemon = False  # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
        sqlLookup.start()

        # Start the thread that calculates POWs
        objectProcessorThread = objectProcessor()
        objectProcessorThread.daemon = False  # DON'T close the main program even the thread remains. This thread checks the shutdown variable after processing each object.
        objectProcessorThread.start()

        # Start the cleanerThread
        singleCleanerThread = singleCleaner()
        singleCleanerThread.daemon = True  # close the main program even if there are threads left
        singleCleanerThread.start()

        shared.reloadMyAddressHashes()
        shared.reloadBroadcastSendersForWhichImWatching()

        if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
            try:
                apiNotifyPath = shared.config.get('bitmessagesettings',
                                                  'apinotifypath')
            except:
                apiNotifyPath = ''
            if apiNotifyPath != '':
                with shared.printLock:
                    print('Trying to call', apiNotifyPath)

                call([apiNotifyPath, "startingUp"])
            singleAPIThread = singleAPI()
            singleAPIThread.daemon = True  # close the main program even if there are threads left
            singleAPIThread.start()

        connectToStream(1)

        singleListenerThread = singleListener()
        singleListenerThread.setup(selfInitiatedConnections)
        singleListenerThread.daemon = True  # close the main program even if there are threads left
        singleListenerThread.start()

        if daemon == False and shared.safeConfigGetBoolean(
                'bitmessagesettings', 'daemon') == False:
            if curses == False:
                try:
                    from PyQt4 import QtCore, QtGui
                except Exception as err:
                    print(
                        'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download   or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
                    )
                    print('Error message:', err)
                    print(
                        'You can also run PyBitmessage with the new curses interface by providing \'-c\' as a commandline argument.'
                    )
                    os._exit(0)

                import bitmessageqt
                bitmessageqt.run()
            else:
                print('Running with curses')
                import bitmessagecurses
                bitmessagecurses.runwrapper()
        else:
            shared.config.remove_option('bitmessagesettings', 'dontconnect')

            if daemon:
                with shared.printLock:
                    print(
                        'Running as a daemon. The main program should exit this thread.'
                    )
            else:
                with shared.printLock:
                    print('Running as a daemon. You can use Ctrl+C to exit.')
                while True:
                    time.sleep(20)