Ejemplo n.º 1
0
def createSupportMessage(myapp):
    checkAddressBook(myapp)
    address = createAddressIfNeeded(myapp)
    if state.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 = softwareVersion
    commit = paths.lastCommit()
    if commit:
        version += " GIT " + commit

    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
    
    opensslversion = "%s (Python internal), %s (external for PyElliptic)" % (ssl.OPENSSL_VERSION, OpenSSL._version)

    frozen = "N/A"
    if paths.frozen:
        frozen = paths.frozen
    portablemode = "True" if state.appdata == paths.lookupExeFolder() else "False"
    cpow = "True" if bmpow else "False"
    #cpow = QtGui.QApplication.translate("Support", cpow)
    openclpow = str(BMConfigParser().safeGet('bitmessagesettings', 'opencl')) if openclEnabled() else "None"
    #openclpow = QtGui.QApplication.translate("Support", openclpow)
    locale = getTranslationLanguage()
    try:
        socks = BMConfigParser().get('bitmessagesettings', 'socksproxytype')
    except:
        socks = "N/A"
    try:
        upnp = BMConfigParser().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)
Ejemplo n.º 2
0
    def run(self):
        self.conn = sqlite3.connect(state.appdata + 'messages.dat')
        self.conn.text_factory = str
        self.cur = self.conn.cursor()

        self.cur.execute('PRAGMA secure_delete = true')

        try:
            self.cur.execute(
                '''CREATE TABLE inbox (msgid blob, toaddress text, fromaddress text, subject text, received text, message text, folder text, encodingtype int, read bool, sighash blob, UNIQUE(msgid) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, senttime integer, lastactiontime integer, sleeptill integer, status text, retrynumber integer, folder text, encodingtype int, ttl int)''' )
            self.cur.execute(
                '''CREATE TABLE subscriptions (label text, address text, enabled bool)''' )
            self.cur.execute(
                '''CREATE TABLE addressbook (label text, address text)''' )
            self.cur.execute(
                '''CREATE TABLE blacklist (label text, address text, enabled bool)''' )
            self.cur.execute(
                '''CREATE TABLE whitelist (label text, address text, enabled bool)''' )
            self.cur.execute(
                '''CREATE TABLE pubkeys (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''CREATE TABLE inventory (hash blob, objecttype int, streamnumber int, payload blob, expirestime integer, tag blob, UNIQUE(hash) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''')
            self.cur.execute(
                '''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' )
            self.cur.execute( '''INSERT INTO settings VALUES('version','10')''')
            self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', (
                int(time.time()),))
            self.cur.execute(
                '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' )
            self.conn.commit()
            logger.info('Created messages database file')
        except Exception as err:
            if str(err) == 'table inbox already exists':
                logger.debug('Database file already exists.')

            else:
                sys.stderr.write(
                    'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err))
                os._exit(0)

        # If the settings version is equal to 2 or 3 then the
        # sqlThread will modify the pubkeys table and change
        # the settings version to 4.
        settingsversion = BMConfigParser().getint(
            'bitmessagesettings', 'settingsversion')

        # People running earlier versions of PyBitmessage do not have the
        # usedpersonally field in their pubkeys table. Let's add it.
        if settingsversion == 2:
            item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' '''
            parameters = ''
            self.cur.execute(item, parameters)
            self.conn.commit()

            settingsversion = 3

        # People running earlier versions of PyBitmessage do not have the
        # encodingtype field in their inbox and sent tables or the read field
        # in the inbox table. Let's add them.
        if settingsversion == 3:
            item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' '''
            parameters = ''
            self.cur.execute(item, parameters)

            item = '''ALTER TABLE inbox ADD read bool DEFAULT '1' '''
            parameters = ''
            self.cur.execute(item, parameters)

            item = '''ALTER TABLE sent ADD encodingtype int DEFAULT '2' '''
            parameters = ''
            self.cur.execute(item, parameters)
            self.conn.commit()

            settingsversion = 4

        BMConfigParser().set(
            'bitmessagesettings', 'settingsversion', str(settingsversion))
        BMConfigParser().save()

        helper_startup.updateConfig()

        # From now on, let us keep a 'version' embedded in the messages.dat
        # file so that when we make changes to the database, the database
        # version we are on can stay embedded in the messages.dat file. Let us
        # check to see if the settings table exists yet.
        item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';'''
        parameters = ''
        self.cur.execute(item, parameters)
        if self.cur.fetchall() == []:
            # The settings table doesn't exist. We need to make it.
            logger.debug(
                "In messages.dat database, creating new 'settings' table.")
            self.cur.execute(
                '''CREATE TABLE settings (key text, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' )
            self.cur.execute( '''INSERT INTO settings VALUES('version','1')''')
            self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', (
                int(time.time()),))
            logger.debug('In messages.dat database, removing an obsolete field from the pubkeys table.')
            self.cur.execute(
                '''CREATE TEMPORARY TABLE pubkeys_backup(hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE);''')
            self.cur.execute(
                '''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM pubkeys;''')
            self.cur.execute( '''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM pubkeys_backup;''')
            self.cur.execute( '''DROP TABLE pubkeys_backup;''')
            logger.debug('Deleting all pubkeys from inventory. They will be redownloaded and then saved with the correct times.')
            self.cur.execute(
                '''delete from inventory where objecttype = 'pubkey';''')
            logger.debug('replacing Bitmessage announcements mailing list with a new one.')
            self.cur.execute(
                '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' ''')
            self.cur.execute(
                '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''')
            logger.debug('Commiting.')
            self.conn.commit()
            logger.debug('Vacuuming message.dat. You might notice that the file size gets much smaller.')
            self.cur.execute( ''' VACUUM ''')

        # After code refactoring, the possible status values for sent messages
        # have changed.
        self.cur.execute(
            '''update sent set status='doingmsgpow' where status='doingpow'  ''')
        self.cur.execute(
            '''update sent set status='msgsent' where status='sentmessage'  ''')
        self.cur.execute(
            '''update sent set status='doingpubkeypow' where status='findingpubkey'  ''')
        self.cur.execute(
            '''update sent set status='broadcastqueued' where status='broadcastpending'  ''')
        self.conn.commit()

        # Let's get rid of the first20bytesofencryptedmessage field in
        # the inventory table.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        if int(self.cur.fetchall()[0][0]) == 2:
            logger.debug(
                'In messages.dat database, removing an obsolete field from'
                ' the inventory table.')
            self.cur.execute(
                '''CREATE TEMPORARY TABLE inventory_backup(hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, UNIQUE(hash) ON CONFLICT REPLACE);''')
            self.cur.execute(
                '''INSERT INTO inventory_backup SELECT hash, objecttype, streamnumber, payload, receivedtime FROM inventory;''')
            self.cur.execute( '''DROP TABLE inventory''')
            self.cur.execute(
                '''CREATE TABLE inventory (hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, UNIQUE(hash) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''INSERT INTO inventory SELECT hash, objecttype, streamnumber, payload, receivedtime FROM inventory_backup;''')
            self.cur.execute( '''DROP TABLE inventory_backup;''')
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (3,)
            self.cur.execute(item, parameters)

        # Add a new column to the inventory table to store tags.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 1 or currentVersion == 3:
            logger.debug(
                'In messages.dat database, adding tag field to'
                ' the inventory table.')
            item = '''ALTER TABLE inventory ADD tag blob DEFAULT '' '''
            parameters = ''
            self.cur.execute(item, parameters)
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (4,)
            self.cur.execute(item, parameters)

        # Add a new column to the pubkeys table to store the address version.
        # We're going to trash all of our pubkeys and let them be redownloaded.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 4:
            self.cur.execute('''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (hash blob, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(hash, addressversion) ON CONFLICT REPLACE)''')
            self.cur.execute(
                '''delete from inventory where objecttype = 'pubkey';''')
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (5,)
            self.cur.execute(item, parameters)

        # Add a new table: objectprocessorqueue with which to hold objects
        # that have yet to be processed if the user shuts down Bitmessage.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 5:
            self.cur.execute('''DROP TABLE knownnodes''')
            self.cur.execute(
                '''CREATE TABLE objectprocessorqueue (objecttype text, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''')
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (6,)
            self.cur.execute(item, parameters)

        # changes related to protocol v3
        # In table inventory and objectprocessorqueue, objecttype is now
        # an integer (it was a human-friendly string previously)
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 6:
            logger.debug(
                'In messages.dat database, dropping and recreating'
                ' the inventory table.')
            self.cur.execute( '''DROP TABLE inventory''')
            self.cur.execute( '''CREATE TABLE inventory (hash blob, objecttype int, streamnumber int, payload blob, expirestime integer, tag blob, UNIQUE(hash) ON CONFLICT REPLACE)''' )
            self.cur.execute( '''DROP TABLE objectprocessorqueue''')
            self.cur.execute( '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' )
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (7,)
            self.cur.execute(item, parameters)
            logger.debug(
                'Finished dropping and recreating the inventory table.')

        # The format of data stored in the pubkeys table has changed. Let's
        # clear it, and the pubkeys from inventory, so that they'll
        # be re-downloaded.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 7:
            logger.debug(
                'In messages.dat database, clearing pubkeys table'
                ' because the data format has been updated.')
            self.cur.execute(
                '''delete from inventory where objecttype = 1;''')
            self.cur.execute(
                '''delete from pubkeys;''')
            # Any sending messages for which we *thought* that we had
            # the pubkey must be rechecked.
            self.cur.execute(
                '''UPDATE sent SET status='msgqueued' WHERE status='doingmsgpow' or status='badkey';''')
            query = '''update settings set value=? WHERE key='version';'''
            parameters = (8,)
            self.cur.execute(query, parameters)
            logger.debug('Finished clearing currently held pubkeys.')

        # Add a new column to the inbox table to store the hash of
        # the message signature. We'll use this as temporary message UUID
        # in order to detect duplicates.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 8:
            logger.debug(
                'In messages.dat database, adding sighash field to'
                ' the inbox table.')
            item = '''ALTER TABLE inbox ADD sighash blob DEFAULT '' '''
            parameters = ''
            self.cur.execute(item, parameters)
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (9,)
            self.cur.execute(item, parameters)

        # We'll also need a `sleeptill` field and a `ttl` field. Also we
        # can combine the pubkeyretrynumber and msgretrynumber into one.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 9:
            logger.info(
                'In messages.dat database, making TTL-related changes:'
                ' combining the pubkeyretrynumber and msgretrynumber'
                ' fields into the retrynumber field and adding the'
                ' sleeptill and ttl fields...')
            self.cur.execute(
                '''CREATE TEMPORARY TABLE sent_backup (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, lastactiontime integer, status text, retrynumber integer, folder text, encodingtype int)''' )
            self.cur.execute(
                '''INSERT INTO sent_backup SELECT msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, 0, folder, encodingtype FROM sent;''')
            self.cur.execute( '''DROP TABLE sent''')
            self.cur.execute(
                '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, senttime integer, lastactiontime integer, sleeptill int, status text, retrynumber integer, folder text, encodingtype int, ttl int)''' )
            self.cur.execute(
                '''INSERT INTO sent SELECT msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, lastactiontime, 0, status, 0, folder, encodingtype, 216000 FROM sent_backup;''')
            self.cur.execute( '''DROP TABLE sent_backup''')
            logger.info('In messages.dat database, finished making TTL-related changes.')
            logger.debug('In messages.dat database, adding address field to the pubkeys table.')
            # We're going to have to calculate the address for each row in the pubkeys
            # table. Then we can take out the hash field.
            self.cur.execute('''ALTER TABLE pubkeys ADD address text DEFAULT '' ''')
            self.cur.execute('''SELECT hash, addressversion FROM pubkeys''')
            queryResult = self.cur.fetchall()
            from addresses import encodeAddress
            for row in queryResult:
                addressHash, addressVersion = row
                address = encodeAddress(addressVersion, 1, hash)
                item = '''UPDATE pubkeys SET address=? WHERE hash=?;'''
                parameters = (address, addressHash)
                self.cur.execute(item, parameters)
            # Now we can remove the hash field from the pubkeys table.
            self.cur.execute(
                '''CREATE TEMPORARY TABLE pubkeys_backup (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''INSERT INTO pubkeys_backup SELECT address, addressversion, transmitdata, time, usedpersonally FROM pubkeys;''')
            self.cur.execute( '''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)''' )
            self.cur.execute(
                '''INSERT INTO pubkeys SELECT address, addressversion, transmitdata, time, usedpersonally FROM pubkeys_backup;''')
            self.cur.execute( '''DROP TABLE pubkeys_backup''')
            logger.debug('In messages.dat database, done adding address field to the pubkeys table and removing the hash field.')
            self.cur.execute('''update settings set value=10 WHERE key='version';''')

        # Are you hoping to add a new option to the keys.dat file of existing
        # Bitmessage users or modify the SQLite database? Add it right
        # above this line!

        try:
            testpayload = '\x00\x00'
            t = ('1234', 1, testpayload, '12345678', 'no')
            self.cur.execute( '''INSERT INTO pubkeys VALUES(?,?,?,?,?)''', t)
            self.conn.commit()
            self.cur.execute(
                '''SELECT transmitdata FROM pubkeys WHERE address='1234' ''')
            queryreturn = self.cur.fetchall()
            for row in queryreturn:
                transmitdata, = row
            self.cur.execute('''DELETE FROM pubkeys WHERE address='1234' ''')
            self.conn.commit()
            if transmitdata == '':
                logger.fatal('Problem: The version of SQLite you have cannot store Null values. Please download and install the latest revision of your version of Python (for example, the latest Python 2.7 revision) and try again.\n')
                logger.fatal('PyBitmessage will now exit very abruptly. You may now see threading errors related to this abrupt exit but the problem you need to solve is related to SQLite.\n\n')
                os._exit(0)
        except Exception as err:
            if str(err) == 'database or disk is full':
                logger.fatal('(While null value test) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                os._exit(0)
            else:
                logger.error(err)

        # Let us check to see the last time we vaccumed the messages.dat file.
        # If it has been more than a month let's do it now.
        item = '''SELECT value FROM settings WHERE key='lastvacuumtime';'''
        parameters = ''
        self.cur.execute(item, parameters)
        queryreturn = self.cur.fetchall()
        for row in queryreturn:
            value, = row
            if int(value) < int(time.time()) - 86400:
                logger.info('It has been a long time since the messages.dat file has been vacuumed. Vacuuming now...')
                try:
                    self.cur.execute( ''' VACUUM ''')
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(While VACUUM) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
                item = '''update settings set value=? WHERE key='lastvacuumtime';'''
                parameters = (int(time.time()),)
                self.cur.execute(item, parameters)

        state.sqlReady = True

        while True:
            item = helper_sql.sqlSubmitQueue.get()
            if item == 'commit':
                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(While committing) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
            elif item == 'exit':
                self.conn.close()
                logger.info('sqlThread exiting gracefully.')

                return
            elif item == 'movemessagstoprog':
                logger.debug('the sqlThread is moving the messages.dat file to the local program directory.')

                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(while movemessagstoprog) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
                self.conn.close()
                shutil.move(
                    paths.lookupAppdataFolder() + 'messages.dat', paths.lookupExeFolder() + 'messages.dat')
                self.conn = sqlite3.connect(paths.lookupExeFolder() + 'messages.dat')
                self.conn.text_factory = str
                self.cur = self.conn.cursor()
            elif item == 'movemessagstoappdata':
                logger.debug('the sqlThread is moving the messages.dat file to the Appdata folder.')

                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(while movemessagstoappdata) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
                self.conn.close()
                shutil.move(
                    paths.lookupExeFolder() + 'messages.dat', paths.lookupAppdataFolder() + 'messages.dat')
                self.conn = sqlite3.connect(paths.lookupAppdataFolder() + 'messages.dat')
                self.conn.text_factory = str
                self.cur = self.conn.cursor()
            elif item == 'deleteandvacuume':
                self.cur.execute('''delete from inbox where folder='trash' ''')
                self.cur.execute('''delete from sent where folder='trash' ''')
                self.conn.commit()
                try:
                    self.cur.execute( ''' VACUUM ''')
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(while deleteandvacuume) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
            else:
                parameters = helper_sql.sqlSubmitQueue.get()
                rowcount = 0
                # print 'item', item
                # print 'parameters', parameters
                try:
                    self.cur.execute(item, parameters)
                    rowcount = self.cur.rowcount
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal('(while cur.execute) Alert: Your disk or data storage volume is full. sqlThread will now exit.')
                        queues.UISignalQueue.put(('alert', (tr._translate("MainWindow", "Disk full"), tr._translate("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True)))
                        os._exit(0)
                    else:
                        logger.fatal('Major error occurred when trying to execute a SQL statement within the sqlThread. Please tell Atheros about this error message or post it in the forum! Error occurred while trying to execute statement: "%s"  Here are the parameters; you might want to censor this data with asterisks (***) as it can contain private information: %s. Here is the actual error message thrown by the sqlThread: %s', str(item), str(repr(parameters)),  str(err))
                        logger.fatal('This program shall now abruptly exit!')

                    os._exit(0)

                helper_sql.sqlReturnQueue.put((self.cur.fetchall(), rowcount))
Ejemplo n.º 3
0
def loadConfig():
    if state.appdata:
        BMConfigParser().read(state.appdata + 'keys.dat')
        #state.appdata must have been specified as a startup option.
        try:
            BMConfigParser().get('bitmessagesettings', 'settingsversion')
            print 'Loading config files from directory specified on startup: ' + state.appdata
            needToCreateKeysFile = False
        except:
            needToCreateKeysFile = True

    else:
        BMConfigParser().read(paths.lookupExeFolder() + 'keys.dat')
        try:
            BMConfigParser().get('bitmessagesettings', 'settingsversion')
            print 'Loading config files from same directory as program.'
            needToCreateKeysFile = False
            state.appdata = paths.lookupExeFolder()
        except:
            # Could not load the keys.dat file in the program directory. Perhaps it
            # is in the appdata directory.
            state.appdata = paths.lookupAppdataFolder()
            BMConfigParser().read(state.appdata + 'keys.dat')
            try:
                BMConfigParser().get('bitmessagesettings', 'settingsversion')
                print 'Loading existing config files from', state.appdata
                needToCreateKeysFile = False
            except:
                needToCreateKeysFile = True

    if needToCreateKeysFile:
        # This appears to be the first time running the program; there is
        # no config file (or it cannot be accessed). Create config file.
        BMConfigParser().add_section('bitmessagesettings')
        BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
        BMConfigParser().set('bitmessagesettings', 'port', '8444')
        BMConfigParser().set(
            'bitmessagesettings', 'timeformat', '%%c')
        BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black')
        BMConfigParser().set('bitmessagesettings', 'startonlogon', 'false')
        if 'linux' in sys.platform:
            BMConfigParser().set(
                'bitmessagesettings', 'minimizetotray', 'false')
                              # This isn't implimented yet and when True on
                              # Ubuntu causes Bitmessage to disappear while
                              # running when minimized.
        else:
            BMConfigParser().set(
                'bitmessagesettings', 'minimizetotray', 'true')
        BMConfigParser().set(
            'bitmessagesettings', 'showtraynotifications', 'true')
        BMConfigParser().set('bitmessagesettings', 'startintray', 'false')
        BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'none')
        BMConfigParser().set(
            'bitmessagesettings', 'sockshostname', 'localhost')
        BMConfigParser().set('bitmessagesettings', 'socksport', '9050')
        BMConfigParser().set(
            'bitmessagesettings', 'socksauthentication', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'sockslisten', 'false')
        BMConfigParser().set('bitmessagesettings', 'socksusername', '')
        BMConfigParser().set('bitmessagesettings', 'sockspassword', '')
        BMConfigParser().set('bitmessagesettings', 'keysencrypted', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'messagesencrypted', 'false')
        BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
            defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
        BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
            defaults.networkDefaultPayloadLengthExtraBytes))
        BMConfigParser().set('bitmessagesettings', 'minimizeonclose', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
        BMConfigParser().set(
            'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
        BMConfigParser().set('bitmessagesettings', 'dontconnect', 'true')
        BMConfigParser().set('bitmessagesettings', 'userlocale', 'system')
        BMConfigParser().set('bitmessagesettings', 'useidenticons', 'True')
        BMConfigParser().set('bitmessagesettings', 'identiconsuffix', ''.join(random.choice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12))) # a twelve character pseudo-password to salt the identicons
        BMConfigParser().set('bitmessagesettings', 'replybelow', 'False')
        BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
        BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
        BMConfigParser().set('bitmessagesettings', 'maxoutboundconnections', '8')
        BMConfigParser().set('bitmessagesettings', 'ttl', '367200')
        
         #start:UI setting to stop trying to send messages after X days/months
        BMConfigParser().set(
            'bitmessagesettings', 'stopresendingafterxdays', '')
        BMConfigParser().set(
            'bitmessagesettings', 'stopresendingafterxmonths', '')
        #BMConfigParser().set(
        #    'bitmessagesettings', 'timeperiod', '-1')
        #end

        # Are you hoping to add a new option to the keys.dat file? You're in
        # the right place for adding it to users who install the software for
        # the first time. But you must also add it to the keys.dat file of
        # existing users. To do that, search the class_sqlThread.py file for the
        # text: "right above this line!"

        ensureNamecoinOptions()

        if storeConfigFilesInSameDirectoryAsProgramByDefault:
            # Just use the same directory as the program and forget about
            # the appdata folder
            state.appdata = ''
            print 'Creating new config files in same directory as program.'
        else:
            print 'Creating new config files in', state.appdata
            if not os.path.exists(state.appdata):
                os.makedirs(state.appdata)
        if not sys.platform.startswith('win'):
            os.umask(0o077)
        BMConfigParser().save()

    _loadTrustedPeer()
Ejemplo n.º 4
0
def loadConfig():
    if state.appdata:
        BMConfigParser().read(state.appdata + 'keys.dat')
        # state.appdata must have been specified as a startup option.
        try:
            BMConfigParser().get('bitmessagesettings', 'settingsversion')
            print 'Loading config files from directory specified on startup: ' + state.appdata
            needToCreateKeysFile = False
        except Exception:
            needToCreateKeysFile = True

    else:
        BMConfigParser().read(paths.lookupExeFolder() + 'keys.dat')
        try:
            BMConfigParser().get('bitmessagesettings', 'settingsversion')
            print 'Loading config files from same directory as program.'
            needToCreateKeysFile = False
            state.appdata = paths.lookupExeFolder()
        except Exception:
            # Could not load the keys.dat file in the program directory.
            # Perhaps it is in the appdata directory.
            state.appdata = paths.lookupAppdataFolder()
            BMConfigParser().read(state.appdata + 'keys.dat')
            try:
                BMConfigParser().get('bitmessagesettings', 'settingsversion')
                print 'Loading existing config files from', state.appdata
                needToCreateKeysFile = False
            except Exception:
                needToCreateKeysFile = True

    if needToCreateKeysFile:
        # This appears to be the first time running the program; there is
        # no config file (or it cannot be accessed). Create config file.
        BMConfigParser().add_section('bitmessagesettings')
        BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
        BMConfigParser().set('bitmessagesettings', 'port', '8444')
        BMConfigParser().set(
            'bitmessagesettings', 'timeformat', '%%c')
        BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black')
        BMConfigParser().set('bitmessagesettings', 'startonlogon', 'false')
        if 'linux' in sys.platform:
            BMConfigParser().set(
                'bitmessagesettings', 'minimizetotray', 'false')
                              # This isn't implimented yet and when True on
                              # Ubuntu causes Bitmessage to disappear while
                              # running when minimized.
        else:
            BMConfigParser().set(
                'bitmessagesettings', 'minimizetotray', 'true')
        BMConfigParser().set(
            'bitmessagesettings', 'showtraynotifications', 'true')
        BMConfigParser().set('bitmessagesettings', 'startintray', 'false')
        BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'none')
        BMConfigParser().set(
            'bitmessagesettings', 'sockshostname', 'localhost')
        BMConfigParser().set('bitmessagesettings', 'socksport', '9050')
        BMConfigParser().set(
            'bitmessagesettings', 'socksauthentication', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'sockslisten', 'false')
        BMConfigParser().set('bitmessagesettings', 'socksusername', '')
        BMConfigParser().set('bitmessagesettings', 'sockspassword', '')
        BMConfigParser().set('bitmessagesettings', 'keysencrypted', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'messagesencrypted', 'false')
        BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
            defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
        BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
            defaults.networkDefaultPayloadLengthExtraBytes))
        BMConfigParser().set('bitmessagesettings', 'minimizeonclose', 'false')
        BMConfigParser().set(
            'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
        BMConfigParser().set(
            'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
        BMConfigParser().set('bitmessagesettings', 'dontconnect', 'true')
        BMConfigParser().set('bitmessagesettings', 'userlocale', 'system')
        BMConfigParser().set('bitmessagesettings', 'useidenticons', 'True')
        BMConfigParser().set('bitmessagesettings', 'identiconsuffix', ''.join(helper_random.randomchoice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12)))# a twelve character pseudo-password to salt the identicons
        BMConfigParser().set('bitmessagesettings', 'replybelow', 'False')
        BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
        BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
        BMConfigParser().set('bitmessagesettings', 'maxoutboundconnections', '8')
        BMConfigParser().set('bitmessagesettings', 'ttl', '367200')
         #start:UI setting to stop trying to send messages after X days/months
        BMConfigParser().set(
            'bitmessagesettings', 'stopresendingafterxdays', '')
        BMConfigParser().set(
            'bitmessagesettings', 'stopresendingafterxmonths', '')
        #BMConfigParser().set(
        #    'bitmessagesettings', 'timeperiod', '-1')
        #end

        # Are you hoping to add a new option to the keys.dat file? You're in
        # the right place for adding it to users who install the software for
        # the first time. But you must also add it to the keys.dat file of
        # existing users. To do that, search the class_sqlThread.py file for the
        # text: "right above this line!"

        ensureNamecoinOptions()

        if StoreConfigFilesInSameDirectoryAsProgramByDefault:
            # Just use the same directory as the program and forget about
            # the appdata folder
            state.appdata = ''
            print 'Creating new config files in same directory as program.'
        else:
            print 'Creating new config files in', state.appdata
            if not os.path.exists(state.appdata):
                os.makedirs(state.appdata)
        if not sys.platform.startswith('win'):
            os.umask(0o077)
        BMConfigParser().save()

    _loadTrustedPeer()
Ejemplo n.º 5
0
def loadConfig():
    """Load the config"""
    config = BMConfigParser()
    if state.appdata:
        config.read(state.appdata + 'keys.dat')
        # state.appdata must have been specified as a startup option.
        needToCreateKeysFile = config.safeGet('bitmessagesettings',
                                              'settingsversion') is None
        if not needToCreateKeysFile:
            print('Loading config files from directory specified'
                  ' on startup: %s' % state.appdata)
    else:
        config.read(paths.lookupExeFolder() + 'keys.dat')
        try:
            config.get('bitmessagesettings', 'settingsversion')
            print('Loading config files from same directory as program.')
            needToCreateKeysFile = False
            state.appdata = paths.lookupExeFolder()
        except:
            # Could not load the keys.dat file in the program directory.
            # Perhaps it is in the appdata directory.
            state.appdata = paths.lookupAppdataFolder()
            config.read(state.appdata + 'keys.dat')
            needToCreateKeysFile = config.safeGet('bitmessagesettings',
                                                  'settingsversion') is None
            if not needToCreateKeysFile:
                print('Loading existing config files from', state.appdata)

    if needToCreateKeysFile:

        # This appears to be the first time running the program; there is
        # no config file (or it cannot be accessed). Create config file.
        config.add_section('bitmessagesettings')
        config.set('bitmessagesettings', 'settingsversion', '10')
        config.set('bitmessagesettings', 'port', '8444')
        config.set('bitmessagesettings', 'timeformat', '%%c')
        config.set('bitmessagesettings', 'blackwhitelist', 'black')
        config.set('bitmessagesettings', 'startonlogon', 'false')
        if 'linux' in sys.platform:
            config.set('bitmessagesettings', 'minimizetotray', 'false')
        # This isn't implimented yet and when True on
        # Ubuntu causes Bitmessage to disappear while
        # running when minimized.
        else:
            config.set('bitmessagesettings', 'minimizetotray', 'true')
        config.set('bitmessagesettings', 'showtraynotifications', 'true')
        config.set('bitmessagesettings', 'startintray', 'false')
        config.set('bitmessagesettings', 'socksproxytype', 'none')
        config.set('bitmessagesettings', 'sockshostname', 'localhost')
        config.set('bitmessagesettings', 'socksport', '9050')
        config.set('bitmessagesettings', 'socksauthentication', 'false')
        config.set('bitmessagesettings', 'socksusername', '')
        config.set('bitmessagesettings', 'sockspassword', '')
        config.set('bitmessagesettings', 'keysencrypted', 'false')
        config.set('bitmessagesettings', 'messagesencrypted', 'false')
        config.set('bitmessagesettings', 'defaultnoncetrialsperbyte',
                   str(defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
        config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes',
                   str(defaults.networkDefaultPayloadLengthExtraBytes))
        config.set('bitmessagesettings', 'minimizeonclose', 'false')
        config.set('bitmessagesettings', 'dontconnect', 'true')
        config.set('bitmessagesettings', 'replybelow', 'False')
        config.set('bitmessagesettings', 'maxdownloadrate', '0')
        config.set('bitmessagesettings', 'maxuploadrate', '0')

        # UI setting to stop trying to send messages after X days/months
        config.set('bitmessagesettings', 'stopresendingafterxdays', '')
        config.set('bitmessagesettings', 'stopresendingafterxmonths', '')

        # Are you hoping to add a new option to the keys.dat file? You're in
        # the right place for adding it to users who install the software for
        # the first time. But you must also add it to the keys.dat file of
        # existing users. To do that, search the class_sqlThread.py file
        # for the text: "right above this line!"

        if StoreConfigFilesInSameDirectoryAsProgramByDefault:
            # Just use the same directory as the program and forget about
            # the appdata folder
            state.appdata = ''
            print('Creating new config files in same directory as program.')
        else:
            print('Creating new config files in', state.appdata)
            if not os.path.exists(state.appdata):
                os.makedirs(state.appdata)
        if not sys.platform.startswith('win'):
            os.umask(0o077)
        config.save()
    else:
        updateConfig()

    _loadTrustedPeer()
Ejemplo n.º 6
0
def createSupportMessage(myapp):
    checkAddressBook(myapp)
    address = createAddressIfNeeded(myapp)
    if state.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 = softwareVersion
    commit = paths.lastCommit().get('commit')
    if commit:
        version += " GIT " + commit

    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
    
    opensslversion = "%s (Python internal), %s (external for PyElliptic)" % (ssl.OPENSSL_VERSION, OpenSSL._version)

    frozen = "N/A"
    if paths.frozen:
        frozen = paths.frozen
    portablemode = "True" if state.appdata == paths.lookupExeFolder() else "False"
    cpow = "True" if proofofwork.bmpow else "False"
    #cpow = QtGui.QApplication.translate("Support", cpow)
    openclpow = str(BMConfigParser().safeGet('bitmessagesettings', 'opencl')) if openclEnabled() else "None"
    #openclpow = QtGui.QApplication.translate("Support", openclpow)
    locale = getTranslationLanguage()
    try:
        socks = BMConfigParser().get('bitmessagesettings', 'socksproxytype')
    except:
        socks = "N/A"
    try:
        upnp = BMConfigParser().get('bitmessagesettings', 'upnp')
    except:
        upnp = "N/A"
    connectedhosts = len(network.stats.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(
        myapp.ui.tabWidgetSend.indexOf(myapp.ui.sendDirect)
    )
    # send tab
    myapp.ui.tabWidget.setCurrentIndex(
        myapp.ui.tabWidget.indexOf(myapp.ui.send)
    )
Ejemplo n.º 7
0
    def run(self):
        self.conn = sqlite3.connect(state.appdata + 'messages.dat')
        self.conn.text_factory = str
        self.cur = self.conn.cursor()

        self.cur.execute('PRAGMA secure_delete = true')

        try:
            self.cur.execute(
                '''CREATE TABLE inbox (msgid blob, toaddress text, fromaddress text, subject text, received text, message text, folder text, encodingtype int, read bool, sighash blob, UNIQUE(msgid) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, senttime integer, lastactiontime integer, sleeptill integer, status text, retrynumber integer, folder text, encodingtype int, ttl int)'''
            )
            self.cur.execute(
                '''CREATE TABLE subscriptions (label text, address text, enabled bool)'''
            )
            self.cur.execute(
                '''CREATE TABLE addressbook (label text, address text)''')
            self.cur.execute(
                '''CREATE TABLE blacklist (label text, address text, enabled bool)'''
            )
            self.cur.execute(
                '''CREATE TABLE whitelist (label text, address text, enabled bool)'''
            )
            self.cur.execute(
                '''CREATE TABLE pubkeys (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''CREATE TABLE inventory (hash blob, objecttype int, streamnumber int, payload blob, expirestime integer, tag blob, UNIQUE(hash) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)'''
            )
            self.cur.execute(
                '''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)'''
            )
            self.cur.execute('''INSERT INTO settings VALUES('version','10')''')
            self.cur.execute(
                '''INSERT INTO settings VALUES('lastvacuumtime',?)''',
                (int(time.time()), ))
            self.cur.execute(
                '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)'''
            )
            self.conn.commit()
            logger.info('Created messages database file')
        except Exception as err:
            if str(err) == 'table inbox already exists':
                logger.debug('Database file already exists.')

            else:
                sys.stderr.write(
                    'ERROR trying to create database file (message.dat). Error message: %s\n'
                    % str(err))
                os._exit(0)

        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 1:
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '2')
            # If the settings version is equal to 2 or 3 then the
            # sqlThread will modify the pubkeys table and change
            # the settings version to 4.
            BMConfigParser().set('bitmessagesettings', 'socksproxytype',
                                 'none')
            BMConfigParser().set('bitmessagesettings', 'sockshostname',
                                 'localhost')
            BMConfigParser().set('bitmessagesettings', 'socksport', '9050')
            BMConfigParser().set('bitmessagesettings', 'socksauthentication',
                                 'false')
            BMConfigParser().set('bitmessagesettings', 'socksusername', '')
            BMConfigParser().set('bitmessagesettings', 'sockspassword', '')
            BMConfigParser().set('bitmessagesettings', 'sockslisten', 'false')
            BMConfigParser().set('bitmessagesettings', 'keysencrypted',
                                 'false')
            BMConfigParser().set('bitmessagesettings', 'messagesencrypted',
                                 'false')

        # People running earlier versions of PyBitmessage do not have the
        # usedpersonally field in their pubkeys table. Let's add it.
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 2:
            item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' '''
            parameters = ''
            self.cur.execute(item, parameters)
            self.conn.commit()

            BMConfigParser().set('bitmessagesettings', 'settingsversion', '3')

        # People running earlier versions of PyBitmessage do not have the
        # encodingtype field in their inbox and sent tables or the read field
        # in the inbox table. Let's add them.
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 3:
            item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' '''
            parameters = ''
            self.cur.execute(item, parameters)

            item = '''ALTER TABLE inbox ADD read bool DEFAULT '1' '''
            parameters = ''
            self.cur.execute(item, parameters)

            item = '''ALTER TABLE sent ADD encodingtype int DEFAULT '2' '''
            parameters = ''
            self.cur.execute(item, parameters)
            self.conn.commit()

            BMConfigParser().set('bitmessagesettings', 'settingsversion', '4')

        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 4:
            BMConfigParser().set(
                'bitmessagesettings', 'defaultnoncetrialsperbyte',
                str(defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
            BMConfigParser().set(
                'bitmessagesettings', 'defaultpayloadlengthextrabytes',
                str(defaults.networkDefaultPayloadLengthExtraBytes))
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '5')

        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 5:
            BMConfigParser().set('bitmessagesettings',
                                 'maxacceptablenoncetrialsperbyte', '0')
            BMConfigParser().set('bitmessagesettings',
                                 'maxacceptablepayloadlengthextrabytes', '0')
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '6')

        # From now on, let us keep a 'version' embedded in the messages.dat
        # file so that when we make changes to the database, the database
        # version we are on can stay embedded in the messages.dat file. Let us
        # check to see if the settings table exists yet.
        item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';'''
        parameters = ''
        self.cur.execute(item, parameters)
        if self.cur.fetchall() == []:
            # The settings table doesn't exist. We need to make it.
            logger.debug(
                'In messages.dat database, creating new \'settings\' table.')
            self.cur.execute(
                '''CREATE TABLE settings (key text, value blob, UNIQUE(key) ON CONFLICT REPLACE)'''
            )
            self.cur.execute('''INSERT INTO settings VALUES('version','1')''')
            self.cur.execute(
                '''INSERT INTO settings VALUES('lastvacuumtime',?)''',
                (int(time.time()), ))
            logger.debug(
                'In messages.dat database, removing an obsolete field from the pubkeys table.'
            )
            self.cur.execute(
                '''CREATE TEMPORARY TABLE pubkeys_backup(hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE);'''
            )
            self.cur.execute(
                '''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM pubkeys;'''
            )
            self.cur.execute('''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM pubkeys_backup;'''
            )
            self.cur.execute('''DROP TABLE pubkeys_backup;''')
            logger.debug(
                'Deleting all pubkeys from inventory. They will be redownloaded and then saved with the correct times.'
            )
            self.cur.execute(
                '''delete from inventory where objecttype = 'pubkey';''')
            logger.debug(
                'replacing Bitmessage announcements mailing list with a new one.'
            )
            self.cur.execute(
                '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' '''
            )
            self.cur.execute(
                '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)'''
            )
            logger.debug('Commiting.')
            self.conn.commit()
            logger.debug(
                'Vacuuming message.dat. You might notice that the file size gets much smaller.'
            )
            self.cur.execute(''' VACUUM ''')

        # After code refactoring, the possible status values for sent messages
        # have changed.
        self.cur.execute(
            '''update sent set status='doingmsgpow' where status='doingpow'  '''
        )
        self.cur.execute(
            '''update sent set status='msgsent' where status='sentmessage'  '''
        )
        self.cur.execute(
            '''update sent set status='doingpubkeypow' where status='findingpubkey'  '''
        )
        self.cur.execute(
            '''update sent set status='broadcastqueued' where status='broadcastpending'  '''
        )
        self.conn.commit()

        if not BMConfigParser().has_option('bitmessagesettings',
                                           'sockslisten'):
            BMConfigParser().set('bitmessagesettings', 'sockslisten', 'false')

        ensureNamecoinOptions()

        # Let's get rid of the first20bytesofencryptedmessage field in the inventory table.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        if int(self.cur.fetchall()[0][0]) == 2:
            logger.debug(
                'In messages.dat database, removing an obsolete field from the inventory table.'
            )
            self.cur.execute(
                '''CREATE TEMPORARY TABLE inventory_backup(hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, UNIQUE(hash) ON CONFLICT REPLACE);'''
            )
            self.cur.execute(
                '''INSERT INTO inventory_backup SELECT hash, objecttype, streamnumber, payload, receivedtime FROM inventory;'''
            )
            self.cur.execute('''DROP TABLE inventory''')
            self.cur.execute(
                '''CREATE TABLE inventory (hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, UNIQUE(hash) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''INSERT INTO inventory SELECT hash, objecttype, streamnumber, payload, receivedtime FROM inventory_backup;'''
            )
            self.cur.execute('''DROP TABLE inventory_backup;''')
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (3, )
            self.cur.execute(item, parameters)

        # Add a new column to the inventory table to store tags.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 1 or currentVersion == 3:
            logger.debug(
                'In messages.dat database, adding tag field to the inventory table.'
            )
            item = '''ALTER TABLE inventory ADD tag blob DEFAULT '' '''
            parameters = ''
            self.cur.execute(item, parameters)
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (4, )
            self.cur.execute(item, parameters)

        if not BMConfigParser().has_option('bitmessagesettings', 'userlocale'):
            BMConfigParser().set('bitmessagesettings', 'userlocale', 'system')
        if not BMConfigParser().has_option('bitmessagesettings',
                                           'sendoutgoingconnections'):
            BMConfigParser().set('bitmessagesettings',
                                 'sendoutgoingconnections', 'True')

        # Raise the default required difficulty from 1 to 2
        # With the change to protocol v3, this is obsolete.
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 6:
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '7')

        # Add a new column to the pubkeys table to store the address version.
        # We're going to trash all of our pubkeys and let them be redownloaded.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 4:
            self.cur.execute('''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (hash blob, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(hash, addressversion) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''delete from inventory where objecttype = 'pubkey';''')
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (5, )
            self.cur.execute(item, parameters)

        if not BMConfigParser().has_option('bitmessagesettings',
                                           'useidenticons'):
            BMConfigParser().set('bitmessagesettings', 'useidenticons', 'True')
        if not BMConfigParser().has_option(
                'bitmessagesettings', 'identiconsuffix'):  # acts as a salt
            BMConfigParser(
            ).set('bitmessagesettings', 'identiconsuffix', ''.join(
                helper_random.randomchoice(
                    "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
                ) for x in range(12)
            ))  # a twelve character pseudo-password to salt the identicons

        #Add settings to support no longer resending messages after a certain period of time even if we never get an ack
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 7:
            BMConfigParser().set('bitmessagesettings',
                                 'stopresendingafterxdays', '')
            BMConfigParser().set('bitmessagesettings',
                                 'stopresendingafterxmonths', '')
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '8')

        # Add a new table: objectprocessorqueue with which to hold objects
        # that have yet to be processed if the user shuts down Bitmessage.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 5:
            self.cur.execute('''DROP TABLE knownnodes''')
            self.cur.execute(
                '''CREATE TABLE objectprocessorqueue (objecttype text, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)'''
            )
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (6, )
            self.cur.execute(item, parameters)

        # changes related to protocol v3
#    In table inventory and objectprocessorqueue, objecttype is now an integer (it was a human-friendly string previously)
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 6:
            logger.debug(
                'In messages.dat database, dropping and recreating the inventory table.'
            )
            self.cur.execute('''DROP TABLE inventory''')
            self.cur.execute(
                '''CREATE TABLE inventory (hash blob, objecttype int, streamnumber int, payload blob, expirestime integer, tag blob, UNIQUE(hash) ON CONFLICT REPLACE)'''
            )
            self.cur.execute('''DROP TABLE objectprocessorqueue''')
            self.cur.execute(
                '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)'''
            )
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (7, )
            self.cur.execute(item, parameters)
            logger.debug(
                'Finished dropping and recreating the inventory table.')

        # With the change to protocol version 3, reset the user-settable difficulties to 1
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 8:
            BMConfigParser().set(
                'bitmessagesettings', 'defaultnoncetrialsperbyte',
                str(defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
            BMConfigParser().set(
                'bitmessagesettings', 'defaultpayloadlengthextrabytes',
                str(defaults.networkDefaultPayloadLengthExtraBytes))
            previousTotalDifficulty = int(BMConfigParser().getint(
                'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / 320
            previousSmallMessageDifficulty = int(BMConfigParser().getint(
                'bitmessagesettings',
                'maxacceptablepayloadlengthextrabytes')) / 14000
            BMConfigParser().set('bitmessagesettings',
                                 'maxacceptablenoncetrialsperbyte',
                                 str(previousTotalDifficulty * 1000))
            BMConfigParser().set('bitmessagesettings',
                                 'maxacceptablepayloadlengthextrabytes',
                                 str(previousSmallMessageDifficulty * 1000))
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '9')

        # Adjust the required POW values for each of this user's addresses to conform to protocol v3 norms.
        if BMConfigParser().getint('bitmessagesettings',
                                   'settingsversion') == 9:
            for addressInKeysFile in BMConfigParser().addressses():
                try:
                    previousTotalDifficulty = float(BMConfigParser().getint(
                        addressInKeysFile, 'noncetrialsperbyte')) / 320
                    previousSmallMessageDifficulty = float(
                        BMConfigParser().getint(
                            addressInKeysFile,
                            'payloadlengthextrabytes')) / 14000
                    if previousTotalDifficulty <= 2:
                        previousTotalDifficulty = 1
                    if previousSmallMessageDifficulty < 1:
                        previousSmallMessageDifficulty = 1
                    BMConfigParser().set(
                        addressInKeysFile, 'noncetrialsperbyte',
                        str(int(previousTotalDifficulty * 1000)))
                    BMConfigParser().set(
                        addressInKeysFile, 'payloadlengthextrabytes',
                        str(int(previousSmallMessageDifficulty * 1000)))
                except:
                    continue
            BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
            BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
            BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
            BMConfigParser().save()

        # sanity check
        if BMConfigParser().getint('bitmessagesettings',
                                   'maxacceptablenoncetrialsperbyte') == 0:
            BMConfigParser().set(
                'bitmessagesettings', 'maxacceptablenoncetrialsperbyte',
                str(defaults.ridiculousDifficulty *
                    defaults.networkDefaultProofOfWorkNonceTrialsPerByte))
        if BMConfigParser().getint(
                'bitmessagesettings',
                'maxacceptablepayloadlengthextrabytes') == 0:
            BMConfigParser().set(
                'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes',
                str(defaults.ridiculousDifficulty *
                    defaults.networkDefaultPayloadLengthExtraBytes))

        # The format of data stored in the pubkeys table has changed. Let's
        # clear it, and the pubkeys from inventory, so that they'll be re-downloaded.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 7:
            logger.debug(
                'In messages.dat database, clearing pubkeys table because the data format has been updated.'
            )
            self.cur.execute('''delete from inventory where objecttype = 1;''')
            self.cur.execute('''delete from pubkeys;''')
            # Any sending messages for which we *thought* that we had the pubkey must
            # be rechecked.
            self.cur.execute(
                '''UPDATE sent SET status='msgqueued' WHERE status='doingmsgpow' or status='badkey';'''
            )
            query = '''update settings set value=? WHERE key='version';'''
            parameters = (8, )
            self.cur.execute(query, parameters)
            logger.debug('Finished clearing currently held pubkeys.')

        # Add a new column to the inbox table to store the hash of the message signature.
        # We'll use this as temporary message UUID in order to detect duplicates.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 8:
            logger.debug(
                'In messages.dat database, adding sighash field to the inbox table.'
            )
            item = '''ALTER TABLE inbox ADD sighash blob DEFAULT '' '''
            parameters = ''
            self.cur.execute(item, parameters)
            item = '''update settings set value=? WHERE key='version';'''
            parameters = (9, )
            self.cur.execute(item, parameters)

        # TTL is now user-specifiable. Let's add an option to save whatever the user selects.
        if not BMConfigParser().has_option('bitmessagesettings', 'ttl'):
            BMConfigParser().set('bitmessagesettings', 'ttl', '367200')
        # We'll also need a `sleeptill` field and a `ttl` field. Also we can combine
        # the pubkeyretrynumber and msgretrynumber into one.
        item = '''SELECT value FROM settings WHERE key='version';'''
        parameters = ''
        self.cur.execute(item, parameters)
        currentVersion = int(self.cur.fetchall()[0][0])
        if currentVersion == 9:
            logger.info(
                'In messages.dat database, making TTL-related changes: combining the pubkeyretrynumber and msgretrynumber fields into the retrynumber field and adding the sleeptill and ttl fields...'
            )
            self.cur.execute(
                '''CREATE TEMPORARY TABLE sent_backup (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, lastactiontime integer, status text, retrynumber integer, folder text, encodingtype int)'''
            )
            self.cur.execute(
                '''INSERT INTO sent_backup SELECT msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, 0, folder, encodingtype FROM sent;'''
            )
            self.cur.execute('''DROP TABLE sent''')
            self.cur.execute(
                '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, senttime integer, lastactiontime integer, sleeptill int, status text, retrynumber integer, folder text, encodingtype int, ttl int)'''
            )
            self.cur.execute(
                '''INSERT INTO sent SELECT msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, lastactiontime, 0, status, 0, folder, encodingtype, 216000 FROM sent_backup;'''
            )
            self.cur.execute('''DROP TABLE sent_backup''')
            logger.info(
                'In messages.dat database, finished making TTL-related changes.'
            )
            logger.debug(
                'In messages.dat database, adding address field to the pubkeys table.'
            )
            # We're going to have to calculate the address for each row in the pubkeys
            # table. Then we can take out the hash field.
            self.cur.execute(
                '''ALTER TABLE pubkeys ADD address text DEFAULT '' ''')
            self.cur.execute('''SELECT hash, addressversion FROM pubkeys''')
            queryResult = self.cur.fetchall()
            from addresses import encodeAddress
            for row in queryResult:
                addressHash, addressVersion = row
                address = encodeAddress(addressVersion, 1, hash)
                item = '''UPDATE pubkeys SET address=? WHERE hash=?;'''
                parameters = (address, addressHash)
                self.cur.execute(item, parameters)
            # Now we can remove the hash field from the pubkeys table.
            self.cur.execute(
                '''CREATE TEMPORARY TABLE pubkeys_backup (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''INSERT INTO pubkeys_backup SELECT address, addressversion, transmitdata, time, usedpersonally FROM pubkeys;'''
            )
            self.cur.execute('''DROP TABLE pubkeys''')
            self.cur.execute(
                '''CREATE TABLE pubkeys (address text, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(address) ON CONFLICT REPLACE)'''
            )
            self.cur.execute(
                '''INSERT INTO pubkeys SELECT address, addressversion, transmitdata, time, usedpersonally FROM pubkeys_backup;'''
            )
            self.cur.execute('''DROP TABLE pubkeys_backup''')
            logger.debug(
                'In messages.dat database, done adding address field to the pubkeys table and removing the hash field.'
            )
            self.cur.execute(
                '''update settings set value=10 WHERE key='version';''')

        if not BMConfigParser().has_option('bitmessagesettings',
                                           'onionhostname'):
            BMConfigParser().set('bitmessagesettings', 'onionhostname', '')
        if not BMConfigParser().has_option('bitmessagesettings', 'onionport'):
            BMConfigParser().set('bitmessagesettings', 'onionport', '8444')
        if not BMConfigParser().has_option('bitmessagesettings',
                                           'onionbindip'):
            BMConfigParser().set('bitmessagesettings', 'onionbindip',
                                 '127.0.0.1')
        if not BMConfigParser().has_option('bitmessagesettings',
                                           'smtpdeliver'):
            BMConfigParser().set('bitmessagesettings', 'smtpdeliver', '')
        if not BMConfigParser().has_option('bitmessagesettings',
                                           'hidetrayconnectionnotifications'):
            BMConfigParser().set('bitmessagesettings',
                                 'hidetrayconnectionnotifications', 'false')
        if BMConfigParser().has_option('bitmessagesettings',
                                       'maxoutboundconnections'):
            try:
                if BMConfigParser().getint('bitmessagesettings',
                                           'maxoutboundconnections') < 1:
                    raise ValueError
            except ValueError as err:
                BMConfigParser().remove_option('bitmessagesettings',
                                               'maxoutboundconnections')
                logger.error(
                    'Your maximum outbound connections must be a number.')
        if not BMConfigParser().has_option('bitmessagesettings',
                                           'maxoutboundconnections'):
            logger.info('Setting maximum outbound connections to 8.')
            BMConfigParser().set('bitmessagesettings',
                                 'maxoutboundconnections', '8')

        BMConfigParser().save()

        # Are you hoping to add a new option to the keys.dat file of existing
        # Bitmessage users or modify the SQLite database? Add it right above this line!

        try:
            testpayload = '\x00\x00'
            t = ('1234', 1, testpayload, '12345678', 'no')
            self.cur.execute('''INSERT INTO pubkeys VALUES(?,?,?,?,?)''', t)
            self.conn.commit()
            self.cur.execute(
                '''SELECT transmitdata FROM pubkeys WHERE address='1234' ''')
            queryreturn = self.cur.fetchall()
            for row in queryreturn:
                transmitdata, = row
            self.cur.execute('''DELETE FROM pubkeys WHERE address='1234' ''')
            self.conn.commit()
            if transmitdata == '':
                logger.fatal(
                    'Problem: The version of SQLite you have cannot store Null values. Please download and install the latest revision of your version of Python (for example, the latest Python 2.7 revision) and try again.\n'
                )
                logger.fatal(
                    'PyBitmessage will now exit very abruptly. You may now see threading errors related to this abrupt exit but the problem you need to solve is related to SQLite.\n\n'
                )
                os._exit(0)
        except Exception as err:
            if str(err) == 'database or disk is full':
                logger.fatal(
                    '(While null value test) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                )
                queues.UISignalQueue.put(('alert', (
                    tr._translate("MainWindow", "Disk full"),
                    tr._translate(
                        "MainWindow",
                        'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                    ), True)))
                os._exit(0)
            else:
                logger.error(err)

        # Let us check to see the last time we vaccumed the messages.dat file.
        # If it has been more than a month let's do it now.
        item = '''SELECT value FROM settings WHERE key='lastvacuumtime';'''
        parameters = ''
        self.cur.execute(item, parameters)
        queryreturn = self.cur.fetchall()
        for row in queryreturn:
            value, = row
            if int(value) < int(time.time()) - 86400:
                logger.info(
                    'It has been a long time since the messages.dat file has been vacuumed. Vacuuming now...'
                )
                try:
                    self.cur.execute(''' VACUUM ''')
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(While VACUUM) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
                item = '''update settings set value=? WHERE key='lastvacuumtime';'''
                parameters = (int(time.time()), )
                self.cur.execute(item, parameters)

        state.sqlReady = True

        while True:
            item = helper_sql.sqlSubmitQueue.get()
            if item == 'commit':
                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(While committing) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
            elif item == 'exit':
                self.conn.close()
                logger.info('sqlThread exiting gracefully.')

                return
            elif item == 'movemessagstoprog':
                logger.debug(
                    'the sqlThread is moving the messages.dat file to the local program directory.'
                )

                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(while movemessagstoprog) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
                self.conn.close()
                shutil.move(paths.lookupAppdataFolder() + 'messages.dat',
                            paths.lookupExeFolder() + 'messages.dat')
                self.conn = sqlite3.connect(paths.lookupExeFolder() +
                                            'messages.dat')
                self.conn.text_factory = str
                self.cur = self.conn.cursor()
            elif item == 'movemessagstoappdata':
                logger.debug(
                    'the sqlThread is moving the messages.dat file to the Appdata folder.'
                )

                try:
                    self.conn.commit()
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(while movemessagstoappdata) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
                self.conn.close()
                shutil.move(paths.lookupExeFolder() + 'messages.dat',
                            paths.lookupAppdataFolder() + 'messages.dat')
                self.conn = sqlite3.connect(paths.lookupAppdataFolder() +
                                            'messages.dat')
                self.conn.text_factory = str
                self.cur = self.conn.cursor()
            elif item == 'deleteandvacuume':
                self.cur.execute('''delete from inbox where folder='trash' ''')
                self.cur.execute('''delete from sent where folder='trash' ''')
                self.conn.commit()
                try:
                    self.cur.execute(''' VACUUM ''')
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(while deleteandvacuume) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
            else:
                parameters = helper_sql.sqlSubmitQueue.get()
                rowcount = 0
                # print 'item', item
                # print 'parameters', parameters
                try:
                    self.cur.execute(item, parameters)
                    rowcount = self.cur.rowcount
                except Exception as err:
                    if str(err) == 'database or disk is full':
                        logger.fatal(
                            '(while cur.execute) Alert: Your disk or data storage volume is full. sqlThread will now exit.'
                        )
                        queues.UISignalQueue.put(('alert', (
                            tr._translate("MainWindow", "Disk full"),
                            tr._translate(
                                "MainWindow",
                                'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'
                            ), True)))
                        os._exit(0)
                    else:
                        logger.fatal(
                            'Major error occurred when trying to execute a SQL statement within the sqlThread. Please tell Atheros about this error message or post it in the forum! Error occurred while trying to execute statement: "%s"  Here are the parameters; you might want to censor this data with asterisks (***) as it can contain private information: %s. Here is the actual error message thrown by the sqlThread: %s',
                            str(item), str(repr(parameters)), str(err))
                        logger.fatal('This program shall now abruptly exit!')

                    os._exit(0)

                helper_sql.sqlReturnQueue.put((self.cur.fetchall(), rowcount))
Ejemplo n.º 8
0
    def adjust_from_config(self, config):
        """Adjust all widgets state according to config settings"""
        # pylint: disable=too-many-branches,too-many-statements
        if not self.parent.tray.isSystemTrayAvailable():
            self.groupBoxTray.setEnabled(False)
            self.groupBoxTray.setTitle(
                _translate("MainWindow",
                           "Tray (not available in your system)"))
            for setting in ('minimizetotray', 'trayonclose', 'startintray'):
                config.set('bitmessagesettings', setting, 'false')
        else:
            self.checkBoxMinimizeToTray.setChecked(
                config.getboolean('bitmessagesettings', 'minimizetotray'))
            self.checkBoxTrayOnClose.setChecked(
                config.safeGetBoolean('bitmessagesettings', 'trayonclose'))
            self.checkBoxStartInTray.setChecked(
                config.getboolean('bitmessagesettings', 'startintray'))

        self.checkBoxHideTrayConnectionNotifications.setChecked(
            config.getboolean('bitmessagesettings',
                              'hidetrayconnectionnotifications'))
        self.checkBoxShowTrayNotifications.setChecked(
            config.getboolean('bitmessagesettings', 'showtraynotifications'))

        self.checkBoxStartOnLogon.setChecked(
            config.getboolean('bitmessagesettings', 'startonlogon'))

        self.checkBoxWillinglySendToMobile.setChecked(
            config.safeGetBoolean('bitmessagesettings',
                                  'willinglysendtomobile'))
        self.checkBoxUseIdenticons.setChecked(
            config.safeGetBoolean('bitmessagesettings', 'useidenticons'))
        self.checkBoxReplyBelow.setChecked(
            config.safeGetBoolean('bitmessagesettings', 'replybelow'))

        if state.appdata == paths.lookupExeFolder():
            self.checkBoxPortableMode.setChecked(True)
        else:
            try:
                tempfile.NamedTemporaryFile(
                    dir=paths.lookupExeFolder(),
                    delete=True).close()  # should autodelete
            except Exception:
                self.checkBoxPortableMode.setDisabled(True)

        if 'darwin' in sys.platform:
            self.checkBoxStartOnLogon.setDisabled(True)
            self.checkBoxStartOnLogon.setText(
                _translate("MainWindow",
                           "Start-on-login not yet supported on your OS."))
            self.checkBoxMinimizeToTray.setDisabled(True)
            self.checkBoxMinimizeToTray.setText(
                _translate("MainWindow",
                           "Minimize-to-tray not yet supported on your OS."))
            self.checkBoxShowTrayNotifications.setDisabled(True)
            self.checkBoxShowTrayNotifications.setText(
                _translate("MainWindow",
                           "Tray notifications not yet supported on your OS."))
        elif 'linux' in sys.platform:
            self.checkBoxStartOnLogon.setDisabled(True)
            self.checkBoxStartOnLogon.setText(
                _translate("MainWindow",
                           "Start-on-login not yet supported on your OS."))
        # On the Network settings tab:
        self.lineEditTCPPort.setText(
            str(config.get('bitmessagesettings', 'port')))
        self.checkBoxUPnP.setChecked(
            config.safeGetBoolean('bitmessagesettings', 'upnp'))
        self.checkBoxAuthentication.setChecked(
            config.getboolean('bitmessagesettings', 'socksauthentication'))
        self.checkBoxSocksListen.setChecked(
            config.getboolean('bitmessagesettings', 'sockslisten'))
        self.checkBoxOnionOnly.setChecked(
            config.safeGetBoolean('bitmessagesettings', 'onionservicesonly'))

        self._proxy_type = getSOCKSProxyType(config)
        self.comboBoxProxyType.setCurrentIndex(
            0 if not self._proxy_type else self.comboBoxProxyType.
            findText(self._proxy_type))
        self.comboBoxProxyTypeChanged(self.comboBoxProxyType.currentIndex())

        self.lineEditSocksHostname.setText(
            config.get('bitmessagesettings', 'sockshostname'))
        self.lineEditSocksPort.setText(
            str(config.get('bitmessagesettings', 'socksport')))
        self.lineEditSocksUsername.setText(
            config.get('bitmessagesettings', 'socksusername'))
        self.lineEditSocksPassword.setText(
            config.get('bitmessagesettings', 'sockspassword'))

        self.lineEditMaxDownloadRate.setText(
            str(config.get('bitmessagesettings', 'maxdownloadrate')))
        self.lineEditMaxUploadRate.setText(
            str(config.get('bitmessagesettings', 'maxuploadrate')))
        self.lineEditMaxOutboundConnections.setText(
            str(config.get('bitmessagesettings', 'maxoutboundconnections')))

        # Demanded difficulty tab
        self.lineEditTotalDifficulty.setText(
            str((float(
                config.getint('bitmessagesettings',
                              'defaultnoncetrialsperbyte')) /
                 defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
        self.lineEditSmallMessageDifficulty.setText(
            str((float(
                config.getint('bitmessagesettings',
                              'defaultpayloadlengthextrabytes')) /
                 defaults.networkDefaultPayloadLengthExtraBytes)))

        # Max acceptable difficulty tab
        self.lineEditMaxAcceptableTotalDifficulty.setText(
            str((float(
                config.getint('bitmessagesettings',
                              'maxacceptablenoncetrialsperbyte')) /
                 defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
        self.lineEditMaxAcceptableSmallMessageDifficulty.setText(
            str((float(
                config.getint('bitmessagesettings',
                              'maxacceptablepayloadlengthextrabytes')) /
                 defaults.networkDefaultPayloadLengthExtraBytes)))

        # OpenCL
        self.comboBoxOpenCL.setEnabled(openclpow.openclAvailable())
        self.comboBoxOpenCL.clear()
        self.comboBoxOpenCL.addItem("None")
        self.comboBoxOpenCL.addItems(openclpow.vendors)
        self.comboBoxOpenCL.setCurrentIndex(0)
        for i in range(self.comboBoxOpenCL.count()):
            if self.comboBoxOpenCL.itemText(i) == config.safeGet(
                    'bitmessagesettings', 'opencl'):
                self.comboBoxOpenCL.setCurrentIndex(i)
                break

        # Namecoin integration tab
        nmctype = config.get('bitmessagesettings', 'namecoinrpctype')
        self.lineEditNamecoinHost.setText(
            config.get('bitmessagesettings', 'namecoinrpchost'))
        self.lineEditNamecoinPort.setText(
            str(config.get('bitmessagesettings', 'namecoinrpcport')))
        self.lineEditNamecoinUser.setText(
            config.get('bitmessagesettings', 'namecoinrpcuser'))
        self.lineEditNamecoinPassword.setText(
            config.get('bitmessagesettings', 'namecoinrpcpassword'))

        if nmctype == "namecoind":
            self.radioButtonNamecoinNamecoind.setChecked(True)
        elif nmctype == "nmcontrol":
            self.radioButtonNamecoinNmcontrol.setChecked(True)
            self.lineEditNamecoinUser.setEnabled(False)
            self.labelNamecoinUser.setEnabled(False)
            self.lineEditNamecoinPassword.setEnabled(False)
            self.labelNamecoinPassword.setEnabled(False)
        else:
            assert False

        # Message Resend tab
        self.lineEditDays.setText(
            str(config.get('bitmessagesettings', 'stopresendingafterxdays')))
        self.lineEditMonths.setText(
            str(config.get('bitmessagesettings', 'stopresendingafterxmonths')))
Ejemplo n.º 9
0
    def accept(self):
        """A callback for accepted event of buttonBox (OK button pressed)"""
        # pylint: disable=too-many-branches,too-many-statements
        super(SettingsDialog, self).accept()
        if self.firstrun:
            self.config.remove_option('bitmessagesettings', 'dontconnect')
        self.config.set('bitmessagesettings', 'startonlogon',
                        str(self.checkBoxStartOnLogon.isChecked()))
        self.config.set('bitmessagesettings', 'minimizetotray',
                        str(self.checkBoxMinimizeToTray.isChecked()))
        self.config.set('bitmessagesettings', 'trayonclose',
                        str(self.checkBoxTrayOnClose.isChecked()))
        self.config.set(
            'bitmessagesettings', 'hidetrayconnectionnotifications',
            str(self.checkBoxHideTrayConnectionNotifications.isChecked()))
        self.config.set('bitmessagesettings', 'showtraynotifications',
                        str(self.checkBoxShowTrayNotifications.isChecked()))
        self.config.set('bitmessagesettings', 'startintray',
                        str(self.checkBoxStartInTray.isChecked()))
        self.config.set('bitmessagesettings', 'willinglysendtomobile',
                        str(self.checkBoxWillinglySendToMobile.isChecked()))
        self.config.set('bitmessagesettings', 'useidenticons',
                        str(self.checkBoxUseIdenticons.isChecked()))
        self.config.set('bitmessagesettings', 'replybelow',
                        str(self.checkBoxReplyBelow.isChecked()))

        lang = str(
            self.languageComboBox.itemData(
                self.languageComboBox.currentIndex()).toString())
        self.config.set('bitmessagesettings', 'userlocale', lang)
        self.parent.change_translation()

        if int(self.config.get('bitmessagesettings', 'port')) != int(
                self.lineEditTCPPort.text()):
            self.config.set('bitmessagesettings', 'port',
                            str(self.lineEditTCPPort.text()))
            if not self.config.safeGetBoolean('bitmessagesettings',
                                              'dontconnect'):
                self.net_restart_needed = True

        if self.checkBoxUPnP.isChecked() != self.config.safeGetBoolean(
                'bitmessagesettings', 'upnp'):
            self.config.set('bitmessagesettings', 'upnp',
                            str(self.checkBoxUPnP.isChecked()))
            if self.checkBoxUPnP.isChecked():
                import upnp
                upnpThread = upnp.uPnPThread()
                upnpThread.start()

        proxytype_index = self.comboBoxProxyType.currentIndex()
        if proxytype_index == 0:
            if self._proxy_type and state.statusIconColor != 'red':
                self.net_restart_needed = True
        elif self.comboBoxProxyType.currentText() != self._proxy_type:
            self.net_restart_needed = True
            self.parent.statusbar.clearMessage()

        self.config.set(
            'bitmessagesettings', 'socksproxytype',
            'none' if self.comboBoxProxyType.currentIndex() == 0 else str(
                self.comboBoxProxyType.currentText()))
        if proxytype_index > 2:  # last literal proxytype in ui
            start_proxyconfig()

        self.config.set('bitmessagesettings', 'socksauthentication',
                        str(self.checkBoxAuthentication.isChecked()))
        self.config.set('bitmessagesettings', 'sockshostname',
                        str(self.lineEditSocksHostname.text()))
        self.config.set('bitmessagesettings', 'socksport',
                        str(self.lineEditSocksPort.text()))
        self.config.set('bitmessagesettings', 'socksusername',
                        str(self.lineEditSocksUsername.text()))
        self.config.set('bitmessagesettings', 'sockspassword',
                        str(self.lineEditSocksPassword.text()))
        self.config.set('bitmessagesettings', 'sockslisten',
                        str(self.checkBoxSocksListen.isChecked()))
        if self.checkBoxOnionOnly.isChecked() \
                and not self.config.safeGetBoolean('bitmessagesettings', 'onionservicesonly'):
            self.net_restart_needed = True
        self.config.set('bitmessagesettings', 'onionservicesonly',
                        str(self.checkBoxOnionOnly.isChecked()))
        try:
            # Rounding to integers just for aesthetics
            self.config.set(
                'bitmessagesettings', 'maxdownloadrate',
                str(int(float(self.lineEditMaxDownloadRate.text()))))
            self.config.set('bitmessagesettings', 'maxuploadrate',
                            str(int(float(self.lineEditMaxUploadRate.text()))))
        except ValueError:
            QtGui.QMessageBox.about(
                self, _translate("MainWindow", "Number needed"),
                _translate(
                    "MainWindow",
                    "Your maximum download and upload rate must be numbers."
                    " Ignoring what you typed."))
        else:
            set_rates(
                self.config.safeGetInt('bitmessagesettings',
                                       'maxdownloadrate'),
                self.config.safeGetInt('bitmessagesettings', 'maxuploadrate'))

        self.config.set(
            'bitmessagesettings', 'maxoutboundconnections',
            str(int(float(self.lineEditMaxOutboundConnections.text()))))

        self.config.set('bitmessagesettings', 'namecoinrpctype',
                        self.getNamecoinType())
        self.config.set('bitmessagesettings', 'namecoinrpchost',
                        str(self.lineEditNamecoinHost.text()))
        self.config.set('bitmessagesettings', 'namecoinrpcport',
                        str(self.lineEditNamecoinPort.text()))
        self.config.set('bitmessagesettings', 'namecoinrpcuser',
                        str(self.lineEditNamecoinUser.text()))
        self.config.set('bitmessagesettings', 'namecoinrpcpassword',
                        str(self.lineEditNamecoinPassword.text()))
        self.parent.resetNamecoinConnection()

        # Demanded difficulty tab
        if float(self.lineEditTotalDifficulty.text()) >= 1:
            self.config.set(
                'bitmessagesettings', 'defaultnoncetrialsperbyte',
                str(
                    int(
                        float(self.lineEditTotalDifficulty.text()) *
                        defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
        if float(self.lineEditSmallMessageDifficulty.text()) >= 1:
            self.config.set(
                'bitmessagesettings', 'defaultpayloadlengthextrabytes',
                str(
                    int(
                        float(self.lineEditSmallMessageDifficulty.text()) *
                        defaults.networkDefaultPayloadLengthExtraBytes)))

        if self.comboBoxOpenCL.currentText().toUtf8() != self.config.safeGet(
                'bitmessagesettings', 'opencl'):
            self.config.set('bitmessagesettings', 'opencl',
                            str(self.comboBoxOpenCL.currentText()))
            queues.workerQueue.put(('resetPoW', ''))

        acceptableDifficultyChanged = False

        if (float(self.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or
                float(self.lineEditMaxAcceptableTotalDifficulty.text()) == 0):
            if self.config.get(
                    'bitmessagesettings', 'maxacceptablenoncetrialsperbyte'
            ) != str(
                    int(
                        float(
                            self.lineEditMaxAcceptableTotalDifficulty.text()) *
                        defaults.networkDefaultProofOfWorkNonceTrialsPerByte)):
                # the user changed the max acceptable total difficulty
                acceptableDifficultyChanged = True
                self.config.set(
                    'bitmessagesettings', 'maxacceptablenoncetrialsperbyte',
                    str(
                        int(
                            float(self.lineEditMaxAcceptableTotalDifficulty.
                                  text()) * defaults.
                            networkDefaultProofOfWorkNonceTrialsPerByte)))
        if (float(self.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1
                or float(
                    self.lineEditMaxAcceptableSmallMessageDifficulty.text())
                == 0):
            if self.config.get(
                    'bitmessagesettings',
                    'maxacceptablepayloadlengthextrabytes'
            ) != str(
                    int(
                        float(self.lineEditMaxAcceptableSmallMessageDifficulty.
                              text()) *
                        defaults.networkDefaultPayloadLengthExtraBytes)):
                # the user changed the max acceptable small message difficulty
                acceptableDifficultyChanged = True
                self.config.set(
                    'bitmessagesettings',
                    'maxacceptablepayloadlengthextrabytes',
                    str(
                        int(
                            float(self.
                                  lineEditMaxAcceptableSmallMessageDifficulty.
                                  text()) *
                            defaults.networkDefaultPayloadLengthExtraBytes)))
        if acceptableDifficultyChanged:
            # It might now be possible to send msgs which were previously
            # marked as toodifficult. Let us change them to 'msgqueued'.
            # The singleWorker will try to send them and will again mark
            # them as toodifficult if the receiver's required difficulty
            # is still higher than we are willing to do.
            sqlExecute("UPDATE sent SET status='msgqueued'"
                       " WHERE status='toodifficult'")
            queues.workerQueue.put(('sendmessage', ''))

        stopResendingDefaults = False

        # UI setting to stop trying to send messages after X days/months
        # I'm open to changing this UI to something else if someone has a better idea.
        if self.lineEditDays.text() == '' and self.lineEditMonths.text() == '':
            # We need to handle this special case. Bitmessage has its
            # default behavior. The input is blank/blank
            self.config.set('bitmessagesettings', 'stopresendingafterxdays',
                            '')
            self.config.set('bitmessagesettings', 'stopresendingafterxmonths',
                            '')
            state.maximumLengthOfTimeToBotherResendingMessages = float('inf')
            stopResendingDefaults = True

        try:
            days = float(self.lineEditDays.text())
        except ValueError:
            self.lineEditDays.setText("0")
            days = 0.0
        try:
            months = float(self.lineEditMonths.text())
        except ValueError:
            self.lineEditMonths.setText("0")
            months = 0.0

        if days >= 0 and months >= 0 and not stopResendingDefaults:
            state.maximumLengthOfTimeToBotherResendingMessages = \
                days * 24 * 60 * 60 + months * 60 * 60 * 24 * 365 / 12
            if state.maximumLengthOfTimeToBotherResendingMessages < 432000:
                # If the time period is less than 5 hours, we give
                # zero values to all fields. No message will be sent again.
                QtGui.QMessageBox.about(
                    self, _translate("MainWindow", "Will not resend ever"),
                    _translate(
                        "MainWindow",
                        "Note that the time limit you entered is less"
                        " than the amount of time Bitmessage waits for"
                        " the first resend attempt therefore your"
                        " messages will never be resent."))
                self.config.set('bitmessagesettings',
                                'stopresendingafterxdays', '0')
                self.config.set('bitmessagesettings',
                                'stopresendingafterxmonths', '0')
                state.maximumLengthOfTimeToBotherResendingMessages = 0.0
            else:
                self.config.set('bitmessagesettings',
                                'stopresendingafterxdays', str(days))
                self.config.set('bitmessagesettings',
                                'stopresendingafterxmonths', str(months))

        self.config.save()

        if self.net_restart_needed:
            self.net_restart_needed = False
            self.config.setTemp('bitmessagesettings', 'dontconnect', 'true')
            self.timer.singleShot(
                5000, lambda: self.config.setTemp('bitmessagesettings',
                                                  'dontconnect', 'false'))

        self.parent.updateStartOnLogon()

        if (state.appdata != paths.lookupExeFolder()
                and self.checkBoxPortableMode.isChecked()):
            # If we are NOT using portable mode now but the user selected
            # that we should...
            # Write the keys.dat file to disk in the new location
            sqlStoredProcedure('movemessagstoprog')
            with open(paths.lookupExeFolder() + 'keys.dat',
                      'wb') as configfile:
                self.config.write(configfile)
            # Write the knownnodes.dat file to disk in the new location
            knownnodes.saveKnownNodes(paths.lookupExeFolder())
            os.remove(state.appdata + 'keys.dat')
            os.remove(state.appdata + 'knownnodes.dat')
            previousAppdataLocation = state.appdata
            state.appdata = paths.lookupExeFolder()
            debug.resetLogging()
            try:
                os.remove(previousAppdataLocation + 'debug.log')
                os.remove(previousAppdataLocation + 'debug.log.1')
            except Exception:
                pass

        if (state.appdata == paths.lookupExeFolder()
                and not self.checkBoxPortableMode.isChecked()):
            # If we ARE using portable mode now but the user selected
            # that we shouldn't...
            state.appdata = paths.lookupAppdataFolder()
            if not os.path.exists(state.appdata):
                os.makedirs(state.appdata)
            sqlStoredProcedure('movemessagstoappdata')
            # Write the keys.dat file to disk in the new location
            self.config.save()
            # Write the knownnodes.dat file to disk in the new location
            knownnodes.saveKnownNodes(state.appdata)
            os.remove(paths.lookupExeFolder() + 'keys.dat')
            os.remove(paths.lookupExeFolder() + 'knownnodes.dat')
            debug.resetLogging()
            try:
                os.remove(paths.lookupExeFolder() + 'debug.log')
                os.remove(paths.lookupExeFolder() + 'debug.log.1')
            except Exception:
                pass