def send(self, fromAddress, toAddress, subject, message):
        status, addressVersionNumber, streamNumber, ripe = decodeAddress(toAddress)
        stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel')
        ackdata = genAckPayload(streamNumber, stealthLevel)
        t = ()
        sqlExecute(
            '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            '',
            toAddress,
            ripe,
            fromAddress,
            subject,
            message,
            ackdata,
            int(time.time()), # sentTime (this will never change)
            int(time.time()), # lastActionTime
            0, # sleepTill time. This will get set when the POW gets done.
            'msgqueued',
            0, # retryNumber
            'sent', # folder
            2, # encodingtype
            min(BMConfigParser().getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
        )

        queues.workerQueue.put(('sendmessage', toAddress))
Beispiel #2
0
 def HandleTrashSentMessageByAckDAta(self, params):
     # This API method should only be used when msgid is not available
     if len(params) == 0:
         raise APIError(0, 'I need parameters!')
     ackdata = self._decode(params[0], "hex")
     sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata)
     return 'Trashed sent message (assuming message existed).'
Beispiel #3
0
    def send(self, fromAddress, toAddress, subject, message):
        """Send a bitmessage"""
        # pylint: disable=arguments-differ
        streamNumber, ripe = decodeAddress(toAddress)[2:]
        stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings',
                                                   'ackstealthlevel')
        ackdata = genAckPayload(streamNumber, stealthLevel)
        sqlExecute(
            '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            '',
            toAddress,
            ripe,
            fromAddress,
            subject,
            message,
            ackdata,
            int(time.time()),  # sentTime (this will never change)
            int(time.time()),  # lastActionTime
            0,  # sleepTill time. This will get set when the POW gets done.
            'msgqueued',
            0,  # retryNumber
            'sent',  # folder
            2,  # encodingtype
            # not necessary to have a TTL higher than 2 days
            min(BMConfigParser().getint('bitmessagesettings', 'ttl'),
                86400 * 2))

        queues.workerQueue.put(('sendmessage', toAddress))
Beispiel #4
0
 def HandleAddSubscription(self, params):
     if len(params) == 0:
         raise APIError(0, 'I need parameters!')
     if len(params) == 1:
         address, = params
         label = ''
     if len(params) == 2:
         address, label = params
         label = self._decode(label, "base64")
         try:
             unicode(label, 'utf-8')
         except:
             raise APIError(17, 'Label is not valid UTF-8 data.')
     if len(params) > 2:
         raise APIError(0, 'I need either 1 or 2 parameters!')
     address = addBMIfNotPresent(address)
     self._verifyAddress(address)
     # First we must check to see if the address is already in the
     # subscriptions list.
     queryreturn = sqlQuery("SELECT * FROM subscriptions WHERE address=?",
                            address)
     if queryreturn != []:
         raise APIError(16, 'You are already subscribed to that address.')
     sqlExecute("INSERT INTO subscriptions VALUES (?,?,?)", label, address,
                True)
     shared.reloadBroadcastSendersForWhichImWatching()
     queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
     queues.UISignalQueue.put(('rerenderSubscriptions', ''))
     return 'Added subscription.'
    def send(self):
        """Override the send method for gateway accounts"""

        # pylint: disable=unused-variable
        status, addressVersionNumber, streamNumber, ripe = decodeAddress(
            self.toAddress)
        stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings',
                                                   'ackstealthlevel')
        ackdata = genAckPayload(streamNumber, stealthLevel)
        sqlExecute(
            '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            '',
            self.toAddress,
            ripe,
            self.fromAddress,
            self.subject,
            self.message,
            ackdata,
            int(time.time()),  # sentTime (this will never change)
            int(time.time()),  # lastActionTime
            0,  # sleepTill time. This will get set when the POW gets done.
            'msgqueued',
            0,  # retryNumber
            'sent',  # folder
            2,  # encodingtype
            # not necessary to have a TTL higher than 2 days
            min(BMConfigParser().getint('bitmessagesettings', 'ttl'),
                86400 * 2))

        queues.workerQueue.put(('sendmessage', self.toAddress))
Beispiel #6
0
    def send(self, fromAddress, toAddress, subject, message):
        status, addressVersionNumber, streamNumber, ripe = decodeAddress(
            toAddress)
        ackdata = OpenSSL.rand(32)
        t = ()
        sqlExecute(
            '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            '',
            toAddress,
            ripe,
            fromAddress,
            subject,
            message,
            ackdata,
            int(time.time()),  # sentTime (this will never change)
            int(time.time()),  # lastActionTime
            0,  # sleepTill time. This will get set when the POW gets done.
            'msgqueued',
            0,  # retryNumber
            'sent',  # folder
            2,  # encodingtype
            min(BMConfigParser().getint('bitmessagesettings', 'ttl'),
                86400 * 2)  # not necessary to have a TTL higher than 2 days
        )

        queues.workerQueue.put(('sendmessage', toAddress))
Beispiel #7
0
 def clean(self):
     """Free memory / perform garbage collection"""
     with self.lock:
         sqlExecute('DELETE FROM inventory WHERE expirestime<?',
                    int(time.time()) - (60 * 60 * 3))
         self._objects.clear()
         for objectHash, value in self._inventory.items():
             self._objects[objectHash] = value.stream
Beispiel #8
0
def checkAddressBook(myapp):
    sqlExecute('DELETE from addressbook WHERE address=?', OLD_SUPPORT_ADDRESS)
    queryreturn = sqlQuery('SELECT * FROM addressbook WHERE address=?',
                           SUPPORT_ADDRESS)
    if queryreturn == []:
        sqlExecute('INSERT INTO addressbook VALUES (?,?)',
                   SUPPORT_LABEL.toUtf8(), SUPPORT_ADDRESS)
        myapp.rerenderAddressBook()
Beispiel #9
0
 def tableWidgetBlacklistItemChanged(self, item):
     if item.column() == 0:
         addressitem = self.tableWidgetBlacklist.item(item.row(), 1)
         if isinstance(addressitem, QtGui.QTableWidgetItem):
             if self.radioButtonBlacklist.isChecked():
                 sqlExecute('''UPDATE blacklist SET label=? WHERE address=?''',
                         str(item.text()), str(addressitem.text()))
             else:
                 sqlExecute('''UPDATE whitelist SET label=? WHERE address=?''',
                         str(item.text()), str(addressitem.text()))
Beispiel #10
0
 def HandleDeleteSubscription(self, params):
     if len(params) != 1:
         raise APIError(0, 'I need 1 parameter!')
     address, = params
     address = addBMIfNotPresent(address)
     sqlExecute('''DELETE FROM subscriptions WHERE address=?''', address)
     shared.reloadBroadcastSendersForWhichImWatching()
     queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
     queues.UISignalQueue.put(('rerenderSubscriptions', ''))
     return 'Deleted subscription if it existed.'
Beispiel #11
0
    def HandleTrashMessage(self, params):
        if len(params) == 0:
            raise APIError(0, 'I need parameters!')
        msgid = self._decode(params[0], "hex")

        # Trash if in inbox table
        helper_inbox.trash(msgid)
        # Trash if in sent table
        sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
        return 'Trashed message (assuming message existed).'
def resendMsg(ackdata):
    logger.debug(
        'It has been a long time and we haven\'t heard an acknowledgement'
        ' to our msg. Sending again.')
    sqlExecute('''UPDATE sent SET status='msgqueued' WHERE ackdata=?''',
               ackdata)
    queues.workerQueue.put(('sendmessage', ''))
    queues.UISignalQueue.put(
        ('updateStatusBar',
         'Doing work necessary to again attempt to deliver a message...'))
Beispiel #13
0
 def setData(self, column, role, value):
     if role == QtCore.Qt.EditRole:
         if isinstance(value, QtCore.QVariant):
             label = str(value.toString().toUtf8()).decode(
                 'utf-8', 'ignore')
         else:
             label = unicode(value, 'utf-8', 'ignore')
         sqlExecute('''UPDATE subscriptions SET label=? WHERE address=?''',
                    label, self.address)
     return super(Ui_SubscriptionWidget, self).setData(column, role, value)
Beispiel #14
0
 def HandleDeleteAddressBookEntry(self, params):
     if len(params) != 1:
         raise APIError(0, "I need an address")
     address, = params
     address = addBMIfNotPresent(address)
     self._verifyAddress(address)
     sqlExecute('DELETE FROM addressbook WHERE address=?', address)
     queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
     queues.UISignalQueue.put(('rerenderMessagelistToLabels', ''))
     queues.UISignalQueue.put(('rerenderAddressBook', ''))
     return "Deleted address book entry for %s if it existed" % address
 def click_pushButtonAddBlacklist(self):
     self.NewBlacklistDialogInstance = AddAddressDialog(self)
     if self.NewBlacklistDialogInstance.exec_():
         if self.NewBlacklistDialogInstance.labelAddressCheck.text() == \
                 _translate("MainWindow", "Address is valid."):
             address = addBMIfNotPresent(
                 str(self.NewBlacklistDialogInstance.lineEditAddress.text())
             )
             # First we must check to see if the address is already in the
             # address book. The user cannot add it again or else it will
             # cause problems when updating and deleting the entry.
             t = (address, )
             if BMConfigParser().get('bitmessagesettings',
                                     'blackwhitelist') == 'black':
                 sql = '''select * from blacklist where address=?'''
             else:
                 sql = '''select * from whitelist where address=?'''
             queryreturn = sqlQuery(sql, *t)
             if queryreturn == []:
                 self.tableWidgetBlacklist.setSortingEnabled(False)
                 self.tableWidgetBlacklist.insertRow(0)
                 newItem = QtGui.QTableWidgetItem(
                     unicode(
                         self.NewBlacklistDialogInstance.lineEditLabel.text(
                         ).toUtf8(), 'utf-8'))
                 newItem.setIcon(avatarize(address))
                 self.tableWidgetBlacklist.setItem(0, 0, newItem)
                 newItem = QtGui.QTableWidgetItem(address)
                 newItem.setFlags(QtCore.Qt.ItemIsSelectable
                                  | QtCore.Qt.ItemIsEnabled)
                 self.tableWidgetBlacklist.setItem(0, 1, newItem)
                 self.tableWidgetBlacklist.setSortingEnabled(True)
                 t = (str(self.NewBlacklistDialogInstance.lineEditLabel.
                          text().toUtf8()), address, True)
                 if BMConfigParser().get('bitmessagesettings',
                                         'blackwhitelist') == 'black':
                     sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
                 else:
                     sql = '''INSERT INTO whitelist VALUES (?,?,?)'''
                 sqlExecute(sql, *t)
             else:
                 UISignalQueue.put(
                     ('updateStatusBar',
                      _translate(
                          "MainWindow",
                          "Error: You cannot add the same address to your"
                          " list twice. Perhaps rename the existing one"
                          " if you want.")))
         else:
             UISignalQueue.put(
                 ('updateStatusBar',
                  _translate(
                      "MainWindow",
                      "The address you entered was invalid. Ignoring it.")))
Beispiel #16
0
 def sendMessages(self, address):
     """
     This function is called by the possibleNewPubkey function when
     that function sees that we now have the necessary pubkey
     to send one or more messages.
     """
     logger.info('We have been awaiting the arrival of this pubkey.')
     sqlExecute(
         '''UPDATE sent SET status='doingmsgpow', retrynumber=0 WHERE toaddress=? AND (status='awaitingpubkey' or status='doingpubkeypow') AND folder='sent' ''',
         address)
     queues.workerQueue.put(('sendmessage', ''))
Beispiel #17
0
    def send(self):

        fromAddress = "BM-2cXxMHUdyqGESttuTwzQUKCFLZNfVjoon2"
        toAddress = "BM-2cWF9TNuK5zfgnB6z4F7JJ5KizBRivDevp"
        message = self.ids.user_input.text
        subject = 'Test'
        print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4")
        print("################################################################")
        encoding = 3
        print("message: ", self.ids.user_input.text)
        sendMessageToPeople = True
        if sendMessageToPeople:
            if toAddress != '':
                status, addressVersionNumber, streamNumber, ripe = decodeAddress(toAddress)
                if status == 'success':
                    toAddress = addBMIfNotPresent(toAddress)

                    if addressVersionNumber > 4 or addressVersionNumber <= 1:
                        print("addressVersionNumber > 4 or addressVersionNumber <= 1")
                    if streamNumber > 1 or streamNumber == 0:
                        print("streamNumber > 1 or streamNumber == 0")
                    if statusIconColor == 'red':
                        print("shared.statusIconColor == 'red'")
                    stealthLevel = BMConfigParser().safeGetInt(
                        'bitmessagesettings', 'ackstealthlevel')
                    ackdata = genAckPayload(streamNumber, stealthLevel)
                    t = ()
                    sqlLookup = sqlThread()
                    sqlLookup.daemon = False  # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
                    sqlLookup.start()
                    sqlExecute(
                        '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
                        '',
                        toAddress,
                        ripe,
                        fromAddress,
                        subject,
                        message,
                        ackdata,
                        int(time.time()), # sentTime (this will never change)
                        int(time.time()), # lastActionTime
                        0, # sleepTill time. This will get set when the POW gets done.
                        'msgqueued',
                        0, # retryNumber
                        'sent', # folder
                        encoding, # encodingtype
                        BMConfigParser().getint('bitmessagesettings', 'ttl')
                        )
                    print("sqlExecute successfully #######################")

                    aa = App.get_running_app()
                    aa.Exit()
Beispiel #18
0
 def on_action_BlacklistDisable(self):
     currentRow = self.tableWidgetBlacklist.currentRow()
     addressAtCurrentRow = self.tableWidgetBlacklist.item(
         currentRow, 1).text()
     self.tableWidgetBlacklist.item(
         currentRow, 0).setTextColor(QtGui.QColor(128, 128, 128))
     self.tableWidgetBlacklist.item(
         currentRow, 1).setTextColor(QtGui.QColor(128, 128, 128))
     if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
         sqlExecute(
             '''UPDATE blacklist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow))
     else:
         sqlExecute(
             '''UPDATE whitelist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow))
Beispiel #19
0
 def on_action_BlacklistDelete(self):
     currentRow = self.tableWidgetBlacklist.currentRow()
     labelAtCurrentRow = self.tableWidgetBlacklist.item(currentRow,
                                                        0).text().toUtf8()
     addressAtCurrentRow = self.tableWidgetBlacklist.item(currentRow,
                                                          1).text()
     if BMConfigParser().get('bitmessagesettings',
                             'blackwhitelist') == 'black':
         sqlExecute('''DELETE FROM blacklist WHERE label=? AND address=?''',
                    str(labelAtCurrentRow), str(addressAtCurrentRow))
     else:
         sqlExecute('''DELETE FROM whitelist WHERE label=? AND address=?''',
                    str(labelAtCurrentRow), str(addressAtCurrentRow))
     self.tableWidgetBlacklist.removeRow(currentRow)
Beispiel #20
0
 def checkackdata(self, data):
     # Let's check whether this is a message acknowledgement bound for us.
     if len(data) < 32:
         return
     if data[-32:] in shared.ackdataForWhichImWatching:
         logger.info('This object is an acknowledgement bound for me.')
         del shared.ackdataForWhichImWatching[data[-32:]]
         sqlExecute('UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?',
                    'ackreceived',
                    int(time.time()), 
                    data[-32:])
         queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (data[-32:], tr._translate("MainWindow",'Acknowledgement of the message received %1').arg(l10n.formatTimestamp()))))
     else:
         logger.debug('This object is not an acknowledgement bound for me.')
Beispiel #21
0
 def on_action_BlacklistDelete(self):
     currentRow = self.tableWidgetBlacklist.currentRow()
     labelAtCurrentRow = self.tableWidgetBlacklist.item(
         currentRow, 0).text().toUtf8()
     addressAtCurrentRow = self.tableWidgetBlacklist.item(
         currentRow, 1).text()
     if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
         sqlExecute(
             '''DELETE FROM blacklist WHERE label=? AND address=?''',
             str(labelAtCurrentRow), str(addressAtCurrentRow))
     else:
         sqlExecute(
             '''DELETE FROM whitelist WHERE label=? AND address=?''',
             str(labelAtCurrentRow), str(addressAtCurrentRow))
     self.tableWidgetBlacklist.removeRow(currentRow)
Beispiel #22
0
 def on_action_BlacklistEnable(self):
     currentRow = self.tableWidgetBlacklist.currentRow()
     addressAtCurrentRow = self.tableWidgetBlacklist.item(currentRow,
                                                          1).text()
     self.tableWidgetBlacklist.item(currentRow, 0).setTextColor(
         QtGui.QApplication.palette().text().color())
     self.tableWidgetBlacklist.item(currentRow, 1).setTextColor(
         QtGui.QApplication.palette().text().color())
     if shared.config.get('bitmessagesettings',
                          'blackwhitelist') == 'black':
         sqlExecute('''UPDATE blacklist SET enabled=1 WHERE address=?''',
                    str(addressAtCurrentRow))
     else:
         sqlExecute('''UPDATE whitelist SET enabled=1 WHERE address=?''',
                    str(addressAtCurrentRow))
Beispiel #23
0
 def __init__(self):
     threading.Thread.__init__(self, name="objectProcessor")
     """
     It may be the case that the last time Bitmessage was running, the user
     closed it before it finished processing everything in the
     objectProcessorQueue. Assuming that Bitmessage wasn't closed forcefully,
     it should have saved the data in the queue into the objectprocessorqueue 
     table. Let's pull it out.
     """
     queryreturn = sqlQuery(
         '''SELECT objecttype, data FROM objectprocessorqueue''')
     for row in queryreturn:
         objectType, data = row
         queues.objectProcessorQueue.put((objectType,data))
     sqlExecute('''DELETE FROM objectprocessorqueue''')
     logger.debug('Loaded %s objects from disk into the objectProcessorQueue.' % str(len(queryreturn)))
Beispiel #24
0
 def on_action_BlacklistEnable(self):
     currentRow = self.tableWidgetBlacklist.currentRow()
     addressAtCurrentRow = self.tableWidgetBlacklist.item(
         currentRow, 1).text()
     self.tableWidgetBlacklist.item(
         currentRow, 0).setTextColor(QtGui.QApplication.palette().text().color())
     self.tableWidgetBlacklist.item(
         currentRow, 1).setTextColor(QtGui.QApplication.palette().text().color())
     if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
         sqlExecute(
             '''UPDATE blacklist SET enabled=1 WHERE address=?''',
             str(addressAtCurrentRow))
     else:
         sqlExecute(
             '''UPDATE whitelist SET enabled=1 WHERE address=?''',
             str(addressAtCurrentRow))
Beispiel #25
0
 def __init__(self):
     # It may be the case that the last time Bitmessage was running,
     # the user closed it before it finished processing everything in the
     # objectProcessorQueue. Assuming that Bitmessage wasn't closed
     # forcefully, it should have saved the data in the queue into the
     # objectprocessorqueue table. Let's pull it out.
     threading.Thread.__init__(self, name="objectProcessor")
     queryreturn = sqlQuery(
         '''SELECT objecttype, data FROM objectprocessorqueue''')
     for row in queryreturn:
         objectType, data = row
         queues.objectProcessorQueue.put((objectType, data))
     sqlExecute('''DELETE FROM objectprocessorqueue''')
     logger.debug(
         'Loaded %s objects from disk into the objectProcessorQueue.',
         len(queryreturn))
     self._ack_obj = bmproto.BMStringParser()
     self.successfullyDecryptMessageTimings = []
Beispiel #26
0
    def HandleAddAddressBookEntry(self, params):
        if len(params) != 2:
            raise APIError(0, "I need label and address")
        address, label = params
        label = self._decode(label, "base64")
        address = addBMIfNotPresent(address)
        self._verifyAddress(address)
        queryreturn = sqlQuery(
            "SELECT address FROM addressbook WHERE address=?", address)
        if queryreturn != []:
            raise APIError(
                16, 'You already have this address in your address book.')

        sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address)
        queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
        queues.UISignalQueue.put(('rerenderMessagelistToLabels', ''))
        queues.UISignalQueue.put(('rerenderAddressBook', ''))
        return "Added address %s to address book" % address
Beispiel #27
0
    def send(self):
        """Send message from one address to another."""
        fromAddress = self.ids.spinner_id.text
        # For now we are using static address i.e we are not using recipent field value.
        toAddress = "BM-2cWyUfBdY2FbgyuCb7abFZ49JYxSzUhNFe"
        message = self.ids.message.text
        subject = self.ids.subject.text
        encoding = 3
        print("message: ", self.ids.message.text)
        sendMessageToPeople = True
        if sendMessageToPeople:
            if toAddress != '':
                status, addressVersionNumber, streamNumber, ripe = decodeAddress(
                    toAddress)
                if status == 'success':
                    toAddress = addBMIfNotPresent(toAddress)

                    if addressVersionNumber > 4 or addressVersionNumber <= 1:
                        print(
                            "addressVersionNumber > 4 or addressVersionNumber <= 1"
                        )
                    if streamNumber > 1 or streamNumber == 0:
                        print("streamNumber > 1 or streamNumber == 0")
                    if statusIconColor == 'red':
                        print("shared.statusIconColor == 'red'")
                    stealthLevel = BMConfigParser().safeGetInt(
                        'bitmessagesettings', 'ackstealthlevel')
                    ackdata = genAckPayload(streamNumber, stealthLevel)
                    t = ()
                    sqlExecute(
                        '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
                        '', toAddress, ripe, fromAddress,
                        subject, message, ackdata, int(time.time()),
                        int(time.time()), 0, 'msgqueued', 0, 'sent', encoding,
                        BMConfigParser().getint('bitmessagesettings', 'ttl'))
                    toLabel = ''
                    queues.workerQueue.put(('sendmessage', toAddress))
                    print(
                        "sqlExecute successfully #####    ##################")
                    self.ids.message.text = ''
                    self.ids.spinner_id.text = '<select>'
                    self.ids.subject.text = ''
                    self.ids.recipent.text = ''
                    return None
Beispiel #28
0
 def HandleGetInboxMessageById(self, params):
     if len(params) == 0:
         raise APIError(0, 'I need parameters!')
     elif len(params) == 1:
         msgid = self._decode(params[0], "hex")
     elif len(params) >= 2:
         msgid = self._decode(params[0], "hex")
         readStatus = params[1]
         if not isinstance(readStatus, bool):
             raise APIError(
                 23, 'Bool expected in readStatus, saw %s instead.' %
                 type(readStatus))
         queryreturn = sqlQuery("SELECT read FROM inbox WHERE msgid=?",
                                msgid)
         # UPDATE is slow, only update if status is different
         if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus:
             sqlExecute("UPDATE inbox set read = ? WHERE msgid=?",
                        readStatus, msgid)
             queues.UISignalQueue.put(('changedInboxUnread', None))
     queryreturn = sqlQuery(
         "SELECT msgid, toaddress, fromaddress, subject, received, message,"
         " encodingtype, read FROM inbox WHERE msgid=?", msgid)
     data = '{"inboxMessage":['
     for row in queryreturn:
         msgid, toAddress, fromAddress, subject, received, message, \
             encodingtype, read = row
         subject = shared.fixPotentiallyInvalidUTF8Data(subject)
         message = shared.fixPotentiallyInvalidUTF8Data(message)
         data += json.dumps(
             {
                 'msgid': hexlify(msgid),
                 'toAddress': toAddress,
                 'fromAddress': fromAddress,
                 'subject': base64.b64encode(subject),
                 'message': base64.b64encode(message),
                 'encodingType': encodingtype,
                 'receivedTime': received,
                 'read': read
             },
             indent=4,
             separators=(',', ': '))
         data += ']}'
         return data
def resendPubkeyRequest(address):
    logger.debug(
        'It has been a long time and we haven\'t heard a response to our'
        ' getpubkey request. Sending again.')
    try:
        # We need to take this entry out of the neededPubkeys structure
        # because the queues.workerQueue checks to see whether the entry
        # is already present and will not do the POW and send the message
        # because it assumes that it has already done it recently.
        del state.neededPubkeys[address]
    except:
        pass

    queues.UISignalQueue.put(
        ('updateStatusBar',
         'Doing work necessary to again attempt to request a public key...'))
    sqlExecute('''UPDATE sent SET status='msgqueued' WHERE toaddress=?''',
               address)
    queues.workerQueue.put(('sendmessage', ''))
Beispiel #30
0
 def click_pushButtonAddBlacklist(self):
     self.NewBlacklistDialogInstance = AddAddressDialog(self)
     if self.NewBlacklistDialogInstance.exec_():
         if self.NewBlacklistDialogInstance.ui.labelAddressCheck.text() == _translate("MainWindow", "Address is valid."):
             address = addBMIfNotPresent(str(
                 self.NewBlacklistDialogInstance.ui.lineEditAddress.text()))
             # First we must check to see if the address is already in the
             # address book. The user cannot add it again or else it will
             # cause problems when updating and deleting the entry.
             t = (address,)
             if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
                 sql = '''select * from blacklist where address=?'''
             else:
                 sql = '''select * from whitelist where address=?'''
             queryreturn = sqlQuery(sql,*t)
             if queryreturn == []:
                 self.tableWidgetBlacklist.setSortingEnabled(False)
                 self.tableWidgetBlacklist.insertRow(0)
                 newItem = QtGui.QTableWidgetItem(unicode(
                     self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8(), 'utf-8'))
                 newItem.setIcon(avatarize(address))
                 self.tableWidgetBlacklist.setItem(0, 0, newItem)
                 newItem = QtGui.QTableWidgetItem(address)
                 newItem.setFlags(
                     QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                 self.tableWidgetBlacklist.setItem(0, 1, newItem)
                 self.tableWidgetBlacklist.setSortingEnabled(True)
                 t = (str(self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8()), address, True)
                 if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
                     sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
                 else:
                     sql = '''INSERT INTO whitelist VALUES (?,?,?)'''
                 sqlExecute(sql, *t)
             else:
                 self.statusBar().showMessage(_translate(
                     "MainWindow", "Error: You cannot add the same address to your list twice. Perhaps rename the existing one if you want."))
         else:
             self.statusBar().showMessage(_translate(
                 "MainWindow", "The address you entered was invalid. Ignoring it."))
Beispiel #31
0
 def setData(self, role, value):
     """Set data"""
     if role == QtCore.Qt.EditRole:
         self.label = str(value.toString().toUtf8(
         ) if isinstance(value, QtCore.QVariant) else value)
         if self.type in (AccountMixin.NORMAL, AccountMixin.MAILINGLIST,
                          AccountMixin.CHAN):
             try:
                 BMConfigParser().get(self.address, 'label')
                 BMConfigParser().set(self.address, 'label', self.label)
                 BMConfigParser().save()
             except:
                 sqlExecute(
                     '''UPDATE addressbook set label=? WHERE address=?''',
                     self.label, self.address)
         elif self.type == AccountMixin.SUBSCRIPTION:
             sqlExecute(
                 '''UPDATE subscriptions set label=? WHERE address=?''',
                 self.label, self.address)
         else:
             pass
     return super(Ui_AddressBookWidgetItem, self).setData(role, value)
Beispiel #32
0
    def send(self, fromAddress, toAddress, subject, message):
        status, addressVersionNumber, streamNumber, ripe = decodeAddress(toAddress)
        ackdata = OpenSSL.rand(32)
        t = ()
        sqlExecute(
            '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            '',
            toAddress,
            ripe,
            fromAddress,
            subject,
            message,
            ackdata,
            int(time.time()), # sentTime (this will never change)
            int(time.time()), # lastActionTime
            0, # sleepTill time. This will get set when the POW gets done.
            'msgqueued',
            0, # retryNumber
            'sent', # folder
            2, # encodingtype
            min(shared.config.getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
        )

        shared.workerQueue.put(('sendmessage', toAddress))
Beispiel #33
0
def decryptAndCheckPubkeyPayload(data, address):
    """
    Version 4 pubkeys are encrypted. This function is run when we already have the 
    address to which we want to try to send a message. The 'data' may come either
    off of the wire or we might have had it already in our inventory when we tried
    to send a msg to this particular address. 
    """
    try:
        status, addressVersion, streamNumber, ripe = decodeAddress(address)

        readPosition = 20  # bypass the nonce, time, and object type
        embeddedAddressVersion, varintLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += varintLength
        embeddedStreamNumber, varintLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += varintLength
        storedData = data[
            20:
            readPosition]  # We'll store the address version and stream number (and some more) in the pubkeys table.

        if addressVersion != embeddedAddressVersion:
            logger.info(
                'Pubkey decryption was UNsuccessful due to address version mismatch.'
            )
            return 'failed'
        if streamNumber != embeddedStreamNumber:
            logger.info(
                'Pubkey decryption was UNsuccessful due to stream number mismatch.'
            )
            return 'failed'

        tag = data[readPosition:readPosition + 32]
        readPosition += 32
        signedData = data[
            8:
            readPosition]  # the time through the tag. More data is appended onto signedData below after the decryption.
        encryptedData = data[readPosition:]

        # Let us try to decrypt the pubkey
        toAddress, cryptorObject = state.neededPubkeys[tag]
        if toAddress != address:
            logger.critical(
                'decryptAndCheckPubkeyPayload failed due to toAddress mismatch. This is very peculiar. toAddress: %s, address %s',
                toAddress, address)
            # the only way I can think that this could happen is if someone encodes their address data two different ways.
            # That sort of address-malleability should have been caught by the UI or API and an error given to the user.
            return 'failed'
        try:
            decryptedData = cryptorObject.decrypt(encryptedData)
        except:
            # Someone must have encrypted some data with a different key
            # but tagged it with a tag for which we are watching.
            logger.info('Pubkey decryption was unsuccessful.')
            return 'failed'

        readPosition = 0
        bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        publicSigningKey = '\x04' + decryptedData[readPosition:readPosition +
                                                  64]
        readPosition += 64
        publicEncryptionKey = '\x04' + decryptedData[
            readPosition:readPosition + 64]
        readPosition += 64
        specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += specifiedNonceTrialsPerByteLength
        specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += specifiedPayloadLengthExtraBytesLength
        storedData += decryptedData[:readPosition]
        signedData += decryptedData[:readPosition]
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += signatureLengthLength
        signature = decryptedData[readPosition:readPosition + signatureLength]

        if highlevelcrypto.verify(signedData, signature,
                                  hexlify(publicSigningKey)):
            logger.info(
                'ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
        else:
            logger.info(
                'ECDSA verify failed (within decryptAndCheckPubkeyPayload)')
            return 'failed'

        sha = hashlib.new('sha512')
        sha.update(publicSigningKey + publicEncryptionKey)
        ripeHasher = hashlib.new('ripemd160')
        ripeHasher.update(sha.digest())
        embeddedRipe = ripeHasher.digest()

        if embeddedRipe != ripe:
            # Although this pubkey object had the tag were were looking for and was
            # encrypted with the correct encryption key, it doesn't contain the
            # correct pubkeys. Someone is either being malicious or using buggy software.
            logger.info(
                'Pubkey decryption was UNsuccessful due to RIPE mismatch.')
            return 'failed'

        # Everything checked out. Insert it into the pubkeys table.

        logger.info(
            'within decryptAndCheckPubkeyPayload, addressVersion: %s, streamNumber: %s \n\
                    ripe %s\n\
                    publicSigningKey in hex: %s\n\
                    publicEncryptionKey in hex: %s', addressVersion,
            streamNumber, hexlify(ripe), hexlify(publicSigningKey),
            hexlify(publicEncryptionKey))

        t = (address, addressVersion, storedData, int(time.time()), 'yes')
        sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
        return 'successful'
    except varintDecodeError as e:
        logger.info(
            'Pubkey decryption was UNsuccessful due to a malformed varint.')
        return 'failed'
    except Exception as e:
        logger.critical(
            'Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s',
            traceback.format_exc())
        return 'failed'
Beispiel #34
0
    def _handle_request(self, method, params):
        if method == 'helloWorld':
            (a, b) = params
            return a + '-' + b
        elif method == 'add':
            (a, b) = params
            return a + b
        elif method == 'statusBar':
            message, = params
            shared.UISignalQueue.put(('updateStatusBar', message))
        elif method == 'listAddresses' or method == 'listAddresses2':
            data = '{"addresses":['
            configSections = shared.config.sections()
            for addressInKeysFile in configSections:
                if addressInKeysFile != 'bitmessagesettings':
                    status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
                        addressInKeysFile)
                    if len(data) > 20:
                        data += ','
                    if shared.config.has_option(addressInKeysFile, 'chan'):
                        chan = shared.config.getboolean(addressInKeysFile, 'chan')
                    else:
                        chan = False
                    label = shared.config.get(addressInKeysFile, 'label')
                    if method == 'listAddresses2':
                        label = label.encode('base64')
                    data += json.dumps({'label': label, 'address': addressInKeysFile, 'stream':
                                        streamNumber, 'enabled': shared.config.getboolean(addressInKeysFile, 'enabled'), 'chan': chan}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'listAddressBookEntries' or method == 'listAddressbook': # the listAddressbook alias should be removed eventually.
            queryreturn = sqlQuery('''SELECT label, address from addressbook''')
            data = '{"addresses":['
            for row in queryreturn:
                label, address = row
                label = shared.fixPotentiallyInvalidUTF8Data(label)
                if len(data) > 20:
                    data += ','
                data += json.dumps({'label':label.encode('base64'), 'address': address}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'addAddressBookEntry' or method == 'addAddressbook': # the addAddressbook alias should be deleted eventually.
            if len(params) != 2:
                raise APIError(0, "I need label and address")
            address, label = params
            label = self._decode(label, "base64")
            address = addBMIfNotPresent(address)
            self._verifyAddress(address)
            queryreturn = sqlQuery("SELECT address FROM addressbook WHERE address=?", address)
            if queryreturn != []:
                raise APIError(16, 'You already have this address in your address book.')

            sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address)
            shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
            shared.UISignalQueue.put(('rerenderSentToLabels',''))
            shared.UISignalQueue.put(('rerenderAddressBook',''))
            return "Added address %s to address book" % address
        elif method == 'deleteAddressBookEntry' or method == 'deleteAddressbook': # The deleteAddressbook alias should be deleted eventually.
            if len(params) != 1:
                raise APIError(0, "I need an address")
            address, = params
            address = addBMIfNotPresent(address)
            self._verifyAddress(address)
            sqlExecute('DELETE FROM addressbook WHERE address=?', address)
            shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
            shared.UISignalQueue.put(('rerenderSentToLabels',''))
            shared.UISignalQueue.put(('rerenderAddressBook',''))
            return "Deleted address book entry for %s if it existed" % address
        elif method == 'createRandomAddress':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            elif len(params) == 1:
                label, = params
                eighteenByteRipe = False
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 2:
                label, eighteenByteRipe = params
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 3:
                label, eighteenByteRipe, totalDifficulty = params
                nonceTrialsPerByte = int(
                    shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 4:
                label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
                nonceTrialsPerByte = int(
                    shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
                payloadLengthExtraBytes = int(
                    shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
            else:
                raise APIError(0, 'Too many parameters!')
            label = self._decode(label, "base64")
            try:
                unicode(label, 'utf-8')
            except:
                raise APIError(17, 'Label is not valid UTF-8 data.')
            shared.apiAddressGeneratorReturnQueue.queue.clear()
            streamNumberForAddress = 1
            shared.addressGeneratorQueue.put((
                'createRandomAddress', 4, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
            return shared.apiAddressGeneratorReturnQueue.get()
        elif method == 'createDeterministicAddresses':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            elif len(params) == 1:
                passphrase, = params
                numberOfAddresses = 1
                addressVersionNumber = 0
                streamNumber = 0
                eighteenByteRipe = False
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 2:
                passphrase, numberOfAddresses = params
                addressVersionNumber = 0
                streamNumber = 0
                eighteenByteRipe = False
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 3:
                passphrase, numberOfAddresses, addressVersionNumber = params
                streamNumber = 0
                eighteenByteRipe = False
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 4:
                passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params
                eighteenByteRipe = False
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 5:
                passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params
                nonceTrialsPerByte = shared.config.get(
                    'bitmessagesettings', 'defaultnoncetrialsperbyte')
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 6:
                passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params
                nonceTrialsPerByte = int(
                    shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
                payloadLengthExtraBytes = shared.config.get(
                    'bitmessagesettings', 'defaultpayloadlengthextrabytes')
            elif len(params) == 7:
                passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
                nonceTrialsPerByte = int(
                    shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
                payloadLengthExtraBytes = int(
                    shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
            else:
                raise APIError(0, 'Too many parameters!')
            if len(passphrase) == 0:
                raise APIError(1, 'The specified passphrase is blank.')
            if not isinstance(eighteenByteRipe, bool):
                raise APIError(23, 'Bool expected in eighteenByteRipe, saw %s instead' % type(eighteenByteRipe))
            passphrase = self._decode(passphrase, "base64")
            if addressVersionNumber == 0:  # 0 means "just use the proper addressVersionNumber"
                addressVersionNumber = 4
            if addressVersionNumber != 3 and addressVersionNumber != 4:
                raise APIError(2,'The address version number currently must be 3, 4, or 0 (which means auto-select). ' + addressVersionNumber + ' isn\'t supported.')
            if streamNumber == 0:  # 0 means "just use the most available stream"
                streamNumber = 1
            if streamNumber != 1:
                raise APIError(3,'The stream number must be 1 (or 0 which means auto-select). Others aren\'t supported.')
            if numberOfAddresses == 0:
                raise APIError(4, 'Why would you ask me to generate 0 addresses for you?')
            if numberOfAddresses > 999:
                raise APIError(5, 'You have (accidentally?) specified too many addresses to make. Maximum 999. This check only exists to prevent mischief; if you really want to create more addresses than this, contact the Bitmessage developers and we can modify the check or you can do it yourself by searching the source code for this message.')
            shared.apiAddressGeneratorReturnQueue.queue.clear()
            logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses)
            shared.addressGeneratorQueue.put(
                ('createDeterministicAddresses', addressVersionNumber, streamNumber,
                 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
            data = '{"addresses":['
            queueReturn = shared.apiAddressGeneratorReturnQueue.get()
            for item in queueReturn:
                if len(data) > 20:
                    data += ','
                data += "\"" + item + "\""
            data += ']}'
            return data
        elif method == 'getDeterministicAddress':
            if len(params) != 3:
                raise APIError(0, 'I need exactly 3 parameters.')
            passphrase, addressVersionNumber, streamNumber = params
            numberOfAddresses = 1
            eighteenByteRipe = False
            if len(passphrase) == 0:
                raise APIError(1, 'The specified passphrase is blank.')
            passphrase = self._decode(passphrase, "base64")
            if addressVersionNumber != 3 and addressVersionNumber != 4:
                raise APIError(2, 'The address version number currently must be 3 or 4. ' + addressVersionNumber + ' isn\'t supported.')
            if streamNumber != 1:
                raise APIError(3, ' The stream number must be 1. Others aren\'t supported.')
            shared.apiAddressGeneratorReturnQueue.queue.clear()
            logger.debug('Requesting that the addressGenerator create %s addresses.', numberOfAddresses)
            shared.addressGeneratorQueue.put(
                ('getDeterministicAddress', addressVersionNumber,
                 streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe))
            return shared.apiAddressGeneratorReturnQueue.get()

        elif method == 'createChan':
            if len(params) == 0:
                raise APIError(0, 'I need parameters.')
            elif len(params) == 1:
                passphrase, = params
            passphrase = self._decode(passphrase, "base64")
            if len(passphrase) == 0:
                raise APIError(1, 'The specified passphrase is blank.')
            # It would be nice to make the label the passphrase but it is
            # possible that the passphrase contains non-utf-8 characters.
            try:
                unicode(passphrase, 'utf-8')
                label = str_chan + ' ' + passphrase
            except:
                label = str_chan + ' ' + repr(passphrase)

            addressVersionNumber = 4
            streamNumber = 1
            shared.apiAddressGeneratorReturnQueue.queue.clear()
            logger.debug('Requesting that the addressGenerator create chan %s.', passphrase)
            shared.addressGeneratorQueue.put(('createChan', addressVersionNumber, streamNumber, label, passphrase))
            queueReturn = shared.apiAddressGeneratorReturnQueue.get()
            if len(queueReturn) == 0:
                raise APIError(24, 'Chan address is already present.')
            address = queueReturn[0]
            return address
        elif method == 'joinChan':
            if len(params) < 2:
                raise APIError(0, 'I need two parameters.')
            elif len(params) == 2:
                passphrase, suppliedAddress= params
            passphrase = self._decode(passphrase, "base64")
            if len(passphrase) == 0:
                raise APIError(1, 'The specified passphrase is blank.')
            # It would be nice to make the label the passphrase but it is
            # possible that the passphrase contains non-utf-8 characters.
            try:
                unicode(passphrase, 'utf-8')
                label = str_chan + ' ' + passphrase
            except:
                label = str_chan + ' ' + repr(passphrase)

            status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(suppliedAddress)
            suppliedAddress = addBMIfNotPresent(suppliedAddress)
            shared.apiAddressGeneratorReturnQueue.queue.clear()
            shared.addressGeneratorQueue.put(('joinChan', suppliedAddress, label, passphrase))
            addressGeneratorReturnValue = shared.apiAddressGeneratorReturnQueue.get()

            if addressGeneratorReturnValue == 'chan name does not match address':
                raise APIError(18, 'Chan name does not match address.')
            if len(addressGeneratorReturnValue) == 0:
                raise APIError(24, 'Chan address is already present.')
            #TODO: this variable is not used to anything
            createdAddress = addressGeneratorReturnValue[0] # in case we ever want it for anything.
            return "success"
        elif method == 'leaveChan':
            if len(params) == 0:
                raise APIError(0, 'I need parameters.')
            elif len(params) == 1:
                address, = params
            status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
            address = addBMIfNotPresent(address)
            if not shared.config.has_section(address):
                raise APIError(13, 'Could not find this address in your keys.dat file.')
            if not shared.safeConfigGetBoolean(address, 'chan'):
                raise APIError(25, 'Specified address is not a chan address. Use deleteAddress API call instead.')
            shared.config.remove_section(address)
            with open(shared.appdata + 'keys.dat', 'wb') as configfile:
                shared.config.write(configfile)
            return 'success'

        elif method == 'deleteAddress':
            if len(params) == 0:
                raise APIError(0, 'I need parameters.')
            elif len(params) == 1:
                address, = params
            status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
            address = addBMIfNotPresent(address)
            if not shared.config.has_section(address):
                raise APIError(13, 'Could not find this address in your keys.dat file.')
            shared.config.remove_section(address)
            with open(shared.appdata + 'keys.dat', 'wb') as configfile:
                shared.config.write(configfile)
            shared.UISignalQueue.put(('rerenderInboxFromLabels',''))
            shared.UISignalQueue.put(('rerenderSentToLabels',''))
            shared.reloadMyAddressHashes()
            return 'success'

        elif method == 'getAllInboxMessages':
            queryreturn = sqlQuery(
                '''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox where folder='inbox' ORDER BY received''')
            data = '{"inboxMessages":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid': msgid.encode('hex'), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': subject.encode(
                    'base64'), 'message': message.encode('base64'), 'encodingType': encodingtype, 'receivedTime': received, 'read': read}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getAllInboxMessageIds' or method == 'getAllInboxMessageIDs':
            queryreturn = sqlQuery(
                '''SELECT msgid FROM inbox where folder='inbox' ORDER BY received''')
            data = '{"inboxMessageIds":['
            for row in queryreturn:
                msgid = row[0]
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid': msgid.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getInboxMessageById' or method == 'getInboxMessageByID':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            elif len(params) == 1:
                msgid = self._decode(params[0], "hex")
            elif len(params) >= 2:
                msgid = self._decode(params[0], "hex")
                readStatus = params[1]
                if not isinstance(readStatus, bool):
                    raise APIError(23, 'Bool expected in readStatus, saw %s instead.' % type(readStatus))
                queryreturn = sqlQuery('''SELECT read FROM inbox WHERE msgid=?''', msgid)
                # UPDATE is slow, only update if status is different
                if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus:
                    sqlExecute('''UPDATE inbox set read = ? WHERE msgid=?''', readStatus, msgid)
                    shared.UISignalQueue.put(('changedInboxUnread', None))
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox WHERE msgid=?''', msgid)
            data = '{"inboxMessage":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, received, message, encodingtype, read = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received, 'read': read}, indent=4, separators=(',', ': '))
                data += ']}'
                return data
        elif method == 'getAllSentMessages':
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent where folder='sent' ORDER BY lastactiontime''')
            data = '{"sentMessages":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getAllSentMessageIds' or method == 'getAllSentMessageIDs':
            queryreturn = sqlQuery('''SELECT msgid FROM sent where folder='sent' ORDER BY lastactiontime''')
            data = '{"sentMessageIds":['
            for row in queryreturn:
                msgid = row[0]
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid':msgid.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getInboxMessagesByReceiver' or method == 'getInboxMessagesByAddress': #after some time getInboxMessagesByAddress should be removed
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            toAddress = params[0]
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype FROM inbox WHERE folder='inbox' AND toAddress=?''', toAddress)
            data = '{"inboxMessages":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, received, message, encodingtype = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'receivedTime':received}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getSentMessageById' or method == 'getSentMessageByID':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            msgid = self._decode(params[0], "hex")
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE msgid=?''', msgid)
            data = '{"sentMessage":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
                data += ']}'
                return data
        elif method == 'getSentMessagesByAddress' or method == 'getSentMessagesBySender':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            fromAddress = params[0]
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime''',
                                   fromAddress)
            data = '{"sentMessages":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                if len(data) > 25:
                    data += ','
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getSentMessageByAckData':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            ackData = self._decode(params[0], "hex")
            queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, lastactiontime, message, encodingtype, status, ackdata FROM sent WHERE ackdata=?''',
                                   ackData)
            data = '{"sentMessage":['
            for row in queryreturn:
                msgid, toAddress, fromAddress, subject, lastactiontime, message, encodingtype, status, ackdata = row
                subject = shared.fixPotentiallyInvalidUTF8Data(subject)
                message = shared.fixPotentiallyInvalidUTF8Data(message)
                data += json.dumps({'msgid':msgid.encode('hex'), 'toAddress':toAddress, 'fromAddress':fromAddress, 'subject':subject.encode('base64'), 'message':message.encode('base64'), 'encodingType':encodingtype, 'lastActionTime':lastactiontime, 'status':status, 'ackData':ackdata.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'trashMessage':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            msgid = self._decode(params[0], "hex")

            # Trash if in inbox table
            helper_inbox.trash(msgid)
            # Trash if in sent table
            sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
            return 'Trashed message (assuming message existed).'
        elif method == 'trashInboxMessage':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            msgid = self._decode(params[0], "hex")
            helper_inbox.trash(msgid)
            return 'Trashed inbox message (assuming message existed).'
        elif method == 'trashSentMessage':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            msgid = self._decode(params[0], "hex")
            sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
            return 'Trashed sent message (assuming message existed).'
        elif method == 'trashSentMessageByAckData':
            # This API method should only be used when msgid is not available
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            ackdata = self._decode(params[0], "hex")
            sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''',
                       ackdata)
            return 'Trashed sent message (assuming message existed).'
        elif method == 'sendMessage':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            elif len(params) == 4:
                toAddress, fromAddress, subject, message = params
                encodingType = 2
            elif len(params) == 5:
                toAddress, fromAddress, subject, message, encodingType = params
            if encodingType != 2:
                raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
            subject = self._decode(subject, "base64")
            message = self._decode(message, "base64")
            toAddress = addBMIfNotPresent(toAddress)
            fromAddress = addBMIfNotPresent(fromAddress)
            status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(toAddress)
            self._verifyAddress(fromAddress)
            try:
                fromAddressEnabled = shared.config.getboolean(
                    fromAddress, 'enabled')
            except:
                raise APIError(13, 'Could not find your fromAddress in the keys.dat file.')
            if not fromAddressEnabled:
                raise APIError(14, 'Your fromAddress is disabled. Cannot send.')

            ackdata = OpenSSL.rand(32)

            t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(
                time.time()), 'msgqueued', 1, 1, 'sent', 2)
            helper_sent.insert(t)

            toLabel = ''
            queryreturn = sqlQuery('''select label from addressbook where address=?''', toAddress)
            if queryreturn != []:
                for row in queryreturn:
                    toLabel, = row
            # apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata)))
            shared.UISignalQueue.put(('displayNewSentMessage', (
                toAddress, toLabel, fromAddress, subject, message, ackdata)))

            shared.workerQueue.put(('sendmessage', toAddress))

            return ackdata.encode('hex')

        elif method == 'sendBroadcast':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            if len(params) == 3:
                fromAddress, subject, message = params
                encodingType = 2
            elif len(params) == 4:
                fromAddress, subject, message, encodingType = params
            if encodingType != 2:
                raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
            subject = self._decode(subject, "base64")
            message = self._decode(message, "base64")

            fromAddress = addBMIfNotPresent(fromAddress)
            self._verifyAddress(fromAddress)
            try:
                fromAddressEnabled = shared.config.getboolean(
                    fromAddress, 'enabled')
            except:
                raise APIError(13, 'could not find your fromAddress in the keys.dat file.')
            ackdata = OpenSSL.rand(32)
            toAddress = '[Broadcast subscribers]'
            ripe = ''


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

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

            return ackdata.encode('hex')
        elif method == 'getStatus':
            if len(params) != 1:
                raise APIError(0, 'I need one parameter!')
            ackdata, = params
            if len(ackdata) != 64:
                raise APIError(15, 'The length of ackData should be 32 bytes (encoded in hex thus 64 characters).')
            ackdata = self._decode(ackdata, "hex")
            queryreturn = sqlQuery(
                '''SELECT status FROM sent where ackdata=?''',
                ackdata)
            if queryreturn == []:
                return 'notfound'
            for row in queryreturn:
                status, = row
                return status
        elif method == 'addSubscription':
            if len(params) == 0:
                raise APIError(0, 'I need parameters!')
            if len(params) == 1:
                address, = params
                label = ''
            if len(params) == 2:
                address, label = params
                label = self._decode(label, "base64")
                try:
                    unicode(label, 'utf-8')
                except:
                    raise APIError(17, 'Label is not valid UTF-8 data.')
            if len(params) > 2:
                raise APIError(0, 'I need either 1 or 2 parameters!')
            address = addBMIfNotPresent(address)
            self._verifyAddress(address)
            # First we must check to see if the address is already in the
            # subscriptions list.
            queryreturn = sqlQuery('''select * from subscriptions where address=?''', address)
            if queryreturn != []:
                raise APIError(16, 'You are already subscribed to that address.')
            sqlExecute('''INSERT INTO subscriptions VALUES (?,?,?)''',label, address, True)
            shared.reloadBroadcastSendersForWhichImWatching()
            shared.UISignalQueue.put(('rerenderInboxFromLabels', ''))
            shared.UISignalQueue.put(('rerenderSubscriptions', ''))
            return 'Added subscription.'

        elif method == 'deleteSubscription':
            if len(params) != 1:
                raise APIError(0, 'I need 1 parameter!')
            address, = params
            address = addBMIfNotPresent(address)
            sqlExecute('''DELETE FROM subscriptions WHERE address=?''', address)
            shared.reloadBroadcastSendersForWhichImWatching()
            shared.UISignalQueue.put(('rerenderInboxFromLabels', ''))
            shared.UISignalQueue.put(('rerenderSubscriptions', ''))
            return 'Deleted subscription if it existed.'
        elif method == 'listSubscriptions':
            queryreturn = sqlQuery('''SELECT label, address, enabled FROM subscriptions''')
            data = '{"subscriptions":['
            for row in queryreturn:
                label, address, enabled = row
                label = shared.fixPotentiallyInvalidUTF8Data(label)
                if len(data) > 20:
                    data += ','
                data += json.dumps({'label':label.encode('base64'), 'address': address, 'enabled': enabled == 1}, indent=4, separators=(',',': '))
            data += ']}'
            return data
        elif method == 'disseminatePreEncryptedMsg':
            # The device issuing this command to PyBitmessage supplies a msg object that has
            # already been encrypted but which still needs the POW to be done. PyBitmessage
            # accepts this msg object and sends it out to the rest of the Bitmessage network
            # as if it had generated the message itself. Please do not yet add this to the
            # api doc.
            if len(params) != 3:
                raise APIError(0, 'I need 3 parameter!')
            encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes = params
            encryptedPayload = self._decode(encryptedPayload, "hex")
            # Let us do the POW and attach it to the front
            target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte)
            with shared.printLock:
                print '(For msg message via API) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes
            powStartTime = time.time()
            initialHash = hashlib.sha512(encryptedPayload).digest()
            trialValue, nonce = proofofwork.run(target, initialHash)
            with shared.printLock:
                print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce
                try:
                    print 'POW took', int(time.time() - powStartTime), 'seconds.', nonce / (time.time() - powStartTime), 'nonce trials per second.'
                except:
                    pass
            encryptedPayload = pack('>Q', nonce) + encryptedPayload
            toStreamNumber = decodeVarint(encryptedPayload[16:26])[0]
            inventoryHash = calculateInventoryHash(encryptedPayload)
            objectType = 'msg'
            shared.inventory[inventoryHash] = (
                objectType, toStreamNumber, encryptedPayload, int(time.time()),'')
            shared.inventorySets[toStreamNumber].add(inventoryHash)
            with shared.printLock:
                print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', inventoryHash.encode('hex')
            shared.broadcastToSendDataQueues((
                toStreamNumber, 'advertiseobject', inventoryHash))
        elif method == 'disseminatePubkey':
            # The device issuing this command to PyBitmessage supplies a pubkey object to be
            # disseminated to the rest of the Bitmessage network. PyBitmessage accepts this
            # pubkey object and sends it out to the rest of the Bitmessage network as if it
            # had generated the pubkey object itself. Please do not yet add this to the api
            # doc.
            if len(params) != 1:
                raise APIError(0, 'I need 1 parameter!')
            payload, = params
            payload = self._decode(payload, "hex")

            # Let us do the POW
            target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
                                 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
            print '(For pubkey message via API) Doing proof of work...'
            initialHash = hashlib.sha512(payload).digest()
            trialValue, nonce = proofofwork.run(target, initialHash)
            print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce
            payload = pack('>Q', nonce) + payload

            pubkeyReadPosition = 8 # bypass the nonce
            if payload[pubkeyReadPosition:pubkeyReadPosition+4] == '\x00\x00\x00\x00': # if this pubkey uses 8 byte time
                pubkeyReadPosition += 8
            else:
                pubkeyReadPosition += 4
            addressVersion, addressVersionLength = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10])
            pubkeyReadPosition += addressVersionLength
            pubkeyStreamNumber = decodeVarint(payload[pubkeyReadPosition:pubkeyReadPosition+10])[0]
            inventoryHash = calculateInventoryHash(payload)
            objectType = 'pubkey'
                        #todo: support v4 pubkeys
            shared.inventory[inventoryHash] = (
                objectType, pubkeyStreamNumber, payload, int(time.time()),'')
            shared.inventorySets[pubkeyStreamNumber].add(inventoryHash)
            with shared.printLock:
                print 'broadcasting inv within API command disseminatePubkey with hash:', inventoryHash.encode('hex')
            shared.broadcastToSendDataQueues((
                streamNumber, 'advertiseobject', inventoryHash))
        elif method == 'getMessageDataByDestinationHash' or method == 'getMessageDataByDestinationTag':
            # Method will eventually be used by a particular Android app to
            # select relevant messages. Do not yet add this to the api
            # doc.

            if len(params) != 1:
                raise APIError(0, 'I need 1 parameter!')
            requestedHash, = params
            if len(requestedHash) != 32:
                raise APIError(19, 'The length of hash should be 32 bytes (encoded in hex thus 64 characters).')
            requestedHash = self._decode(requestedHash, "hex")

            # This is not a particularly commonly used API function. Before we
            # use it we'll need to fill out a field in our inventory database
            # which is blank by default (first20bytesofencryptedmessage).
            queryreturn = sqlQuery(
                '''SELECT hash, payload FROM inventory WHERE tag = '' and objecttype = 'msg' ; ''')
            with SqlBulkExecute() as sql:
                for row in queryreturn:
                    hash01, payload = row
                    readPosition = 16 # Nonce length + time length
                    readPosition += decodeVarint(payload[readPosition:readPosition+10])[1] # Stream Number length
                    t = (payload[readPosition:readPosition+32],hash01)
                    sql.execute('''UPDATE inventory SET tag=? WHERE hash=?; ''', *t)

            queryreturn = sqlQuery('''SELECT payload FROM inventory WHERE tag = ?''',
                                   requestedHash)
            data = '{"receivedMessageDatas":['
            for row in queryreturn:
                payload, = row
                if len(data) > 25:
                    data += ','
                data += json.dumps({'data':payload.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'getPubkeyByHash':
            # Method will eventually be used by a particular Android app to
            # retrieve pubkeys. Please do not yet add this to the api docs.
            if len(params) != 1:
                raise APIError(0, 'I need 1 parameter!')
            requestedHash, = params
            if len(requestedHash) != 40:
                raise APIError(19, 'The length of hash should be 20 bytes (encoded in hex thus 40 characters).')
            requestedHash = self._decode(requestedHash, "hex")
            queryreturn = sqlQuery('''SELECT transmitdata FROM pubkeys WHERE hash = ? ; ''', requestedHash)
            data = '{"pubkey":['
            for row in queryreturn:
                transmitdata, = row
                data += json.dumps({'data':transmitdata.encode('hex')}, indent=4, separators=(',', ': '))
            data += ']}'
            return data
        elif method == 'clientStatus':
            if len(shared.connectedHostsList) == 0:
                networkStatus = 'notConnected'
            elif len(shared.connectedHostsList) > 0 and not shared.clientHasReceivedIncomingConnections:
                networkStatus = 'connectedButHaveNotReceivedIncomingConnections'
            else:
                networkStatus = 'connectedAndReceivingIncomingConnections'
            return json.dumps({'networkConnections':len(shared.connectedHostsList),'numberOfMessagesProcessed':shared.numberOfMessagesProcessed, 'numberOfBroadcastsProcessed':shared.numberOfBroadcastsProcessed, 'numberOfPubkeysProcessed':shared.numberOfPubkeysProcessed, 'networkStatus':networkStatus, 'softwareName':'PyBitmessage','softwareVersion':shared.softwareVersion}, indent=4, separators=(',', ': '))
        elif method == 'decodeAddress':
            # Return a meaningful decoding of an address.
            if len(params) != 1:
                raise APIError(0, 'I need 1 parameter!')
            address, = params
            status, addressVersion, streamNumber, ripe = decodeAddress(address)
            return json.dumps({'status':status, 'addressVersion':addressVersion,
                               'streamNumber':streamNumber, 'ripe':ripe.encode('base64')}, indent=4,
                              separators=(',', ': '))
        else:
            raise APIError(20, 'Invalid method: %s' % method)
Beispiel #35
0
def decryptAndCheckPubkeyPayload(data, address):
    """
    Version 4 pubkeys are encrypted. This function is run when we already have the 
    address to which we want to try to send a message. The 'data' may come either
    off of the wire or we might have had it already in our inventory when we tried
    to send a msg to this particular address. 
    """
    try:
        status, addressVersion, streamNumber, ripe = decodeAddress(address)
        
        readPosition = 20  # bypass the nonce, time, and object type
        embeddedAddressVersion, varintLength = decodeVarint(data[readPosition:readPosition + 10])
        readPosition += varintLength
        embeddedStreamNumber, varintLength = decodeVarint(data[readPosition:readPosition + 10])
        readPosition += varintLength
        storedData = data[20:readPosition] # We'll store the address version and stream number (and some more) in the pubkeys table.
        
        if addressVersion != embeddedAddressVersion:
            logger.info('Pubkey decryption was UNsuccessful due to address version mismatch.')
            return 'failed'
        if streamNumber != embeddedStreamNumber:
            logger.info('Pubkey decryption was UNsuccessful due to stream number mismatch.')
            return 'failed'
        
        tag = data[readPosition:readPosition + 32]
        readPosition += 32
        signedData = data[8:readPosition] # the time through the tag. More data is appended onto signedData below after the decryption. 
        encryptedData = data[readPosition:]
    
        # Let us try to decrypt the pubkey
        toAddress, cryptorObject = state.neededPubkeys[tag]
        if toAddress != address:
            logger.critical('decryptAndCheckPubkeyPayload failed due to toAddress mismatch. This is very peculiar. toAddress: %s, address %s', toAddress, address)
            # the only way I can think that this could happen is if someone encodes their address data two different ways.
            # That sort of address-malleability should have been caught by the UI or API and an error given to the user. 
            return 'failed'
        try:
            decryptedData = cryptorObject.decrypt(encryptedData)
        except:
            # Someone must have encrypted some data with a different key
            # but tagged it with a tag for which we are watching.
            logger.info('Pubkey decryption was unsuccessful.')
            return 'failed'
        
        readPosition = 0
        bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += specifiedNonceTrialsPerByteLength
        specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += specifiedPayloadLengthExtraBytesLength
        storedData += decryptedData[:readPosition]
        signedData += decryptedData[:readPosition]
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += signatureLengthLength
        signature = decryptedData[readPosition:readPosition + signatureLength]
        
        if highlevelcrypto.verify(signedData, signature, hexlify(publicSigningKey)):
            logger.info('ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
        else:
            logger.info('ECDSA verify failed (within decryptAndCheckPubkeyPayload)')
            return 'failed'
    
        sha = hashlib.new('sha512')
        sha.update(publicSigningKey + publicEncryptionKey)
        ripeHasher = hashlib.new('ripemd160')
        ripeHasher.update(sha.digest())
        embeddedRipe = ripeHasher.digest()
    
        if embeddedRipe != ripe:
            # Although this pubkey object had the tag were were looking for and was
            # encrypted with the correct encryption key, it doesn't contain the
            # correct pubkeys. Someone is either being malicious or using buggy software.
            logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch.')
            return 'failed'
        
        # Everything checked out. Insert it into the pubkeys table.
        
        logger.info('within decryptAndCheckPubkeyPayload, addressVersion: %s, streamNumber: %s \n\
                    ripe %s\n\
                    publicSigningKey in hex: %s\n\
                    publicEncryptionKey in hex: %s', addressVersion,
                                                       streamNumber, 
                                                       hexlify(ripe),
                                                       hexlify(publicSigningKey),
                                                       hexlify(publicEncryptionKey)
                    )
    
        t = (address, addressVersion, storedData, int(time.time()), 'yes')
        sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
        return 'successful'
    except varintDecodeError as e:
        logger.info('Pubkey decryption was UNsuccessful due to a malformed varint.')
        return 'failed'
    except Exception as e:
        logger.critical('Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s', traceback.format_exc())
        return 'failed'
    def run(self):
        gc.disable()
        timeWeLastClearedInventoryAndPubkeysTables = 0
        try:
            shared.maximumLengthOfTimeToBotherResendingMessages = (
                float(BMConfigParser().get('lmessagesettings',
                                           'stopresendingafterxdays')) * 24 *
                60 * 60) + (float(BMConfigParser().get(
                    'lmessagesettings', 'stopresendingafterxmonths')) *
                            (60 * 60 * 24 * 365) / 12)
        except:
            # Either the user hasn't set stopresendingafterxdays and
            # stopresendingafterxmonths yet or the options are missing
            # from the config file.
            shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')

        # initial wait
        if state.shutdown == 0:
            self.stop.wait(singleCleaner.cycleLength)

        while state.shutdown == 0:
            queues.UISignalQueue.put(
                ('updateStatusBar',
                 'Doing housekeeping (Flushing inventory in memory to disk...)'
                 ))
            Inventory().flush()
            queues.UISignalQueue.put(('updateStatusBar', ''))

            # If we are running as a daemon then we are going to fill up the UI
            # queue which will never be handled by a UI. We should clear it to
            # save memory.
            # FIXME redundant?
            if shared.thisapp.daemon or not state.enableGUI:
                queues.UISignalQueue.queue.clear()
            if timeWeLastClearedInventoryAndPubkeysTables < \
                    int(time.time()) - 7380:
                timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
                Inventory().clean()
                # pubkeys
                sqlExecute(
                    "DELETE FROM pubkeys WHERE time<? AND usedpersonally='no'",
                    int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys)

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

            # cleanup old nodes
            now = int(time.time())

            with knownnodes.knownNodesLock:
                for stream in knownnodes.knownNodes:
                    keys = knownnodes.knownNodes[stream].keys()
                    for node in keys:
                        try:
                            # scrap old nodes
                            if now - knownnodes.knownNodes[stream][node][
                                    "lastseen"] > 2419200:  # 28 days
                                shared.needToWriteKnownNodesToDisk = True
                                del knownnodes.knownNodes[stream][node]
                                continue
                            # scrap old nodes with low rating
                            if now - knownnodes.knownNodes[stream][node][
                                    "lastseen"] > 10800 and knownnodes.knownNodes[
                                        stream][node][
                                            "rating"] <= knownnodes.knownNodesForgetRating:
                                shared.needToWriteKnownNodesToDisk = True
                                del knownnodes.knownNodes[stream][node]
                                continue
                        except TypeError:
                            print "Error in %s" % node
                    keys = []

            # Let us write out the knowNodes to disk
            # if there is anything new to write out.
            if shared.needToWriteKnownNodesToDisk:
                try:
                    knownnodes.saveKnownNodes()
                except Exception as err:
                    if "Errno 28" in str(err):
                        logger.fatal('(while receiveDataThread'
                                     ' knownnodes.needToWriteKnownNodesToDisk)'
                                     ' Alert: Your disk or data storage volume'
                                     ' is full. ')
                        queues.UISignalQueue.put(
                            ('alert',
                             (tr._translate("MainWindow", "Disk full"),
                              tr._translate(
                                  "MainWindow",
                                  'Alert: Your disk or data storage volume'
                                  ' is full. LMessage will now exit.'), True)))
                        # FIXME redundant?
                        if shared.daemon or not state.enableGUI:
                            os._exit(0)
                shared.needToWriteKnownNodesToDisk = False


#            # clear download queues
#            for thread in threading.enumerate():
#                if thread.isAlive() and hasattr(thread, 'downloadQueue'):
#                    thread.downloadQueue.clear()

# inv/object tracking
            for connection in \
                    BMConnectionPool().inboundConnections.values() + \
                    BMConnectionPool().outboundConnections.values():
                connection.clean()

            # discovery tracking
            exp = time.time() - singleCleaner.expireDiscoveredPeers
            reaper = (k for k, v in state.discoveredPeers.items() if v < exp)
            for k in reaper:
                try:
                    del state.discoveredPeers[k]
                except KeyError:
                    pass
            # TODO: cleanup pending upload / download

            gc.collect()

            if state.shutdown == 0:
                self.stop.wait(singleCleaner.cycleLength)
Beispiel #37
0
 def HandleTrashSentMessage(self, params):
     if len(params) == 0:
         raise APIError(0, 'I need parameters!')
     msgid = self._decode(params[0], "hex")
     sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
     return 'Trashed sent message (assuming message existed).'