2018-10-22 19:06:12 +02:00
|
|
|
# Copyright (c) 2012-2016 Jonathan Warren
|
|
|
|
# Copyright (c) 2012-2020 The Bitmessage developers
|
|
|
|
|
2019-10-10 15:38:13 +02:00
|
|
|
"""
|
2018-11-05 17:35:38 +01:00
|
|
|
This is not what you run to start the Bitmessage API.
|
|
|
|
Instead, `enable the API <https://bitmessage.org/wiki/API>`_
|
|
|
|
and optionally `enable daemon mode <https://bitmessage.org/wiki/Daemon>`_
|
|
|
|
then run the PyBitmessage.
|
|
|
|
|
|
|
|
The PyBitmessage API is provided either as
|
|
|
|
`XML-RPC <http://xmlrpc.scripting.com/spec.html>`_ or
|
|
|
|
`JSON-RPC <https://www.jsonrpc.org/specification>`_ like in bitcoin.
|
|
|
|
It's selected according to 'apivariant' setting in config file.
|
|
|
|
|
|
|
|
Special value ``apivariant=legacy`` is to mimic the old pre 0.6.3
|
|
|
|
behaviour when any results are returned as strings of json.
|
|
|
|
|
|
|
|
.. list-table:: All config settings related to API:
|
|
|
|
:header-rows: 0
|
|
|
|
|
|
|
|
* - apienabled = true
|
|
|
|
- if 'false' the `singleAPI` wont start
|
|
|
|
* - apiinterface = 127.0.0.1
|
|
|
|
- this is the recommended default
|
|
|
|
* - apiport = 8442
|
|
|
|
- the API listens apiinterface:apiport if apiport is not used,
|
|
|
|
random in range (32767, 65535) otherwice
|
|
|
|
* - apivariant = xml
|
|
|
|
- current default for backward compatibility, 'json' is recommended
|
|
|
|
* - apiusername = username
|
|
|
|
- set the username
|
|
|
|
* - apipassword = password
|
|
|
|
- and the password
|
|
|
|
* - apinotifypath =
|
|
|
|
- not really the API setting, this sets a path for the executable to be ran
|
|
|
|
when certain internal event happens
|
|
|
|
|
|
|
|
To use the API concider such simple example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
import jsonrpclib
|
|
|
|
|
|
|
|
from pybitmessage import bmconfigparser, helper_startup
|
|
|
|
|
|
|
|
helper_startup.loadConfig() # find and load local config file
|
|
|
|
conf = bmconfigparser.BMConfigParser()
|
|
|
|
api_uri = "http://%s:%s@127.0.0.1:8442/" % (
|
|
|
|
conf.safeGet('bitmessagesettings', 'apiusername'),
|
|
|
|
conf.safeGet('bitmessagesettings', 'apipassword')
|
|
|
|
)
|
|
|
|
api = jsonrpclib.ServerProxy(api_uri)
|
|
|
|
print(api.clientStatus())
|
|
|
|
|
|
|
|
|
|
|
|
For further examples please reference `.tests.test_api`.
|
2014-01-13 01:56:30 +01:00
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
|
2017-06-03 02:53:13 +02:00
|
|
|
import base64
|
2018-10-22 19:06:12 +02:00
|
|
|
import ConfigParser
|
2018-06-28 15:09:23 +02:00
|
|
|
import errno
|
2018-04-08 17:28:08 +02:00
|
|
|
import hashlib
|
2018-10-26 13:45:37 +02:00
|
|
|
import httplib
|
2014-01-13 01:56:30 +01:00
|
|
|
import json
|
2018-06-28 15:09:23 +02:00
|
|
|
import random # nosec
|
|
|
|
import socket
|
|
|
|
import subprocess
|
2018-04-08 17:28:08 +02:00
|
|
|
import time
|
2018-10-25 12:57:21 +02:00
|
|
|
import xmlrpclib
|
2017-06-03 02:53:13 +02:00
|
|
|
from binascii import hexlify, unhexlify
|
2018-04-08 17:28:08 +02:00
|
|
|
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
|
|
|
|
from struct import pack
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2017-02-08 20:37:42 +01:00
|
|
|
import defaults
|
2014-01-13 01:56:30 +01:00
|
|
|
import helper_inbox
|
|
|
|
import helper_sent
|
2018-10-10 12:41:44 +02:00
|
|
|
import network.stats
|
|
|
|
import proofofwork
|
2017-02-08 13:41:56 +01:00
|
|
|
import queues
|
2018-10-10 12:41:44 +02:00
|
|
|
import shared
|
2017-08-21 10:39:03 +02:00
|
|
|
import shutdown
|
2018-10-10 12:41:44 +02:00
|
|
|
import state
|
2020-01-17 14:27:36 +01:00
|
|
|
from addresses import (
|
|
|
|
addBMIfNotPresent,
|
|
|
|
calculateInventoryHash,
|
|
|
|
decodeAddress,
|
|
|
|
decodeVarint,
|
|
|
|
varintDecodeError
|
|
|
|
)
|
2018-10-10 12:41:44 +02:00
|
|
|
from bmconfigparser import BMConfigParser
|
2014-01-13 01:56:30 +01:00
|
|
|
from debug import logger
|
2021-10-15 16:00:19 +02:00
|
|
|
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure, sql_ready
|
2017-01-10 21:17:25 +01:00
|
|
|
from inventory import Inventory
|
2019-08-06 13:04:33 +02:00
|
|
|
from network.threads import StoppableThread
|
2021-10-15 16:00:19 +02:00
|
|
|
from six.moves import queue
|
2020-01-24 15:03:13 +01:00
|
|
|
from version import softwareVersion
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2018-10-25 12:57:21 +02:00
|
|
|
try: # TODO: write tests for XML vulnerabilities
|
|
|
|
from defusedxml.xmlrpc import monkey_patch
|
|
|
|
except ImportError:
|
|
|
|
logger.warning(
|
|
|
|
'defusedxml not available, only use API on a secure, closed network.')
|
|
|
|
else:
|
|
|
|
monkey_patch()
|
|
|
|
|
2018-10-25 23:19:07 +02:00
|
|
|
|
2014-01-13 01:56:30 +01:00
|
|
|
str_chan = '[chan]'
|
2018-10-22 19:06:12 +02:00
|
|
|
str_broadcast_subscribers = '[Broadcast subscribers]'
|
2014-01-13 01:56:30 +01:00
|
|
|
|
|
|
|
|
2019-11-12 16:32:39 +01:00
|
|
|
class ErrorCodes(type):
|
|
|
|
"""Metaclass for :class:`APIError` documenting error codes."""
|
|
|
|
_CODES = {
|
|
|
|
0: 'Invalid command parameters number',
|
|
|
|
1: 'The specified passphrase is blank.',
|
|
|
|
2: 'The address version number currently must be 3, 4, or 0'
|
|
|
|
' (which means auto-select).',
|
|
|
|
3: 'The stream number must be 1 (or 0 which means'
|
|
|
|
' auto-select). Others aren\'t supported.',
|
|
|
|
4: 'Why would you ask me to generate 0 addresses for you?',
|
|
|
|
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.',
|
|
|
|
6: 'The encoding type must be 2 or 3.',
|
|
|
|
7: 'Could not decode address',
|
|
|
|
8: 'Checksum failed for address',
|
|
|
|
9: 'Invalid characters in address',
|
|
|
|
10: 'Address version number too high (or zero)',
|
|
|
|
11: 'The address version number currently must be 2, 3 or 4.'
|
|
|
|
' Others aren\'t supported. Check the address.',
|
|
|
|
12: 'The stream number must be 1. Others aren\'t supported.'
|
|
|
|
' Check the address.',
|
|
|
|
13: 'Could not find this address in your keys.dat file.',
|
|
|
|
14: 'Your fromAddress is disabled. Cannot send.',
|
|
|
|
15: 'Invalid ackData object size.',
|
|
|
|
16: 'You are already subscribed to that address.',
|
|
|
|
17: 'Label is not valid UTF-8 data.',
|
|
|
|
18: 'Chan name does not match address.',
|
|
|
|
19: 'The length of hash should be 32 bytes (encoded in hex'
|
|
|
|
' thus 64 characters).',
|
|
|
|
20: 'Invalid method:',
|
|
|
|
21: 'Unexpected API Failure',
|
|
|
|
22: 'Decode error',
|
|
|
|
23: 'Bool expected in eighteenByteRipe',
|
|
|
|
24: 'Chan address is already present.',
|
|
|
|
25: 'Specified address is not a chan address.'
|
|
|
|
' Use deleteAddress API call instead.',
|
|
|
|
26: 'Malformed varint in address: ',
|
|
|
|
27: 'Message is too long.'
|
|
|
|
}
|
|
|
|
|
|
|
|
def __new__(mcs, name, bases, namespace):
|
|
|
|
result = super(ErrorCodes, mcs).__new__(mcs, name, bases, namespace)
|
|
|
|
for code in mcs._CODES.iteritems():
|
|
|
|
# beware: the formatting is adjusted for list-table
|
|
|
|
result.__doc__ += """ * - %04i
|
|
|
|
- %s
|
|
|
|
""" % code
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2018-10-25 11:52:16 +02:00
|
|
|
class APIError(xmlrpclib.Fault):
|
2019-11-12 16:32:39 +01:00
|
|
|
"""
|
|
|
|
APIError exception class
|
|
|
|
|
|
|
|
.. list-table:: Possible error values
|
|
|
|
:header-rows: 1
|
|
|
|
:widths: auto
|
|
|
|
|
|
|
|
* - Error Number
|
|
|
|
- Message
|
|
|
|
"""
|
|
|
|
__metaclass__ = ErrorCodes
|
|
|
|
|
2014-01-13 01:56:30 +01:00
|
|
|
def __str__(self):
|
2018-10-25 11:52:16 +02:00
|
|
|
return "API Error %04i: %s" % (self.faultCode, self.faultString)
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2015-11-24 01:55:17 +01:00
|
|
|
|
2018-06-28 15:09:23 +02:00
|
|
|
# This thread, of which there is only one, runs the API.
|
2019-08-01 13:37:26 +02:00
|
|
|
class singleAPI(StoppableThread):
|
2018-09-05 12:56:06 +02:00
|
|
|
"""API thread"""
|
2019-08-01 13:37:26 +02:00
|
|
|
|
|
|
|
name = "singleAPI"
|
2018-06-28 15:09:23 +02:00
|
|
|
|
|
|
|
def stopThread(self):
|
|
|
|
super(singleAPI, self).stopThread()
|
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
try:
|
|
|
|
s.connect((
|
|
|
|
BMConfigParser().get('bitmessagesettings', 'apiinterface'),
|
|
|
|
BMConfigParser().getint('bitmessagesettings', 'apiport')
|
|
|
|
))
|
|
|
|
s.shutdown(socket.SHUT_RDWR)
|
|
|
|
s.close()
|
2018-10-10 12:41:44 +02:00
|
|
|
except BaseException:
|
2018-06-28 15:09:23 +02:00
|
|
|
pass
|
|
|
|
|
|
|
|
def run(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The instance of `SimpleXMLRPCServer.SimpleXMLRPCServer` or
|
|
|
|
:class:`jsonrpclib.SimpleJSONRPCServer` is created and started here
|
|
|
|
with `BMRPCDispatcher` dispatcher.
|
|
|
|
"""
|
2018-06-28 15:09:23 +02:00
|
|
|
port = BMConfigParser().getint('bitmessagesettings', 'apiport')
|
|
|
|
try:
|
2018-09-05 12:56:06 +02:00
|
|
|
getattr(errno, 'WSAEADDRINUSE')
|
|
|
|
except AttributeError:
|
2018-06-28 15:09:23 +02:00
|
|
|
errno.WSAEADDRINUSE = errno.EADDRINUSE
|
2018-10-25 23:19:07 +02:00
|
|
|
|
|
|
|
RPCServerBase = SimpleXMLRPCServer
|
2018-10-26 13:45:37 +02:00
|
|
|
ct = 'text/xml'
|
2018-10-25 23:19:07 +02:00
|
|
|
if BMConfigParser().safeGet(
|
|
|
|
'bitmessagesettings', 'apivariant') == 'json':
|
|
|
|
try:
|
|
|
|
from jsonrpclib.SimpleJSONRPCServer import (
|
|
|
|
SimpleJSONRPCServer as RPCServerBase)
|
|
|
|
except ImportError:
|
|
|
|
logger.warning(
|
|
|
|
'jsonrpclib not available, failing back to XML-RPC')
|
2018-10-26 13:45:37 +02:00
|
|
|
else:
|
|
|
|
ct = 'application/json-rpc'
|
2018-10-25 23:19:07 +02:00
|
|
|
|
|
|
|
# Nested class. FIXME not found a better solution.
|
|
|
|
class StoppableRPCServer(RPCServerBase):
|
|
|
|
"""A SimpleXMLRPCServer that honours state.shutdown"""
|
|
|
|
allow_reuse_address = True
|
2018-10-26 13:45:37 +02:00
|
|
|
content_type = ct
|
2018-10-25 23:19:07 +02:00
|
|
|
|
|
|
|
def serve_forever(self, poll_interval=None):
|
|
|
|
"""Start the RPCServer"""
|
2021-10-15 16:00:19 +02:00
|
|
|
sql_ready.wait()
|
2018-10-25 23:19:07 +02:00
|
|
|
while state.shutdown == 0:
|
|
|
|
self.handle_request()
|
|
|
|
|
2018-06-28 15:09:23 +02:00
|
|
|
for attempt in range(50):
|
|
|
|
try:
|
|
|
|
if attempt > 0:
|
2019-08-14 17:34:34 +02:00
|
|
|
logger.warning(
|
|
|
|
'Failed to start API listener on port %s', port)
|
2018-06-28 15:09:23 +02:00
|
|
|
port = random.randint(32767, 65535)
|
2018-10-25 23:19:07 +02:00
|
|
|
se = StoppableRPCServer(
|
2018-06-28 15:09:23 +02:00
|
|
|
(BMConfigParser().get(
|
|
|
|
'bitmessagesettings', 'apiinterface'),
|
|
|
|
port),
|
2018-10-25 23:19:07 +02:00
|
|
|
BMXMLRPCRequestHandler, True, encoding='UTF-8')
|
2018-06-28 15:09:23 +02:00
|
|
|
except socket.error as e:
|
|
|
|
if e.errno in (errno.EADDRINUSE, errno.WSAEADDRINUSE):
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
if attempt > 0:
|
2019-08-14 17:34:34 +02:00
|
|
|
logger.warning('Setting apiport to %s', port)
|
2018-06-28 15:09:23 +02:00
|
|
|
BMConfigParser().set(
|
2019-08-14 17:34:34 +02:00
|
|
|
'bitmessagesettings', 'apiport', str(port))
|
2018-06-28 15:09:23 +02:00
|
|
|
BMConfigParser().save()
|
|
|
|
break
|
2018-10-25 23:19:07 +02:00
|
|
|
|
|
|
|
se.register_instance(BMRPCDispatcher())
|
2018-06-28 15:09:23 +02:00
|
|
|
se.register_introspection_functions()
|
|
|
|
|
|
|
|
apiNotifyPath = BMConfigParser().safeGet(
|
|
|
|
'bitmessagesettings', 'apinotifypath')
|
|
|
|
|
|
|
|
if apiNotifyPath:
|
|
|
|
logger.info('Trying to call %s', apiNotifyPath)
|
|
|
|
try:
|
|
|
|
subprocess.call([apiNotifyPath, "startingUp"])
|
|
|
|
except OSError:
|
|
|
|
logger.warning(
|
|
|
|
'Failed to call %s, removing apinotifypath setting',
|
|
|
|
apiNotifyPath)
|
|
|
|
BMConfigParser().remove_option(
|
|
|
|
'bitmessagesettings', 'apinotifypath')
|
|
|
|
|
|
|
|
se.serve_forever()
|
|
|
|
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
class CommandHandler(type):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
The metaclass for `BMRPCDispatcher` which fills _handlers dict by
|
|
|
|
methods decorated with @command
|
2018-10-10 12:41:44 +02:00
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
def __new__(mcs, name, bases, namespace):
|
|
|
|
# pylint: disable=protected-access
|
|
|
|
result = super(CommandHandler, mcs).__new__(
|
|
|
|
mcs, name, bases, namespace)
|
2018-10-25 11:52:16 +02:00
|
|
|
result.config = BMConfigParser()
|
2018-10-22 19:06:12 +02:00
|
|
|
result._handlers = {}
|
2018-10-30 08:17:54 +01:00
|
|
|
apivariant = result.config.safeGet('bitmessagesettings', 'apivariant')
|
2018-10-22 19:06:12 +02:00
|
|
|
for func in namespace.values():
|
|
|
|
try:
|
|
|
|
for alias in getattr(func, '_cmd'):
|
2018-10-30 08:17:54 +01:00
|
|
|
try:
|
|
|
|
prefix, alias = alias.split(':')
|
|
|
|
if apivariant != prefix:
|
|
|
|
continue
|
|
|
|
except ValueError:
|
|
|
|
pass
|
2018-10-22 19:06:12 +02:00
|
|
|
result._handlers[alias] = func
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2021-11-25 17:13:22 +01:00
|
|
|
class testmode(object): # pylint: disable=too-few-public-methods
|
|
|
|
"""Decorator to check testmode & route to command decorator"""
|
|
|
|
|
|
|
|
def __init__(self, *aliases):
|
|
|
|
self.aliases = aliases
|
|
|
|
|
|
|
|
def __call__(self, func):
|
|
|
|
"""Testmode call method"""
|
|
|
|
|
|
|
|
if not state.testmode:
|
|
|
|
return None
|
|
|
|
return command(self.aliases[0]).__call__(func)
|
|
|
|
|
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
class command(object): # pylint: disable=too-few-public-methods
|
2018-10-22 19:06:12 +02:00
|
|
|
"""Decorator for API command method"""
|
|
|
|
def __init__(self, *aliases):
|
|
|
|
self.aliases = aliases
|
|
|
|
|
|
|
|
def __call__(self, func):
|
2021-11-25 17:13:22 +01:00
|
|
|
|
2018-10-25 11:52:16 +02:00
|
|
|
if BMConfigParser().safeGet(
|
|
|
|
'bitmessagesettings', 'apivariant') == 'legacy':
|
|
|
|
def wrapper(*args):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
A wrapper for legacy apivariant which dumps the result
|
|
|
|
into string of json
|
|
|
|
"""
|
2018-10-25 11:52:16 +02:00
|
|
|
result = func(*args)
|
|
|
|
return result if isinstance(result, (int, str)) \
|
|
|
|
else json.dumps(result, indent=4)
|
|
|
|
wrapper.__doc__ = func.__doc__
|
|
|
|
else:
|
|
|
|
wrapper = func
|
2018-10-22 19:06:12 +02:00
|
|
|
# pylint: disable=protected-access
|
|
|
|
wrapper._cmd = self.aliases
|
2018-11-05 17:35:38 +01:00
|
|
|
wrapper.__doc__ = """Commands: *%s*
|
|
|
|
|
|
|
|
""" % ', '.join(self.aliases) + wrapper.__doc__.lstrip()
|
2018-10-22 19:06:12 +02:00
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
|
|
|
# This is one of several classes that constitute the API
|
|
|
|
# This class was written by Vaibhav Bhatia.
|
|
|
|
# Modified by Jonathan Warren (Atheros).
|
|
|
|
# Further modified by the Bitmessage developers
|
|
|
|
# http://code.activestate.com/recipes/501148
|
2018-10-25 16:52:19 +02:00
|
|
|
class BMXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
2018-10-22 19:06:12 +02:00
|
|
|
"""The main API handler"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
# pylint: disable=protected-access
|
2014-01-13 01:56:30 +01:00
|
|
|
def do_POST(self):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""
|
|
|
|
Handles the HTTP POST request.
|
|
|
|
|
|
|
|
Attempts to interpret all HTTP POST requests as XML-RPC calls,
|
|
|
|
which are forwarded to the server's _dispatch method for handling.
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
.. note:: this method is the same as in
|
|
|
|
`SimpleXMLRPCServer.SimpleXMLRPCRequestHandler`,
|
|
|
|
just hacked to handle cookies
|
2018-10-10 12:41:44 +02:00
|
|
|
"""
|
2014-01-13 01:56:30 +01:00
|
|
|
|
|
|
|
# Check that the path is legal
|
|
|
|
if not self.is_rpc_path_valid():
|
|
|
|
self.report_404()
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Get arguments by reading body of request.
|
|
|
|
# We read this in chunks to avoid straining
|
|
|
|
# socket.read(); around the 10 or 15Mb mark, some platforms
|
|
|
|
# begin to have problems (bug #792570).
|
|
|
|
max_chunk_size = 10 * 1024 * 1024
|
|
|
|
size_remaining = int(self.headers["content-length"])
|
|
|
|
L = []
|
|
|
|
while size_remaining:
|
|
|
|
chunk_size = min(size_remaining, max_chunk_size)
|
|
|
|
L.append(self.rfile.read(chunk_size))
|
|
|
|
size_remaining -= len(L[-1])
|
|
|
|
data = ''.join(L)
|
|
|
|
|
2018-10-25 16:52:19 +02:00
|
|
|
# pylint: disable=attribute-defined-outside-init
|
|
|
|
self.cookies = []
|
|
|
|
|
|
|
|
validuser = self.APIAuthenticateClient()
|
|
|
|
if not validuser:
|
|
|
|
time.sleep(2)
|
2018-10-26 13:45:37 +02:00
|
|
|
self.send_response(httplib.UNAUTHORIZED)
|
|
|
|
self.end_headers()
|
|
|
|
return
|
|
|
|
# "RPC Username or password incorrect or HTTP header"
|
|
|
|
# " lacks authentication at all."
|
2018-10-25 16:52:19 +02:00
|
|
|
else:
|
|
|
|
# In previous versions of SimpleXMLRPCServer, _dispatch
|
|
|
|
# could be overridden in this class, instead of in
|
|
|
|
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
|
|
|
|
# check to see if a subclass implements _dispatch and dispatch
|
|
|
|
# using that method if present.
|
2018-11-05 17:35:38 +01:00
|
|
|
|
2018-10-25 16:52:19 +02:00
|
|
|
response = self.server._marshaled_dispatch(
|
|
|
|
data, getattr(self, '_dispatch', None)
|
|
|
|
)
|
|
|
|
except Exception: # This should only happen if the module is buggy
|
2014-01-13 01:56:30 +01:00
|
|
|
# internal error, report as HTTP server error
|
2019-05-03 15:34:54 +02:00
|
|
|
self.send_response(httplib.INTERNAL_SERVER_ERROR)
|
2014-01-13 01:56:30 +01:00
|
|
|
self.end_headers()
|
|
|
|
else:
|
|
|
|
# got a valid XML RPC response
|
2019-05-03 15:34:54 +02:00
|
|
|
self.send_response(httplib.OK)
|
2018-10-26 13:45:37 +02:00
|
|
|
self.send_header("Content-type", self.server.content_type)
|
2014-01-13 01:56:30 +01:00
|
|
|
self.send_header("Content-length", str(len(response)))
|
|
|
|
|
|
|
|
# HACK :start -> sends cookies here
|
|
|
|
if self.cookies:
|
|
|
|
for cookie in self.cookies:
|
|
|
|
self.send_header('Set-Cookie', cookie.output(header=''))
|
|
|
|
# HACK :end
|
|
|
|
|
|
|
|
self.end_headers()
|
|
|
|
self.wfile.write(response)
|
|
|
|
|
|
|
|
# shut down the connection
|
|
|
|
self.wfile.flush()
|
|
|
|
self.connection.shutdown(1)
|
|
|
|
|
2019-07-22 11:03:48 +02:00
|
|
|
# actually handle shutdown command after sending response
|
|
|
|
if state.shutdown is False:
|
|
|
|
shutdown.doCleanShutdown()
|
|
|
|
|
2014-01-13 01:56:30 +01:00
|
|
|
def APIAuthenticateClient(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Predicate to check for valid API credentials in the request header
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2014-01-13 01:56:30 +01:00
|
|
|
if 'Authorization' in self.headers:
|
|
|
|
# handle Basic authentication
|
2018-10-22 19:06:12 +02:00
|
|
|
encstr = self.headers.get('Authorization').split()[1]
|
2018-04-08 17:28:08 +02:00
|
|
|
emailid, password = encstr.decode('base64').split(':')
|
|
|
|
return (
|
2018-11-05 17:35:38 +01:00
|
|
|
emailid == BMConfigParser().get(
|
|
|
|
'bitmessagesettings', 'apiusername'
|
|
|
|
) and password == BMConfigParser().get(
|
|
|
|
'bitmessagesettings', 'apipassword'))
|
2014-01-13 01:56:30 +01:00
|
|
|
else:
|
2018-04-08 17:28:08 +02:00
|
|
|
logger.warning(
|
|
|
|
'Authentication failed because header lacks'
|
|
|
|
' Authentication field')
|
2014-01-13 01:56:30 +01:00
|
|
|
time.sleep(2)
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2018-10-25 16:52:19 +02:00
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
# pylint: disable=no-self-use,no-member,too-many-public-methods
|
2018-10-25 23:19:07 +02:00
|
|
|
class BMRPCDispatcher(object):
|
2018-10-25 16:52:19 +02:00
|
|
|
"""This class is used to dispatch API commands"""
|
|
|
|
__metaclass__ = CommandHandler
|
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
@staticmethod
|
|
|
|
def _decode(text, decode_type):
|
2014-01-13 01:56:30 +01:00
|
|
|
try:
|
2017-06-03 02:53:13 +02:00
|
|
|
if decode_type == 'hex':
|
|
|
|
return unhexlify(text)
|
|
|
|
elif decode_type == 'base64':
|
|
|
|
return base64.b64decode(text)
|
2014-01-13 01:56:30 +01:00
|
|
|
except Exception as e:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
2018-10-25 11:52:16 +02:00
|
|
|
22, 'Decode error - %s. Had trouble while decoding string: %r'
|
2018-04-08 17:28:08 +02:00
|
|
|
% (e, text)
|
|
|
|
)
|
2014-01-13 01:56:30 +01:00
|
|
|
|
|
|
|
def _verifyAddress(self, address):
|
2018-04-08 17:28:08 +02:00
|
|
|
status, addressVersionNumber, streamNumber, ripe = \
|
|
|
|
decodeAddress(address)
|
2014-01-13 01:56:30 +01:00
|
|
|
if status != 'success':
|
|
|
|
if status == 'checksumfailed':
|
|
|
|
raise APIError(8, 'Checksum failed for address: ' + address)
|
|
|
|
if status == 'invalidcharacters':
|
|
|
|
raise APIError(9, 'Invalid characters in address: ' + address)
|
|
|
|
if status == 'versiontoohigh':
|
2020-01-17 14:27:36 +01:00
|
|
|
raise APIError(
|
2018-11-05 17:35:38 +01:00
|
|
|
10, 'Address version number too high (or zero) in address: '
|
|
|
|
+ address)
|
2014-08-27 09:14:32 +02:00
|
|
|
if status == 'varintmalformed':
|
|
|
|
raise APIError(26, 'Malformed varint in address: ' + address)
|
2020-01-17 14:27:36 +01:00
|
|
|
raise APIError(
|
|
|
|
7, 'Could not decode address: %s : %s' % (address, status))
|
2014-01-13 01:56:30 +01:00
|
|
|
if addressVersionNumber < 2 or addressVersionNumber > 4:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
11, 'The address version number currently must be 2, 3 or 4.'
|
|
|
|
' Others aren\'t supported. Check the address.'
|
|
|
|
)
|
2014-01-13 01:56:30 +01:00
|
|
|
if streamNumber != 1:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
12, 'The stream number must be 1. Others aren\'t supported.'
|
|
|
|
' Check the address.'
|
|
|
|
)
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2018-10-29 16:38:57 +01:00
|
|
|
return {
|
|
|
|
'status': status,
|
|
|
|
'addressVersion': addressVersionNumber,
|
|
|
|
'streamNumber': streamNumber,
|
|
|
|
'ripe': base64.b64encode(ripe)
|
|
|
|
} if self._method == 'decodeAddress' else (
|
|
|
|
status, addressVersionNumber, streamNumber, ripe)
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2018-10-23 13:37:51 +02:00
|
|
|
@staticmethod
|
2018-11-05 17:35:38 +01:00
|
|
|
def _dump_inbox_message( # pylint: disable=too-many-arguments
|
2018-10-23 13:37:51 +02:00
|
|
|
msgid, toAddress, fromAddress, subject, received,
|
|
|
|
message, encodingtype, read):
|
|
|
|
subject = shared.fixPotentiallyInvalidUTF8Data(subject)
|
|
|
|
message = shared.fixPotentiallyInvalidUTF8Data(message)
|
|
|
|
return {
|
|
|
|
'msgid': hexlify(msgid),
|
|
|
|
'toAddress': toAddress,
|
|
|
|
'fromAddress': fromAddress,
|
|
|
|
'subject': base64.b64encode(subject),
|
|
|
|
'message': base64.b64encode(message),
|
|
|
|
'encodingType': encodingtype,
|
|
|
|
'receivedTime': received,
|
|
|
|
'read': read
|
|
|
|
}
|
|
|
|
|
|
|
|
@staticmethod
|
2018-11-05 17:35:38 +01:00
|
|
|
def _dump_sent_message( # pylint: disable=too-many-arguments
|
2018-10-23 13:37:51 +02:00
|
|
|
msgid, toAddress, fromAddress, subject, lastactiontime,
|
|
|
|
message, encodingtype, status, ackdata):
|
|
|
|
subject = shared.fixPotentiallyInvalidUTF8Data(subject)
|
|
|
|
message = shared.fixPotentiallyInvalidUTF8Data(message)
|
|
|
|
return {
|
|
|
|
'msgid': hexlify(msgid),
|
|
|
|
'toAddress': toAddress,
|
|
|
|
'fromAddress': fromAddress,
|
|
|
|
'subject': base64.b64encode(subject),
|
|
|
|
'message': base64.b64encode(message),
|
|
|
|
'encodingType': encodingtype,
|
|
|
|
'lastActionTime': lastactiontime,
|
|
|
|
'status': status,
|
|
|
|
'ackData': hexlify(ackdata)
|
|
|
|
}
|
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
# Request Handlers
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-10-29 16:38:57 +01:00
|
|
|
@command('decodeAddress')
|
|
|
|
def HandleDecodeAddress(self, address):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Decode given address and return dict with
|
|
|
|
status, addressVersion, streamNumber and ripe keys
|
|
|
|
"""
|
2018-10-29 16:38:57 +01:00
|
|
|
return self._verifyAddress(address)
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('listAddresses', 'listAddresses2')
|
|
|
|
def HandleListAddresses(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns dict with a list of all used addresses with their properties
|
|
|
|
in the *addresses* key.
|
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
data = []
|
2018-10-25 11:52:16 +02:00
|
|
|
for address in self.config.addresses():
|
2018-10-22 19:06:12 +02:00
|
|
|
streamNumber = decodeAddress(address)[2]
|
2018-10-25 11:52:16 +02:00
|
|
|
label = self.config.get(address, 'label')
|
2018-10-22 19:06:12 +02:00
|
|
|
if self._method == 'listAddresses2':
|
2017-06-03 02:53:13 +02:00
|
|
|
label = base64.b64encode(label)
|
2018-10-22 19:06:12 +02:00
|
|
|
data.append({
|
2018-04-08 17:28:08 +02:00
|
|
|
'label': label,
|
2018-10-22 19:06:12 +02:00
|
|
|
'address': address,
|
2018-04-08 17:28:08 +02:00
|
|
|
'stream': streamNumber,
|
2018-10-25 11:52:16 +02:00
|
|
|
'enabled': self.config.safeGetBoolean(address, 'enabled'),
|
|
|
|
'chan': self.config.safeGetBoolean(address, 'chan')
|
2018-10-22 19:06:12 +02:00
|
|
|
})
|
|
|
|
return {'addresses': data}
|
|
|
|
|
|
|
|
# the listAddressbook alias should be removed eventually.
|
2018-10-30 08:17:54 +01:00
|
|
|
@command('listAddressBookEntries', 'legacy:listAddressbook')
|
2018-10-22 19:06:12 +02:00
|
|
|
def HandleListAddressBookEntries(self, label=None):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns dict with a list of all address book entries (address and label)
|
|
|
|
in the *addresses* key.
|
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT label, address from addressbook WHERE label = ?",
|
|
|
|
label
|
|
|
|
) if label else sqlQuery("SELECT label, address from addressbook")
|
|
|
|
data = []
|
|
|
|
for label, address in queryreturn:
|
2015-03-21 12:53:09 +01:00
|
|
|
label = shared.fixPotentiallyInvalidUTF8Data(label)
|
2018-10-22 19:06:12 +02:00
|
|
|
data.append({
|
2018-04-08 17:28:08 +02:00
|
|
|
'label': base64.b64encode(label),
|
2018-10-22 19:06:12 +02:00
|
|
|
'address': address
|
|
|
|
})
|
|
|
|
return {'addresses': data}
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
# the addAddressbook alias should be deleted eventually.
|
2018-10-30 08:17:54 +01:00
|
|
|
@command('addAddressBookEntry', 'legacy:addAddressbook')
|
2018-10-22 19:06:12 +02:00
|
|
|
def HandleAddAddressBookEntry(self, address, label):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Add an entry to address book. label must be base64 encoded."""
|
2015-03-21 12:53:09 +01:00
|
|
|
label = self._decode(label, "base64")
|
|
|
|
address = addBMIfNotPresent(address)
|
|
|
|
self._verifyAddress(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
# TODO: add unique together constraint in the table
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT address FROM addressbook WHERE address=?", address)
|
2015-03-21 12:53:09 +01:00
|
|
|
if queryreturn != []:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
16, 'You already have this address in your address book.')
|
2015-03-21 12:53:09 +01:00
|
|
|
|
|
|
|
sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address)
|
2018-04-08 17:28:08 +02:00
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistToLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderAddressBook', ''))
|
2015-03-21 12:53:09 +01:00
|
|
|
return "Added address %s to address book" % address
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
# the deleteAddressbook alias should be deleted eventually.
|
2018-10-30 08:17:54 +01:00
|
|
|
@command('deleteAddressBookEntry', 'legacy:deleteAddressbook')
|
2018-10-22 19:06:12 +02:00
|
|
|
def HandleDeleteAddressBookEntry(self, address):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Delete an entry from address book."""
|
2015-03-21 12:53:09 +01:00
|
|
|
address = addBMIfNotPresent(address)
|
|
|
|
self._verifyAddress(address)
|
|
|
|
sqlExecute('DELETE FROM addressbook WHERE address=?', address)
|
2018-04-08 17:28:08 +02:00
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistToLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderAddressBook', ''))
|
2015-03-21 12:53:09 +01:00
|
|
|
return "Deleted address book entry for %s if it existed" % address
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('createRandomAddress')
|
|
|
|
def HandleCreateRandomAddress(
|
|
|
|
self, label, eighteenByteRipe=False, totalDifficulty=0,
|
|
|
|
smallMessageDifficulty=0
|
|
|
|
):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Create one address using the random number generator.
|
|
|
|
|
|
|
|
:param str label: base64 encoded label for the address
|
|
|
|
:param bool eighteenByteRipe: is telling Bitmessage whether to
|
|
|
|
generate an address with an 18 byte RIPE hash
|
|
|
|
(as opposed to a 19 byte hash).
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-25 11:52:16 +02:00
|
|
|
nonceTrialsPerByte = self.config.get(
|
2018-10-22 19:06:12 +02:00
|
|
|
'bitmessagesettings', 'defaultnoncetrialsperbyte'
|
|
|
|
) if not totalDifficulty else int(
|
2018-11-05 17:35:38 +01:00
|
|
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
|
|
|
* totalDifficulty)
|
2018-10-25 11:52:16 +02:00
|
|
|
payloadLengthExtraBytes = self.config.get(
|
2018-10-22 19:06:12 +02:00
|
|
|
'bitmessagesettings', 'defaultpayloadlengthextrabytes'
|
|
|
|
) if not smallMessageDifficulty else int(
|
2018-11-05 17:35:38 +01:00
|
|
|
defaults.networkDefaultPayloadLengthExtraBytes
|
|
|
|
* smallMessageDifficulty)
|
2018-10-22 19:06:12 +02:00
|
|
|
|
|
|
|
if not isinstance(eighteenByteRipe, bool):
|
|
|
|
raise APIError(
|
2018-11-05 17:35:38 +01:00
|
|
|
23, 'Bool expected in eighteenByteRipe, saw %s instead'
|
|
|
|
% type(eighteenByteRipe))
|
2015-03-21 12:53:09 +01:00
|
|
|
label = self._decode(label, "base64")
|
|
|
|
try:
|
2021-08-27 18:17:24 +02:00
|
|
|
label.decode('utf-8')
|
2018-10-22 19:06:12 +02:00
|
|
|
except UnicodeDecodeError:
|
2015-03-21 12:53:09 +01:00
|
|
|
raise APIError(17, 'Label is not valid UTF-8 data.')
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
2018-10-22 19:06:12 +02:00
|
|
|
# FIXME hard coded stream no
|
2015-03-21 12:53:09 +01:00
|
|
|
streamNumberForAddress = 1
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.addressGeneratorQueue.put((
|
2018-04-08 17:28:08 +02:00
|
|
|
'createRandomAddress', 4, streamNumberForAddress, label, 1, "",
|
|
|
|
eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes
|
|
|
|
))
|
2017-02-08 13:41:56 +01:00
|
|
|
return queues.apiAddressGeneratorReturnQueue.get()
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-11-05 17:35:38 +01:00
|
|
|
# pylint: disable=too-many-arguments
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('createDeterministicAddresses')
|
|
|
|
def HandleCreateDeterministicAddresses(
|
|
|
|
self, passphrase, numberOfAddresses=1, addressVersionNumber=0,
|
|
|
|
streamNumber=0, eighteenByteRipe=False, totalDifficulty=0,
|
|
|
|
smallMessageDifficulty=0
|
|
|
|
):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Create many addresses deterministically using the passphrase.
|
|
|
|
|
|
|
|
:param str passphrase: base64 encoded passphrase
|
|
|
|
:param int numberOfAddresses: number of addresses to create,
|
|
|
|
up to 999
|
|
|
|
|
|
|
|
*addressVersionNumber* and *streamNumber* may be set to 0
|
|
|
|
which will tell Bitmessage to use the most up-to-date
|
|
|
|
address version and the most available stream.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-25 11:52:16 +02:00
|
|
|
nonceTrialsPerByte = self.config.get(
|
2018-10-22 19:06:12 +02:00
|
|
|
'bitmessagesettings', 'defaultnoncetrialsperbyte'
|
|
|
|
) if not totalDifficulty else int(
|
2018-11-05 17:35:38 +01:00
|
|
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
|
|
|
* totalDifficulty)
|
2018-10-25 11:52:16 +02:00
|
|
|
payloadLengthExtraBytes = self.config.get(
|
2018-10-22 19:06:12 +02:00
|
|
|
'bitmessagesettings', 'defaultpayloadlengthextrabytes'
|
|
|
|
) if not smallMessageDifficulty else int(
|
2018-11-05 17:35:38 +01:00
|
|
|
defaults.networkDefaultPayloadLengthExtraBytes
|
|
|
|
* smallMessageDifficulty)
|
2018-10-22 19:06:12 +02:00
|
|
|
|
2018-10-10 12:41:44 +02:00
|
|
|
if not passphrase:
|
2015-03-21 12:53:09 +01:00
|
|
|
raise APIError(1, 'The specified passphrase is blank.')
|
|
|
|
if not isinstance(eighteenByteRipe, bool):
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
2018-11-05 17:35:38 +01:00
|
|
|
23, 'Bool expected in eighteenByteRipe, saw %s instead'
|
|
|
|
% type(eighteenByteRipe))
|
2015-03-21 12:53:09 +01:00
|
|
|
passphrase = self._decode(passphrase, "base64")
|
2018-04-08 17:28:08 +02:00
|
|
|
# 0 means "just use the proper addressVersionNumber"
|
|
|
|
if addressVersionNumber == 0:
|
2014-01-13 01:56:30 +01:00
|
|
|
addressVersionNumber = 4
|
2018-10-22 19:06:12 +02:00
|
|
|
if addressVersionNumber not in (3, 4):
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
2, 'The address version number currently must be 3, 4, or 0'
|
2018-11-05 17:35:38 +01:00
|
|
|
' (which means auto-select). %i isn\'t supported.'
|
|
|
|
% addressVersionNumber)
|
2015-03-21 12:53:09 +01:00
|
|
|
if streamNumber == 0: # 0 means "just use the most available stream"
|
2018-10-22 19:06:12 +02:00
|
|
|
streamNumber = 1 # FIXME hard coded stream no
|
2015-03-21 12:53:09 +01:00
|
|
|
if streamNumber != 1:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
3, 'The stream number must be 1 (or 0 which means'
|
|
|
|
' auto-select). Others aren\'t supported.')
|
2015-03-21 12:53:09 +01:00
|
|
|
if numberOfAddresses == 0:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
4, 'Why would you ask me to generate 0 addresses for you?')
|
2015-03-21 12:53:09 +01:00
|
|
|
if numberOfAddresses > 999:
|
2018-04-08 17:28:08 +02:00
|
|
|
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.')
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
2018-04-08 17:28:08 +02:00
|
|
|
logger.debug(
|
|
|
|
'Requesting that the addressGenerator create %s addresses.',
|
|
|
|
numberOfAddresses)
|
|
|
|
queues.addressGeneratorQueue.put((
|
|
|
|
'createDeterministicAddresses', addressVersionNumber, streamNumber,
|
|
|
|
'unused API address', numberOfAddresses, passphrase,
|
|
|
|
eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes
|
|
|
|
))
|
2018-10-22 19:06:12 +02:00
|
|
|
|
|
|
|
return {'addresses': queues.apiAddressGeneratorReturnQueue.get()}
|
|
|
|
|
|
|
|
@command('getDeterministicAddress')
|
|
|
|
def HandleGetDeterministicAddress(
|
|
|
|
self, passphrase, addressVersionNumber, streamNumber):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Similar to *createDeterministicAddresses* except that the one
|
|
|
|
address that is returned will not be added to the Bitmessage
|
|
|
|
user interface or the keys.dat file.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-03-21 12:53:09 +01:00
|
|
|
numberOfAddresses = 1
|
|
|
|
eighteenByteRipe = False
|
2018-10-10 12:41:44 +02:00
|
|
|
if not passphrase:
|
2015-03-21 12:53:09 +01:00
|
|
|
raise APIError(1, 'The specified passphrase is blank.')
|
|
|
|
passphrase = self._decode(passphrase, "base64")
|
2018-10-22 19:06:12 +02:00
|
|
|
if addressVersionNumber not in (3, 4):
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
2, 'The address version number currently must be 3 or 4. %i'
|
|
|
|
' isn\'t supported.' % addressVersionNumber)
|
2015-03-21 12:53:09 +01:00
|
|
|
if streamNumber != 1:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
3, ' The stream number must be 1. Others aren\'t supported.')
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
2018-04-08 17:28:08 +02:00
|
|
|
logger.debug(
|
|
|
|
'Requesting that the addressGenerator create %s addresses.',
|
|
|
|
numberOfAddresses)
|
|
|
|
queues.addressGeneratorQueue.put((
|
|
|
|
'getDeterministicAddress', addressVersionNumber, streamNumber,
|
|
|
|
'unused API address', numberOfAddresses, passphrase,
|
|
|
|
eighteenByteRipe
|
|
|
|
))
|
2017-02-08 13:41:56 +01:00
|
|
|
return queues.apiAddressGeneratorReturnQueue.get()
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('createChan')
|
|
|
|
def HandleCreateChan(self, passphrase):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Creates a new chan. passphrase must be base64 encoded.
|
|
|
|
Returns the corresponding Bitmessage address.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-09-28 20:55:40 +02:00
|
|
|
passphrase = self._decode(passphrase, "base64")
|
2018-10-10 12:41:44 +02:00
|
|
|
if not passphrase:
|
2015-09-28 20:55:40 +02:00
|
|
|
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:
|
2021-08-27 18:17:24 +02:00
|
|
|
passphrase.decode('utf-8')
|
2015-09-28 20:55:40 +02:00
|
|
|
label = str_chan + ' ' + passphrase
|
2018-10-22 19:06:12 +02:00
|
|
|
except UnicodeDecodeError:
|
2015-09-28 20:55:40 +02:00
|
|
|
label = str_chan + ' ' + repr(passphrase)
|
|
|
|
|
|
|
|
addressVersionNumber = 4
|
|
|
|
streamNumber = 1
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
2018-04-08 17:28:08 +02:00
|
|
|
logger.debug(
|
|
|
|
'Requesting that the addressGenerator create chan %s.', passphrase)
|
|
|
|
queues.addressGeneratorQueue.put((
|
|
|
|
'createChan', addressVersionNumber, streamNumber, label,
|
|
|
|
passphrase, True
|
|
|
|
))
|
2017-02-08 13:41:56 +01:00
|
|
|
queueReturn = queues.apiAddressGeneratorReturnQueue.get()
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
|
|
|
return queueReturn[0]
|
|
|
|
except IndexError:
|
2015-09-28 20:55:40 +02:00
|
|
|
raise APIError(24, 'Chan address is already present.')
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('joinChan')
|
|
|
|
def HandleJoinChan(self, passphrase, suppliedAddress):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Join a chan. passphrase must be base64 encoded. Returns 'success'.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-09-28 20:55:40 +02:00
|
|
|
passphrase = self._decode(passphrase, "base64")
|
2018-10-10 12:41:44 +02:00
|
|
|
if not passphrase:
|
2015-09-28 20:55:40 +02:00
|
|
|
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:
|
2021-08-27 18:17:24 +02:00
|
|
|
passphrase.decode('utf-8')
|
2015-09-28 20:55:40 +02:00
|
|
|
label = str_chan + ' ' + passphrase
|
2018-10-22 19:06:12 +02:00
|
|
|
except UnicodeDecodeError:
|
2015-09-28 20:55:40 +02:00
|
|
|
label = str_chan + ' ' + repr(passphrase)
|
2018-10-22 19:06:12 +02:00
|
|
|
|
|
|
|
self._verifyAddress(suppliedAddress)
|
2015-09-28 20:55:40 +02:00
|
|
|
suppliedAddress = addBMIfNotPresent(suppliedAddress)
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
2018-04-08 17:28:08 +02:00
|
|
|
queues.addressGeneratorQueue.put((
|
|
|
|
'joinChan', suppliedAddress, label, passphrase, True
|
|
|
|
))
|
2018-10-22 19:06:12 +02:00
|
|
|
queueReturn = queues.apiAddressGeneratorReturnQueue.get()
|
|
|
|
try:
|
|
|
|
if queueReturn[0] == 'chan name does not match address':
|
|
|
|
raise APIError(18, 'Chan name does not match address.')
|
|
|
|
except IndexError:
|
2015-09-28 20:55:40 +02:00
|
|
|
raise APIError(24, 'Chan address is already present.')
|
2018-10-22 19:06:12 +02:00
|
|
|
|
2015-09-28 20:55:40 +02:00
|
|
|
return "success"
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('leaveChan')
|
|
|
|
def HandleLeaveChan(self, address):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Leave a chan. Returns 'success'.
|
|
|
|
|
|
|
|
.. note:: at this time, the address is still shown in the UI
|
|
|
|
until a restart.
|
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
self._verifyAddress(address)
|
2015-09-28 20:55:40 +02:00
|
|
|
address = addBMIfNotPresent(address)
|
2018-10-25 11:52:16 +02:00
|
|
|
if not self.config.safeGetBoolean(address, 'chan'):
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
25, 'Specified address is not a chan address.'
|
|
|
|
' Use deleteAddress API call instead.')
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2018-10-25 11:52:16 +02:00
|
|
|
self.config.remove_section(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
except ConfigParser.NoSectionError:
|
|
|
|
raise APIError(
|
|
|
|
13, 'Could not find this address in your keys.dat file.')
|
2018-10-25 11:52:16 +02:00
|
|
|
self.config.save()
|
2018-10-22 19:06:12 +02:00
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistToLabels', ''))
|
|
|
|
return "success"
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('deleteAddress')
|
|
|
|
def HandleDeleteAddress(self, address):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Permanently delete the address from keys.dat file. Returns 'success'.
|
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
self._verifyAddress(address)
|
2015-09-28 20:55:40 +02:00
|
|
|
address = addBMIfNotPresent(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2018-10-25 11:52:16 +02:00
|
|
|
self.config.remove_section(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
except ConfigParser.NoSectionError:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
13, 'Could not find this address in your keys.dat file.')
|
2018-10-25 11:52:16 +02:00
|
|
|
self.config.save()
|
2019-03-05 17:47:37 +01:00
|
|
|
queues.UISignalQueue.put(('writeNewAddressToTable', ('', '', '')))
|
2015-09-28 20:55:40 +02:00
|
|
|
shared.reloadMyAddressHashes()
|
2018-10-22 19:06:12 +02:00
|
|
|
return "success"
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getAllInboxMessages')
|
|
|
|
def HandleGetAllInboxMessages(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns a dict with all inbox messages in the *inboxMessages* key.
|
|
|
|
The message is a dict with such keys:
|
|
|
|
*msgid*, *toAddress*, *fromAddress*, *subject*, *message*,
|
|
|
|
*encodingType*, *receivedTime*, *read*.
|
|
|
|
*msgid* is hex encoded string.
|
|
|
|
*subject* and *message* are base64 encoded.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-09-28 20:55:40 +02:00
|
|
|
queryreturn = sqlQuery(
|
2018-04-08 17:28:08 +02:00
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, received, message,"
|
2018-10-22 19:06:12 +02:00
|
|
|
" encodingtype, read FROM inbox WHERE folder='inbox'"
|
2018-04-08 17:28:08 +02:00
|
|
|
" ORDER BY received"
|
|
|
|
)
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"inboxMessages": [
|
|
|
|
self._dump_inbox_message(*data) for data in queryreturn
|
|
|
|
]}
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getAllInboxMessageIds', 'getAllInboxMessageIDs')
|
|
|
|
def HandleGetAllInboxMessageIds(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The same as *getAllInboxMessages* but returns only *msgid*s,
|
|
|
|
result key - *inboxMessageIds*.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-09-28 20:55:40 +02:00
|
|
|
queryreturn = sqlQuery(
|
2018-04-08 17:28:08 +02:00
|
|
|
"SELECT msgid FROM inbox where folder='inbox' ORDER BY received")
|
2018-10-22 19:06:12 +02:00
|
|
|
|
|
|
|
return {"inboxMessageIds": [
|
|
|
|
{'msgid': hexlify(msgid)} for msgid, in queryreturn
|
|
|
|
]}
|
|
|
|
|
|
|
|
@command('getInboxMessageById', 'getInboxMessageByID')
|
|
|
|
def HandleGetInboxMessageById(self, hid, readStatus=None):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns a dict with list containing single message in the result
|
|
|
|
key *inboxMessage*. May also return None if message was not found.
|
|
|
|
|
|
|
|
:param str hid: hex encoded msgid
|
|
|
|
:param bool readStatus: sets the message's read status if present
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
msgid = self._decode(hid, "hex")
|
|
|
|
if readStatus is not None:
|
2015-03-21 12:53:09 +01:00
|
|
|
if not isinstance(readStatus, bool):
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
2018-11-05 17:35:38 +01:00
|
|
|
23, 'Bool expected in readStatus, saw %s instead.'
|
|
|
|
% type(readStatus))
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT read FROM inbox WHERE msgid=?", msgid)
|
2015-03-21 12:53:09 +01:00
|
|
|
# UPDATE is slow, only update if status is different
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
|
|
|
if (queryreturn[0][0] == 1) != readStatus:
|
|
|
|
sqlExecute(
|
|
|
|
"UPDATE inbox set read = ? WHERE msgid=?",
|
|
|
|
readStatus, msgid)
|
|
|
|
queues.UISignalQueue.put(('changedInboxUnread', None))
|
|
|
|
except IndexError:
|
|
|
|
pass
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
2020-10-04 16:24:45 +02:00
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, received, message,"
|
2018-04-08 17:28:08 +02:00
|
|
|
" encodingtype, read FROM inbox WHERE msgid=?", msgid
|
|
|
|
)
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"inboxMessage": [
|
|
|
|
self._dump_inbox_message(*queryreturn[0])]}
|
2018-10-22 19:06:12 +02:00
|
|
|
except IndexError:
|
2018-10-23 13:37:51 +02:00
|
|
|
pass # FIXME inconsistent
|
2018-10-22 19:06:12 +02:00
|
|
|
|
|
|
|
@command('getAllSentMessages')
|
|
|
|
def HandleGetAllSentMessages(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The same as *getAllInboxMessages* but for sent,
|
|
|
|
result key - *sentMessages*. Message dict keys are:
|
|
|
|
*msgid*, *toAddress*, *fromAddress*, *subject*, *message*,
|
|
|
|
*encodingType*, *lastActionTime*, *status*, *ackData*.
|
|
|
|
*ackData* is also a hex encoded string.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, lastactiontime,"
|
|
|
|
" message, encodingtype, status, ackdata FROM sent"
|
|
|
|
" WHERE folder='sent' ORDER BY lastactiontime"
|
|
|
|
)
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"sentMessages": [
|
|
|
|
self._dump_sent_message(*data) for data in queryreturn
|
|
|
|
]}
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getAllSentMessageIds', 'getAllSentMessageIDs')
|
|
|
|
def HandleGetAllSentMessageIds(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The same as *getAllInboxMessageIds* but for sent,
|
|
|
|
result key - *sentMessageIds*.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
2018-10-22 19:06:12 +02:00
|
|
|
"SELECT msgid FROM sent WHERE folder='sent'"
|
2018-04-08 17:28:08 +02:00
|
|
|
" ORDER BY lastactiontime"
|
|
|
|
)
|
2018-10-22 19:06:12 +02:00
|
|
|
return {"sentMessageIds": [
|
|
|
|
{'msgid': hexlify(msgid)} for msgid, in queryreturn
|
|
|
|
]}
|
|
|
|
|
|
|
|
# after some time getInboxMessagesByAddress should be removed
|
2018-10-30 08:17:54 +01:00
|
|
|
@command('getInboxMessagesByReceiver', 'legacy:getInboxMessagesByAddress')
|
2018-10-22 19:06:12 +02:00
|
|
|
def HandleInboxMessagesByReceiver(self, toAddress):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The same as *getAllInboxMessages* but returns only messages
|
|
|
|
for toAddress.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
2018-10-23 13:37:51 +02:00
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, received,"
|
|
|
|
" message, encodingtype, read FROM inbox WHERE folder='inbox'"
|
|
|
|
" AND toAddress=?", toAddress)
|
|
|
|
return {"inboxMessages": [
|
|
|
|
self._dump_inbox_message(*data) for data in queryreturn
|
|
|
|
]}
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getSentMessageById', 'getSentMessageByID')
|
|
|
|
def HandleGetSentMessageById(self, hid):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Similiar to *getInboxMessageById* but doesn't change message's
|
|
|
|
read status (sent messages have no such field).
|
|
|
|
Result key is *sentMessage*
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
msgid = self._decode(hid, "hex")
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, lastactiontime,"
|
|
|
|
" message, encodingtype, status, ackdata FROM sent WHERE msgid=?",
|
|
|
|
msgid
|
|
|
|
)
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"sentMessage": [
|
|
|
|
self._dump_sent_message(*queryreturn[0])
|
|
|
|
]}
|
2018-10-22 19:06:12 +02:00
|
|
|
except IndexError:
|
2018-10-23 13:37:51 +02:00
|
|
|
pass # FIXME inconsistent
|
2014-01-13 01:56:30 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getSentMessagesByAddress', 'getSentMessagesBySender')
|
|
|
|
def HandleGetSentMessagesByAddress(self, fromAddress):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
The same as *getAllSentMessages* but returns only messages
|
|
|
|
from fromAddress.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, lastactiontime,"
|
|
|
|
" message, encodingtype, status, ackdata FROM sent"
|
|
|
|
" WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime",
|
|
|
|
fromAddress
|
|
|
|
)
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"sentMessages": [
|
|
|
|
self._dump_sent_message(*data) for data in queryreturn
|
|
|
|
]}
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getSentMessageByAckData')
|
|
|
|
def HandleGetSentMessagesByAckData(self, ackData):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Similiar to *getSentMessageById* but searches by ackdata
|
|
|
|
(also hex encoded).
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
ackData = self._decode(ackData, "hex")
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT msgid, toaddress, fromaddress, subject, lastactiontime,"
|
|
|
|
" message, encodingtype, status, ackdata FROM sent"
|
|
|
|
" WHERE ackdata=?", ackData
|
|
|
|
)
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2018-10-23 13:37:51 +02:00
|
|
|
return {"sentMessage": [
|
|
|
|
self._dump_sent_message(*queryreturn[0])
|
|
|
|
]}
|
2018-10-22 19:06:12 +02:00
|
|
|
except IndexError:
|
2018-10-23 13:37:51 +02:00
|
|
|
pass # FIXME inconsistent
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('trashMessage')
|
|
|
|
def HandleTrashMessage(self, msgid):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Trash message by msgid (encoded in hex). Returns a simple message
|
|
|
|
saying that the message was trashed assuming it ever even existed.
|
|
|
|
Prior existence is not checked.
|
|
|
|
"""
|
2018-10-22 19:06:12 +02:00
|
|
|
msgid = self._decode(msgid, "hex")
|
2015-03-21 12:53:09 +01:00
|
|
|
# Trash if in inbox table
|
|
|
|
helper_inbox.trash(msgid)
|
|
|
|
# Trash if in sent table
|
2018-10-22 19:06:12 +02:00
|
|
|
sqlExecute("UPDATE sent SET folder='trash' WHERE msgid=?", msgid)
|
2015-03-21 12:53:09 +01:00
|
|
|
return 'Trashed message (assuming message existed).'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('trashInboxMessage')
|
|
|
|
def HandleTrashInboxMessage(self, msgid):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Trash inbox message by msgid (encoded in hex)."""
|
2018-10-22 19:06:12 +02:00
|
|
|
msgid = self._decode(msgid, "hex")
|
2015-03-21 12:53:09 +01:00
|
|
|
helper_inbox.trash(msgid)
|
|
|
|
return 'Trashed inbox message (assuming message existed).'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('trashSentMessage')
|
|
|
|
def HandleTrashSentMessage(self, msgid):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Trash sent message by msgid (encoded in hex)."""
|
2018-10-22 19:06:12 +02:00
|
|
|
msgid = self._decode(msgid, "hex")
|
2015-03-21 12:53:09 +01:00
|
|
|
sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
|
|
|
|
return 'Trashed sent message (assuming message existed).'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('sendMessage')
|
|
|
|
def HandleSendMessage(
|
|
|
|
self, toAddress, fromAddress, subject, message,
|
|
|
|
encodingType=2, TTL=4 * 24 * 60 * 60
|
|
|
|
):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Send the message and return ackdata (hex encoded string).
|
|
|
|
subject and message must be encoded in base64 which may optionally
|
|
|
|
include line breaks. TTL is specified in seconds; values outside
|
|
|
|
the bounds of 3600 to 2419200 will be moved to be within those
|
|
|
|
bounds. TTL defaults to 4 days.
|
|
|
|
"""
|
|
|
|
# pylint: disable=too-many-locals
|
2018-10-22 19:06:12 +02:00
|
|
|
if encodingType not in (2, 3):
|
2017-04-30 10:39:48 +02:00
|
|
|
raise APIError(6, 'The encoding type must be 2 or 3.')
|
2015-03-21 12:53:09 +01:00
|
|
|
subject = self._decode(subject, "base64")
|
|
|
|
message = self._decode(message, "base64")
|
|
|
|
if len(subject + message) > (2 ** 18 - 500):
|
|
|
|
raise APIError(27, 'Message is too long.')
|
2018-04-10 09:14:32 +02:00
|
|
|
if TTL < 60 * 60:
|
|
|
|
TTL = 60 * 60
|
|
|
|
if TTL > 28 * 24 * 60 * 60:
|
|
|
|
TTL = 28 * 24 * 60 * 60
|
2015-03-21 12:53:09 +01:00
|
|
|
toAddress = addBMIfNotPresent(toAddress)
|
|
|
|
fromAddress = addBMIfNotPresent(fromAddress)
|
|
|
|
self._verifyAddress(fromAddress)
|
|
|
|
try:
|
2018-10-25 11:52:16 +02:00
|
|
|
fromAddressEnabled = self.config.getboolean(
|
2015-03-21 12:53:09 +01:00
|
|
|
fromAddress, 'enabled')
|
2018-10-10 12:41:44 +02:00
|
|
|
except BaseException:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
13, 'Could not find your fromAddress in the keys.dat file.')
|
2015-03-21 12:53:09 +01:00
|
|
|
if not fromAddressEnabled:
|
|
|
|
raise APIError(14, 'Your fromAddress is disabled. Cannot send.')
|
|
|
|
|
2020-11-17 20:36:05 +01:00
|
|
|
ackdata = helper_sent.insert(
|
2020-11-12 21:15:01 +01:00
|
|
|
toAddress=toAddress, fromAddress=fromAddress,
|
2021-01-08 01:51:12 +01:00
|
|
|
subject=subject, message=message, encoding=encodingType, ttl=TTL)
|
2015-03-21 12:53:09 +01:00
|
|
|
|
|
|
|
toLabel = ''
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT label FROM addressbook WHERE address=?", toAddress)
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
2021-12-11 15:16:50 +01:00
|
|
|
toLabel = queryreturn[0][0]
|
2018-10-22 19:06:12 +02:00
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.UISignalQueue.put(('displayNewSentMessage', (
|
2015-03-21 12:53:09 +01:00
|
|
|
toAddress, toLabel, fromAddress, subject, message, ackdata)))
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.workerQueue.put(('sendmessage', toAddress))
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2016-03-23 23:26:57 +01:00
|
|
|
return hexlify(ackdata)
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('sendBroadcast')
|
|
|
|
def HandleSendBroadcast(
|
|
|
|
self, fromAddress, subject, message, encodingType=2,
|
|
|
|
TTL=4 * 24 * 60 * 60):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Send the broadcast message. Similiar to *sendMessage*."""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
if encodingType not in (2, 3):
|
2017-05-27 07:48:29 +02:00
|
|
|
raise APIError(6, 'The encoding type must be 2 or 3.')
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-03-21 12:53:09 +01:00
|
|
|
subject = self._decode(subject, "base64")
|
|
|
|
message = self._decode(message, "base64")
|
|
|
|
if len(subject + message) > (2 ** 18 - 500):
|
|
|
|
raise APIError(27, 'Message is too long.')
|
2018-04-10 09:14:32 +02:00
|
|
|
if TTL < 60 * 60:
|
|
|
|
TTL = 60 * 60
|
|
|
|
if TTL > 28 * 24 * 60 * 60:
|
|
|
|
TTL = 28 * 24 * 60 * 60
|
2015-03-21 12:53:09 +01:00
|
|
|
fromAddress = addBMIfNotPresent(fromAddress)
|
|
|
|
self._verifyAddress(fromAddress)
|
|
|
|
try:
|
2018-10-25 11:52:16 +02:00
|
|
|
self.config.getboolean(fromAddress, 'enabled')
|
2018-10-10 12:41:44 +02:00
|
|
|
except BaseException:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
2018-10-25 11:52:16 +02:00
|
|
|
13, 'Could not find your fromAddress in the keys.dat file.')
|
2018-10-22 19:06:12 +02:00
|
|
|
toAddress = str_broadcast_subscribers
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2020-11-17 20:36:05 +01:00
|
|
|
ackdata = helper_sent.insert(
|
2020-11-16 14:20:28 +01:00
|
|
|
fromAddress=fromAddress, subject=subject,
|
|
|
|
message=message, status='broadcastqueued',
|
2020-11-12 21:15:01 +01:00
|
|
|
encoding=encodingType)
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
toLabel = str_broadcast_subscribers
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.UISignalQueue.put(('displayNewSentMessage', (
|
2015-03-21 12:53:09 +01:00
|
|
|
toAddress, toLabel, fromAddress, subject, message, ackdata)))
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.workerQueue.put(('sendbroadcast', ''))
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2016-03-23 23:26:57 +01:00
|
|
|
return hexlify(ackdata)
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('getStatus')
|
|
|
|
def HandleGetStatus(self, ackdata):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Get the status of sent message by its ackdata (hex encoded).
|
|
|
|
Returns one of these strings: notfound, msgqueued,
|
|
|
|
broadcastqueued, broadcastsent, doingpubkeypow, awaitingpubkey,
|
|
|
|
doingmsgpow, forcepow, msgsent, msgsentnoackexpected or ackreceived.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-05-05 14:38:05 +02:00
|
|
|
if len(ackdata) < 76:
|
2018-05-06 13:06:44 +02:00
|
|
|
# The length of ackData should be at least 38 bytes (76 hex digits)
|
|
|
|
raise APIError(15, 'Invalid ackData object size.')
|
2015-03-21 12:53:09 +01:00
|
|
|
ackdata = self._decode(ackdata, "hex")
|
|
|
|
queryreturn = sqlQuery(
|
2018-04-08 17:28:08 +02:00
|
|
|
"SELECT status FROM sent where ackdata=?", ackdata)
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
|
|
|
return queryreturn[0][0]
|
|
|
|
except IndexError:
|
2015-03-21 12:53:09 +01:00
|
|
|
return 'notfound'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('addSubscription')
|
|
|
|
def HandleAddSubscription(self, address, label=''):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Subscribe to the address. label must be base64 encoded."""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
if label:
|
2015-03-21 12:53:09 +01:00
|
|
|
label = self._decode(label, "base64")
|
2014-01-13 01:56:30 +01:00
|
|
|
try:
|
2021-08-27 18:17:24 +02:00
|
|
|
label.decode('utf-8')
|
2018-10-22 19:06:12 +02:00
|
|
|
except UnicodeDecodeError:
|
2015-03-21 12:53:09 +01:00
|
|
|
raise APIError(17, 'Label is not valid UTF-8 data.')
|
|
|
|
self._verifyAddress(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
address = addBMIfNotPresent(address)
|
2015-03-21 12:53:09 +01:00
|
|
|
# First we must check to see if the address is already in the
|
|
|
|
# subscriptions list.
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT * FROM subscriptions WHERE address=?", address)
|
2018-10-22 19:06:12 +02:00
|
|
|
if queryreturn:
|
2015-03-21 12:53:09 +01:00
|
|
|
raise APIError(16, 'You are already subscribed to that address.')
|
2018-04-08 17:28:08 +02:00
|
|
|
sqlExecute(
|
|
|
|
"INSERT INTO subscriptions VALUES (?,?,?)", label, address, True)
|
2015-03-21 12:53:09 +01:00
|
|
|
shared.reloadBroadcastSendersForWhichImWatching()
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderSubscriptions', ''))
|
2015-03-21 12:53:09 +01:00
|
|
|
return 'Added subscription.'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('deleteSubscription')
|
|
|
|
def HandleDeleteSubscription(self, address):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Unsubscribe from the address. The program does not check whether
|
|
|
|
you were subscribed in the first place.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2015-03-21 12:53:09 +01:00
|
|
|
address = addBMIfNotPresent(address)
|
2018-10-22 19:06:12 +02:00
|
|
|
sqlExecute("DELETE FROM subscriptions WHERE address=?", address)
|
2015-03-21 12:53:09 +01:00
|
|
|
shared.reloadBroadcastSendersForWhichImWatching()
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.UISignalQueue.put(('rerenderMessagelistFromLabels', ''))
|
|
|
|
queues.UISignalQueue.put(('rerenderSubscriptions', ''))
|
2015-03-21 12:53:09 +01:00
|
|
|
return 'Deleted subscription if it existed.'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('listSubscriptions')
|
|
|
|
def ListSubscriptions(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns dict with a list of all subscriptions
|
|
|
|
in the *subscriptions* key.
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT label, address, enabled FROM subscriptions")
|
2018-10-22 19:06:12 +02:00
|
|
|
data = []
|
|
|
|
for label, address, enabled in queryreturn:
|
2015-03-21 12:53:09 +01:00
|
|
|
label = shared.fixPotentiallyInvalidUTF8Data(label)
|
2018-10-22 19:06:12 +02:00
|
|
|
data.append({
|
2018-04-08 17:28:08 +02:00
|
|
|
'label': base64.b64encode(label),
|
|
|
|
'address': address,
|
|
|
|
'enabled': enabled == 1
|
|
|
|
})
|
2018-10-22 19:06:12 +02:00
|
|
|
return {'subscriptions': data}
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('disseminatePreEncryptedMsg')
|
|
|
|
def HandleDisseminatePreEncryptedMsg(
|
|
|
|
self, encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte,
|
|
|
|
requiredPayloadLengthExtraBytes):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""Handle a request to disseminate an encrypted message"""
|
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
# 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.
|
2015-03-21 12:53:09 +01:00
|
|
|
encryptedPayload = self._decode(encryptedPayload, "hex")
|
|
|
|
# Let us do the POW and attach it to the front
|
2021-08-09 17:22:50 +02:00
|
|
|
target = 2**64 / (
|
|
|
|
(
|
|
|
|
len(encryptedPayload)
|
|
|
|
+ requiredPayloadLengthExtraBytes
|
|
|
|
+ 8
|
|
|
|
) * requiredAverageProofOfWorkNonceTrialsPerByte)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info(
|
|
|
|
'(For msg message via API) Doing proof of work. Total required'
|
|
|
|
' difficulty: %s\nRequired small message difficulty: %s',
|
2021-08-09 17:22:50 +02:00
|
|
|
float(requiredAverageProofOfWorkNonceTrialsPerByte)
|
|
|
|
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
|
|
|
|
float(requiredPayloadLengthExtraBytes)
|
|
|
|
/ defaults.networkDefaultPayloadLengthExtraBytes,
|
2018-10-10 12:41:44 +02:00
|
|
|
)
|
2015-03-21 12:53:09 +01:00
|
|
|
powStartTime = time.time()
|
|
|
|
initialHash = hashlib.sha512(encryptedPayload).digest()
|
|
|
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info(
|
|
|
|
'(For msg message via API) Found proof of work %s\nNonce: %s\n'
|
|
|
|
'POW took %s seconds. %s nonce trials per second.',
|
|
|
|
trialValue, nonce, int(time.time() - powStartTime),
|
|
|
|
nonce / (time.time() - powStartTime)
|
|
|
|
)
|
2015-03-21 12:53:09 +01:00
|
|
|
encryptedPayload = pack('>Q', nonce) + encryptedPayload
|
|
|
|
toStreamNumber = decodeVarint(encryptedPayload[16:26])[0]
|
|
|
|
inventoryHash = calculateInventoryHash(encryptedPayload)
|
|
|
|
objectType = 2
|
|
|
|
TTL = 2.5 * 24 * 60 * 60
|
2017-01-10 21:17:25 +01:00
|
|
|
Inventory()[inventoryHash] = (
|
2018-04-08 17:28:08 +02:00
|
|
|
objectType, toStreamNumber, encryptedPayload,
|
|
|
|
int(time.time()) + TTL, ''
|
|
|
|
)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info(
|
|
|
|
'Broadcasting inv for msg(API disseminatePreEncryptedMsg'
|
|
|
|
' command): %s', hexlify(inventoryHash))
|
2017-08-09 17:36:52 +02:00
|
|
|
queues.invQueue.put((toStreamNumber, inventoryHash))
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('trashSentMessageByAckData')
|
|
|
|
def HandleTrashSentMessageByAckDAta(self, ackdata):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Trash a sent message by ackdata (hex encoded)"""
|
2015-03-21 12:53:09 +01:00
|
|
|
# This API method should only be used when msgid is not available
|
2018-10-22 19:06:12 +02:00
|
|
|
ackdata = self._decode(ackdata, "hex")
|
2018-04-08 17:28:08 +02:00
|
|
|
sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata)
|
2015-03-21 12:53:09 +01:00
|
|
|
return 'Trashed sent message (assuming message existed).'
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('disseminatePubkey')
|
|
|
|
def HandleDissimatePubKey(self, payload):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""Handle a request to disseminate a public key"""
|
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
# 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.
|
2015-03-21 12:53:09 +01:00
|
|
|
payload = self._decode(payload, "hex")
|
|
|
|
|
|
|
|
# Let us do the POW
|
2018-10-10 12:41:44 +02:00
|
|
|
target = 2 ** 64 / ((
|
|
|
|
len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8
|
|
|
|
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info('(For pubkey message via API) Doing proof of work...')
|
2015-03-21 12:53:09 +01:00
|
|
|
initialHash = hashlib.sha512(payload).digest()
|
|
|
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info(
|
|
|
|
'(For pubkey message via API) Found proof of work %s Nonce: %s',
|
|
|
|
trialValue, nonce
|
|
|
|
)
|
2015-03-21 12:53:09 +01:00
|
|
|
payload = pack('>Q', nonce) + payload
|
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
pubkeyReadPosition = 8 # bypass the nonce
|
2018-10-10 12:41:44 +02:00
|
|
|
if payload[pubkeyReadPosition:pubkeyReadPosition + 4] == \
|
2018-04-08 17:28:08 +02:00
|
|
|
'\x00\x00\x00\x00': # if this pubkey uses 8 byte time
|
2015-03-21 12:53:09 +01:00
|
|
|
pubkeyReadPosition += 8
|
|
|
|
else:
|
|
|
|
pubkeyReadPosition += 4
|
2018-10-22 19:06:12 +02:00
|
|
|
addressVersionLength = decodeVarint(
|
|
|
|
payload[pubkeyReadPosition:pubkeyReadPosition + 10])[1]
|
2015-03-21 12:53:09 +01:00
|
|
|
pubkeyReadPosition += addressVersionLength
|
2018-04-08 17:28:08 +02:00
|
|
|
pubkeyStreamNumber = decodeVarint(
|
2018-10-10 12:41:44 +02:00
|
|
|
payload[pubkeyReadPosition:pubkeyReadPosition + 10])[0]
|
2015-03-21 12:53:09 +01:00
|
|
|
inventoryHash = calculateInventoryHash(payload)
|
2018-10-10 12:41:44 +02:00
|
|
|
objectType = 1 # .. todo::: support v4 pubkeys
|
2015-03-21 12:53:09 +01:00
|
|
|
TTL = 28 * 24 * 60 * 60
|
2017-01-10 21:17:25 +01:00
|
|
|
Inventory()[inventoryHash] = (
|
2018-04-08 17:28:08 +02:00
|
|
|
objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, ''
|
|
|
|
)
|
2018-10-22 19:06:12 +02:00
|
|
|
logger.info(
|
|
|
|
'broadcasting inv within API command disseminatePubkey with'
|
|
|
|
' hash: %s', hexlify(inventoryHash))
|
2017-08-09 17:36:52 +02:00
|
|
|
queues.invQueue.put((pubkeyStreamNumber, inventoryHash))
|
2015-03-21 12:53:09 +01:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command(
|
|
|
|
'getMessageDataByDestinationHash', 'getMessageDataByDestinationTag')
|
|
|
|
def HandleGetMessageDataByDestinationHash(self, requestedHash):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""Handle a request to get message data by destination hash"""
|
|
|
|
|
2015-03-21 12:53:09 +01:00
|
|
|
# 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(requestedHash) != 32:
|
2018-04-08 17:28:08 +02:00
|
|
|
raise APIError(
|
|
|
|
19, 'The length of hash should be 32 bytes (encoded in hex'
|
|
|
|
' thus 64 characters).')
|
2015-03-21 12:53:09 +01:00
|
|
|
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(
|
2018-04-08 17:28:08 +02:00
|
|
|
"SELECT hash, payload FROM inventory WHERE tag = ''"
|
|
|
|
" and objecttype = 2")
|
2015-03-21 12:53:09 +01:00
|
|
|
with SqlBulkExecute() as sql:
|
2018-10-22 19:06:12 +02:00
|
|
|
for hash01, payload in queryreturn:
|
2018-04-08 17:28:08 +02:00
|
|
|
readPosition = 16 # Nonce length + time length
|
|
|
|
# Stream Number length
|
|
|
|
readPosition += decodeVarint(
|
2018-10-10 12:41:44 +02:00
|
|
|
payload[readPosition:readPosition + 10])[1]
|
|
|
|
t = (payload[readPosition:readPosition + 32], hash01)
|
2018-04-08 17:28:08 +02:00
|
|
|
sql.execute("UPDATE inventory SET tag=? WHERE hash=?", *t)
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-04-08 17:28:08 +02:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
"SELECT payload FROM inventory WHERE tag = ?", requestedHash)
|
2018-10-22 19:06:12 +02:00
|
|
|
return {"receivedMessageDatas": [
|
|
|
|
{'data': hexlify(payload)} for payload, in queryreturn
|
|
|
|
]}
|
|
|
|
|
|
|
|
@command('clientStatus')
|
|
|
|
def HandleClientStatus(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""
|
|
|
|
Returns the bitmessage status as dict with keys *networkConnections*,
|
|
|
|
*numberOfMessagesProcessed*, *numberOfBroadcastsProcessed*,
|
2020-11-15 23:37:22 +01:00
|
|
|
*numberOfPubkeysProcessed*, *pendingDownload*, *networkStatus*,
|
|
|
|
*softwareName*, *softwareVersion*. *networkStatus* will be one of
|
|
|
|
these strings: "notConnected",
|
2018-11-05 17:35:38 +01:00
|
|
|
"connectedButHaveNotReceivedIncomingConnections",
|
|
|
|
or "connectedAndReceivingIncomingConnections".
|
|
|
|
"""
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-11-01 15:53:53 +01:00
|
|
|
connections_num = len(network.stats.connectedHostsList())
|
|
|
|
if connections_num == 0:
|
2015-09-28 20:55:40 +02:00
|
|
|
networkStatus = 'notConnected'
|
2019-11-05 17:54:04 +01:00
|
|
|
elif state.clientHasReceivedIncomingConnections:
|
2015-09-28 20:55:40 +02:00
|
|
|
networkStatus = 'connectedAndReceivingIncomingConnections'
|
2018-11-01 15:53:53 +01:00
|
|
|
else:
|
|
|
|
networkStatus = 'connectedButHaveNotReceivedIncomingConnections'
|
2018-10-22 19:06:12 +02:00
|
|
|
return {
|
2018-11-01 15:53:53 +01:00
|
|
|
'networkConnections': connections_num,
|
2019-11-05 17:54:04 +01:00
|
|
|
'numberOfMessagesProcessed': state.numberOfMessagesProcessed,
|
|
|
|
'numberOfBroadcastsProcessed': state.numberOfBroadcastsProcessed,
|
|
|
|
'numberOfPubkeysProcessed': state.numberOfPubkeysProcessed,
|
2020-11-15 23:37:22 +01:00
|
|
|
'pendingDownload': network.stats.pendingDownload(),
|
2018-04-08 17:28:08 +02:00
|
|
|
'networkStatus': networkStatus,
|
|
|
|
'softwareName': 'PyBitmessage',
|
|
|
|
'softwareVersion': softwareVersion
|
2018-10-22 19:06:12 +02:00
|
|
|
}
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('helloWorld')
|
|
|
|
def HandleHelloWorld(self, a, b):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""Test two string params"""
|
2015-09-28 20:55:40 +02:00
|
|
|
return a + '-' + b
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('add')
|
|
|
|
def HandleAdd(self, a, b):
|
2018-10-10 12:41:44 +02:00
|
|
|
"""Test two numeric params"""
|
2015-09-28 20:55:40 +02:00
|
|
|
return a + b
|
|
|
|
|
2021-11-25 17:13:22 +01:00
|
|
|
@testmode('clearUISignalQueue')
|
2021-10-15 16:00:19 +02:00
|
|
|
def HandleclearUISignalQueue(self):
|
|
|
|
"""clear UISignalQueue"""
|
|
|
|
queues.UISignalQueue.queue.clear()
|
2021-11-18 16:54:05 +01:00
|
|
|
return "success"
|
2021-10-15 16:00:19 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('statusBar')
|
|
|
|
def HandleStatusBar(self, message):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Update GUI statusbar message"""
|
2017-02-08 13:41:56 +01:00
|
|
|
queues.UISignalQueue.put(('updateStatusBar', message))
|
2015-09-28 20:55:40 +02:00
|
|
|
|
2021-11-25 17:13:22 +01:00
|
|
|
@testmode('getStatusBar')
|
2021-10-15 16:00:19 +02:00
|
|
|
def HandleGetStatusBar(self):
|
|
|
|
"""Get GUI statusbar message"""
|
|
|
|
try:
|
|
|
|
_, data = queues.UISignalQueue.get(block=False)
|
|
|
|
except queue.Empty:
|
|
|
|
return None
|
|
|
|
return data
|
|
|
|
|
2021-11-30 15:16:18 +01:00
|
|
|
@testmode('undeleteMessage')
|
|
|
|
def HandleUndeleteMessage(self, msgid):
|
|
|
|
"""Undelete message"""
|
|
|
|
msgid = self._decode(msgid, "hex")
|
|
|
|
helper_inbox.undeleteMessage(msgid)
|
|
|
|
return "Undeleted message"
|
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('deleteAndVacuum')
|
|
|
|
def HandleDeleteAndVacuum(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Cleanup trashes and vacuum messages database"""
|
2018-10-22 19:06:12 +02:00
|
|
|
sqlStoredProcedure('deleteandvacuume')
|
|
|
|
return 'done'
|
2018-10-10 12:41:44 +02:00
|
|
|
|
2018-10-22 19:06:12 +02:00
|
|
|
@command('shutdown')
|
|
|
|
def HandleShutdown(self):
|
2018-11-05 17:35:38 +01:00
|
|
|
"""Shutdown the bitmessage. Returns 'done'."""
|
2018-10-22 19:06:12 +02:00
|
|
|
# backward compatible trick because False == 0 is True
|
|
|
|
state.shutdown = False
|
|
|
|
return 'done'
|
2015-09-28 20:55:40 +02:00
|
|
|
|
|
|
|
def _handle_request(self, method, params):
|
2018-10-22 19:06:12 +02:00
|
|
|
try:
|
|
|
|
# pylint: disable=attribute-defined-outside-init
|
|
|
|
self._method = method
|
2018-10-24 16:33:05 +02:00
|
|
|
func = self._handlers[method]
|
|
|
|
return func(self, *params)
|
2018-10-22 19:06:12 +02:00
|
|
|
except KeyError:
|
2014-01-13 01:56:30 +01:00
|
|
|
raise APIError(20, 'Invalid method: %s' % method)
|
2018-10-24 16:33:05 +02:00
|
|
|
except TypeError as e:
|
2018-10-25 11:52:16 +02:00
|
|
|
msg = 'Unexpected API Failure - %s' % e
|
2018-10-24 16:33:05 +02:00
|
|
|
if 'argument' not in str(e):
|
2019-11-12 16:32:39 +01:00
|
|
|
raise APIError(21, msg)
|
2018-10-24 16:33:05 +02:00
|
|
|
argcount = len(params)
|
|
|
|
maxcount = func.func_code.co_argcount
|
|
|
|
if argcount > maxcount:
|
|
|
|
msg = (
|
2018-11-05 17:35:38 +01:00
|
|
|
'Command %s takes at most %s parameters (%s given)'
|
|
|
|
% (method, maxcount, argcount))
|
2018-10-24 16:33:05 +02:00
|
|
|
else:
|
|
|
|
mincount = maxcount - len(func.func_defaults or [])
|
|
|
|
if argcount < mincount:
|
|
|
|
msg = (
|
2018-11-05 17:35:38 +01:00
|
|
|
'Command %s takes at least %s parameters (%s given)'
|
|
|
|
% (method, mincount, argcount))
|
2018-10-24 16:33:05 +02:00
|
|
|
raise APIError(0, msg)
|
2018-10-22 19:06:12 +02:00
|
|
|
finally:
|
|
|
|
state.last_api_response = time.time()
|
2014-01-13 01:56:30 +01:00
|
|
|
|
|
|
|
def _dispatch(self, method, params):
|
2018-10-25 11:52:16 +02:00
|
|
|
_fault = None
|
|
|
|
|
2014-01-13 01:56:30 +01:00
|
|
|
try:
|
|
|
|
return self._handle_request(method, params)
|
|
|
|
except APIError as e:
|
2018-10-25 11:52:16 +02:00
|
|
|
_fault = e
|
2014-08-27 09:14:32 +02:00
|
|
|
except varintDecodeError as e:
|
|
|
|
logger.error(e)
|
2018-10-25 11:52:16 +02:00
|
|
|
_fault = APIError(
|
2018-11-05 17:35:38 +01:00
|
|
|
26, 'Data contains a malformed varint. Some details: %s' % e)
|
2014-01-13 01:56:30 +01:00
|
|
|
except Exception as e:
|
|
|
|
logger.exception(e)
|
2018-10-25 11:52:16 +02:00
|
|
|
_fault = APIError(21, 'Unexpected API Failure - %s' % e)
|
2018-04-08 17:28:08 +02:00
|
|
|
|
2018-10-25 11:52:16 +02:00
|
|
|
if _fault:
|
|
|
|
if self.config.safeGet(
|
|
|
|
'bitmessagesettings', 'apivariant') == 'legacy':
|
|
|
|
return str(_fault)
|
|
|
|
else:
|
|
|
|
raise _fault # pylint: disable=raising-bad-type
|
2018-10-25 16:52:19 +02:00
|
|
|
|
|
|
|
def _listMethods(self):
|
|
|
|
"""List all API commands"""
|
|
|
|
return self._handlers.keys()
|
|
|
|
|
|
|
|
def _methodHelp(self, method):
|
|
|
|
return self._handlers[method].__doc__
|