Files
pallectrum/electrum/daemon.py

379 lines
14 KiB
Python
Raw Normal View History

2015-11-30 10:09:54 +01:00
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
2016-02-23 11:36:42 +01:00
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
2015-11-30 10:09:54 +01:00
#
2016-02-23 11:36:42 +01:00
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
2015-11-30 10:09:54 +01:00
#
2016-02-23 11:36:42 +01:00
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import ast
import os
import time
2018-02-15 17:30:40 +01:00
import traceback
import sys
import threading
2018-10-22 16:41:25 +02:00
from typing import Dict, Optional, Tuple
2015-12-08 10:55:34 +01:00
import jsonrpclib
2015-11-30 10:09:54 +01:00
2018-10-12 14:53:22 +02:00
from .jsonrpc import SimpleJSONRPCServer, PasswordProtectedJSONRPCServer
2017-01-22 21:25:24 +03:00
from .version import ELECTRUM_VERSION
from .network import Network
2019-04-26 18:52:26 +02:00
from .util import (json_decode, DaemonThread, to_string,
2019-02-08 12:59:06 +01:00
create_and_start_event_loop, profiler, standardize_path)
2018-09-28 17:58:46 +02:00
from .wallet import Wallet, Abstract_Wallet
2017-01-22 21:25:24 +03:00
from .storage import WalletStorage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
from .plugin import run_hook
2019-04-26 18:52:26 +02:00
from .logging import get_logger
_logger = get_logger(__name__)
2015-11-30 10:09:54 +01:00
2017-01-30 12:36:56 +03:00
2018-10-22 16:41:25 +02:00
def get_lockfile(config: SimpleConfig):
return os.path.join(config.path, 'daemon')
2017-01-30 12:36:56 +03:00
def remove_lockfile(lockfile):
os.unlink(lockfile)
2017-01-30 12:36:56 +03:00
2018-10-22 16:41:25 +02:00
def get_fd_or_server(config: SimpleConfig):
'''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succeeds, the server is returned. Otherwise remove the
lockfile and try again.'''
lockfile = get_lockfile(config)
while True:
try:
2018-01-04 23:41:10 +01:00
return os.open(lockfile, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644), None
except OSError:
pass
server = get_server(config)
if server is not None:
return None, server
# Couldn't connect; remove lockfile and try again.
remove_lockfile(lockfile)
2017-01-30 12:36:56 +03:00
2018-10-22 16:41:25 +02:00
def get_server(config: SimpleConfig) -> Optional[jsonrpclib.Server]:
lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
rpc_user, rpc_password = get_rpc_credentials(config)
if rpc_password == '':
# authentication disabled
server_url = 'http://%s:%d' % (host, port)
else:
server_url = 'http://%s:%s@%s:%d' % (
rpc_user, rpc_password, host, port)
server = jsonrpclib.Server(server_url)
# Test daemon is running
server.ping()
return server
2017-01-30 12:36:56 +03:00
except Exception as e:
2019-04-26 18:52:26 +02:00
_logger.info(f"failed to connect to JSON-RPC server: {e}")
if not create_time or create_time < time.time() - 1.0:
return None
# Sleep a bit and try again; it might have just been started
time.sleep(1.0)
2018-10-22 16:41:25 +02:00
def get_rpc_credentials(config: SimpleConfig) -> Tuple[str, str]:
rpc_user = config.get('rpcuser', None)
rpc_password = config.get('rpcpassword', None)
if rpc_user is None or rpc_password is None:
rpc_user = 'user'
import ecdsa, base64
bits = 128
nbytes = bits // 8 + (bits % 8 > 0)
pw_int = ecdsa.util.randrange(pow(2, bits))
pw_b64 = base64.b64encode(
pw_int.to_bytes(nbytes, 'big'), b'-_')
rpc_password = to_string(pw_b64, 'ascii')
config.set_key('rpcuser', rpc_user)
config.set_key('rpcpassword', rpc_password, save=True)
elif rpc_password == '':
2019-04-26 18:52:26 +02:00
_logger.warning('RPC authentication is disabled.')
return rpc_user, rpc_password
class WatchTower(DaemonThread):
def __init__(self, config, lnwatcher):
DaemonThread.__init__(self)
self.config = config
self.lnwatcher = lnwatcher
self.start()
def run(self):
host = self.config.get('watchtower_host')
port = self.config.get('watchtower_port', 12345)
server = SimpleJSONRPCServer((host, port), logRequests=True)
server.register_function(self.lnwatcher.add_sweep_tx, 'add_sweep_tx')
2019-03-12 18:33:36 +01:00
server.register_function(self.lnwatcher.add_channel, 'add_channel')
server.register_function(self.lnwatcher.get_num_tx, 'get_num_tx')
server.timeout = 0.1
while self.is_running():
server.handle_request()
2015-12-05 21:38:20 +09:00
class Daemon(DaemonThread):
2015-11-30 10:09:54 +01:00
@profiler
2018-10-22 16:41:25 +02:00
def __init__(self, config: SimpleConfig, fd=None, *, listen_jsonrpc=True):
2015-12-05 21:38:20 +09:00
DaemonThread.__init__(self)
2015-11-30 10:09:54 +01:00
self.config = config
if fd is None and listen_jsonrpc:
fd, server = get_fd_or_server(config)
if fd is None: raise Exception('failed to lock daemon; already running?')
2018-11-02 20:14:59 +01:00
self.asyncio_loop, self._stop_loop, self._loop_thread = create_and_start_event_loop()
if config.get('offline'):
self.network = None
else:
self.network = Network(config)
2018-11-01 16:30:03 +01:00
self.network._loop_thread = self._loop_thread
self.fx = FxThread(config, self.network)
self.gui = None
# path -> wallet; make sure path is standardized.
2018-09-28 17:58:46 +02:00
self.wallets = {} # type: Dict[str, Abstract_Wallet]
2018-01-07 23:53:25 +01:00
# Setup JSONRPC server
self.server = None
if listen_jsonrpc:
self.init_server(config, fd)
# server-side watchtower
self.watchtower = WatchTower(self.config, self.network.lnwatcher) if self.config.get('watchtower_host') else None
if self.network:
self.network.start([
self.fx.run,
])
self.start()
2016-08-15 08:14:19 +02:00
2018-10-22 16:41:25 +02:00
def init_server(self, config: SimpleConfig, fd):
2016-08-15 08:27:09 +02:00
host = config.get('rpchost', '127.0.0.1')
port = config.get('rpcport', 0)
rpc_user, rpc_password = get_rpc_credentials(config)
try:
2018-10-12 14:53:22 +02:00
server = PasswordProtectedJSONRPCServer(
(host, port), logRequests=False,
rpc_user=rpc_user, rpc_password=rpc_password)
except Exception as e:
2019-04-26 18:52:26 +02:00
self.logger.error(f'cannot initialize RPC server on host {host}: {repr(e)}')
self.server = None
os.close(fd)
return
os.write(fd, bytes(repr((server.socket.getsockname(), time.time())), 'utf8'))
os.close(fd)
2018-01-07 23:53:25 +01:00
self.server = server
server.timeout = 0.1
server.register_function(self.ping, 'ping')
server.register_function(self.run_gui, 'gui')
server.register_function(self.run_daemon, 'daemon')
self.cmd_runner = Commands(self.config, None, self.network)
for cmdname in known_commands:
server.register_function(getattr(self.cmd_runner, cmdname), cmdname)
server.register_function(self.run_cmdline, 'run_cmdline')
2015-11-30 10:09:54 +01:00
def ping(self):
return True
def run_daemon(self, config_options):
2018-11-01 16:30:03 +01:00
asyncio.set_event_loop(self.asyncio_loop)
config = SimpleConfig(config_options)
2015-11-30 10:09:54 +01:00
sub = config.get('subcommand')
2017-03-05 20:25:42 +01:00
assert sub in [None, 'start', 'stop', 'status', 'load_wallet', 'close_wallet']
if sub in [None, 'start']:
2015-11-30 10:09:54 +01:00
response = "Daemon already running"
2017-03-05 20:25:42 +01:00
elif sub == 'load_wallet':
path = config.get_wallet_path()
2017-03-11 10:26:26 +01:00
wallet = self.load_wallet(path, config.get('password'))
2018-03-25 23:38:55 +02:00
if wallet is not None:
self.cmd_runner.wallet = wallet
run_hook('load_wallet', wallet, None)
response = wallet is not None
2017-03-05 14:57:41 +01:00
elif sub == 'close_wallet':
path = config.get_wallet_path()
path = standardize_path(path)
if path in self.wallets:
2017-03-05 14:57:41 +01:00
self.stop_wallet(path)
response = True
else:
response = False
2015-11-30 10:09:54 +01:00
elif sub == 'status':
if self.network:
2018-11-04 19:25:23 +01:00
net_params = self.network.get_parameters()
current_wallet = self.cmd_runner.wallet
current_wallet_path = current_wallet.storage.path \
if current_wallet else None
response = {
'path': self.network.config.path,
2018-11-04 19:25:23 +01:00
'server': net_params.host,
'blockchain_height': self.network.get_local_height(),
'server_height': self.network.get_server_height(),
'spv_nodes': len(self.network.get_interfaces()),
'connected': self.network.is_connected(),
2018-11-04 19:25:23 +01:00
'auto_connect': net_params.auto_connect,
'version': ELECTRUM_VERSION,
'wallets': {k: w.is_up_to_date()
for k, w in self.wallets.items()},
'current_wallet': current_wallet_path,
2017-03-05 16:12:47 +01:00
'fee_per_kb': self.config.fee_per_kb(),
}
else:
response = "Daemon offline"
2015-11-30 10:09:54 +01:00
elif sub == 'stop':
self.stop()
response = "Daemon stopped"
return response
def run_gui(self, config_options):
2015-11-30 10:09:54 +01:00
config = SimpleConfig(config_options)
if self.gui:
if hasattr(self.gui, 'new_window'):
config.open_last_wallet()
path = config.get_wallet_path()
self.gui.new_window(path, config.get('url'))
response = "ok"
else:
response = "error: current GUI does not support multiple windows"
2015-11-30 10:09:54 +01:00
else:
response = "Error: Electrum is running in daemon mode. Please stop the daemon first."
return response
2018-10-22 16:41:25 +02:00
def load_wallet(self, path, password) -> Optional[Abstract_Wallet]:
2019-02-08 12:59:06 +01:00
path = standardize_path(path)
# wizard will be launched if we return
2015-11-30 10:09:54 +01:00
if path in self.wallets:
wallet = self.wallets[path]
2016-06-20 16:25:11 +02:00
return wallet
storage = WalletStorage(path, manual_upgrades=True)
2017-03-06 08:33:35 +01:00
if not storage.file_exists():
2016-06-20 16:25:11 +02:00
return
if storage.is_encrypted():
if not password:
2017-03-08 11:56:01 +01:00
return
2017-03-06 08:33:35 +01:00
storage.decrypt(password)
if storage.requires_split():
2016-06-20 16:25:11 +02:00
return
if storage.requires_upgrade():
return
if storage.get_action():
return
wallet = Wallet(storage)
wallet.start_network(self.network)
2016-06-20 16:25:11 +02:00
self.wallets[path] = wallet
2015-11-30 10:09:54 +01:00
return wallet
2018-10-22 16:41:25 +02:00
def add_wallet(self, wallet: Abstract_Wallet):
2016-06-20 16:25:11 +02:00
path = wallet.storage.path
path = standardize_path(path)
2016-06-20 16:25:11 +02:00
self.wallets[path] = wallet
def get_wallet(self, path):
path = standardize_path(path)
return self.wallets.get(path)
2019-02-08 11:17:48 +01:00
def delete_wallet(self, path):
self.stop_wallet(path)
if os.path.exists(path):
os.unlink(path)
return True
return False
2016-06-20 16:25:11 +02:00
def stop_wallet(self, path):
path = standardize_path(path)
wallet = self.wallets.pop(path, None)
if not wallet: return
2016-06-20 16:25:11 +02:00
wallet.stop_threads()
2015-11-30 10:09:54 +01:00
def run_cmdline(self, config_options):
2018-11-01 16:30:03 +01:00
asyncio.set_event_loop(self.asyncio_loop)
password = config_options.get('password')
new_password = config_options.get('new_password')
2015-11-30 10:09:54 +01:00
config = SimpleConfig(config_options)
# FIXME this is ugly...
config.fee_estimates = self.network.config.fee_estimates.copy()
config.mempool_fees = self.network.config.mempool_fees.copy()
2015-11-30 10:09:54 +01:00
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
if cmd.requires_wallet:
path = config.get_wallet_path()
path = standardize_path(path)
wallet = self.wallets.get(path)
if wallet is None:
2017-10-05 10:34:20 +02:00
return {'error': 'Wallet "%s" is not loaded. Use "electrum daemon load_wallet"'%os.path.basename(path) }
else:
wallet = None
2015-11-30 10:09:54 +01:00
# arguments passed to function
args = map(lambda x: config.get(x), cmd.params)
# decode json arguments
2017-02-05 13:38:44 +03:00
args = [json_decode(i) for i in args]
2015-11-30 10:09:54 +01:00
# options
kwargs = {}
for x in cmd.options:
kwargs[x] = (config_options.get(x) if x in ['password', 'new_password'] else config.get(x))
2017-07-02 11:44:48 +02:00
cmd_runner = Commands(config, wallet, self.network)
2015-11-30 10:09:54 +01:00
func = getattr(cmd_runner, cmd.name)
try:
result = func(*args, **kwargs)
except TypeError as e:
raise Exception("Wrapping TypeError to prevent JSONRPC-Pelix from hiding traceback") from e
2015-11-30 10:09:54 +01:00
return result
def run(self):
while self.is_running():
2016-08-15 08:14:19 +02:00
self.server.handle_request() if self.server else time.sleep(0.1)
2018-11-01 16:30:03 +01:00
# stop network/wallets
2015-11-30 10:09:54 +01:00
for k, wallet in self.wallets.items():
wallet.stop_threads()
if self.network:
2019-04-26 18:52:26 +02:00
self.logger.info("shutting down network")
self.network.stop()
2018-11-01 16:30:03 +01:00
# stop event loop
self.asyncio_loop.call_soon_threadsafe(self._stop_loop.set_result, 1)
self._loop_thread.join(timeout=1)
2016-06-04 12:58:29 +02:00
self.on_stop()
def stop(self):
if self.gui:
self.gui.stop()
2019-04-26 18:52:26 +02:00
self.logger.info("stopping, removing lockfile")
remove_lockfile(get_lockfile(self.config))
2015-12-05 21:38:20 +09:00
DaemonThread.stop(self)
def init_gui(self, config, plugins):
threading.current_thread().setName('GUI')
gui_name = config.get('gui', 'qt')
if gui_name in ['lite', 'classic']:
gui_name = 'qt'
gui = __import__('electrum.gui.' + gui_name, fromlist=['electrum'])
self.gui = gui.ElectrumGui(config, self, plugins)
2018-02-15 17:30:40 +01:00
try:
self.gui.main()
except BaseException as e:
2019-04-26 18:52:26 +02:00
self.logger.exception('')
2018-02-15 17:30:40 +01:00
# app will exit now