Files
purple-electrumwallet/run_electrum
T

536 lines
21 KiB
Python
Raw Normal View History

2017-02-05 14:31:17 +03:00
#!/usr/bin/env python3
2015-02-21 12:24:40 +01:00
# -*- mode: python -*-
2011-11-04 18:00:37 +01:00
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
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:
2011-11-04 18:00:37 +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.
2011-11-04 18:00:37 +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.
2013-11-12 19:19:32 -08:00
import os
import sys
2019-02-15 22:06:10 +01:00
2022-02-08 12:43:04 +01:00
MIN_PYTHON_VERSION = "3.8.0" # FIXME duplicated from setup.py
2019-02-15 22:06:10 +01:00
_min_python_version_tuple = tuple(map(int, (MIN_PYTHON_VERSION.split("."))))
if sys.version_info[:3] < _min_python_version_tuple:
sys.exit("Error: Electrum requires Python version >= %s..." % MIN_PYTHON_VERSION)
import warnings
import asyncio
from typing import TYPE_CHECKING, Optional
2015-02-24 18:41:29 +01:00
script_dir = os.path.dirname(os.path.realpath(__file__))
is_pyinstaller = getattr(sys, 'frozen', False)
2013-03-12 13:48:16 +01:00
is_android = 'ANDROID_DATA' in os.environ
is_appimage = 'APPIMAGE' in os.environ
is_binary_distributable = is_pyinstaller or is_android or is_appimage
# is_local: unpacked tar.gz but not pip installed, or git clone
is_local = (not is_binary_distributable
and os.path.exists(os.path.join(script_dir, "electrum.desktop")))
is_git_clone = is_local and os.path.exists(os.path.join(script_dir, ".git"))
2013-03-12 13:48:16 +01:00
if is_git_clone:
# developers should probably see all deprecation warnings.
warnings.simplefilter('default', DeprecationWarning)
2015-02-24 18:41:29 +01:00
if is_local or is_android:
sys.path.insert(0, os.path.join(script_dir, 'packages'))
2015-01-27 13:50:02 +01:00
if is_pyinstaller:
# Keep an open file handle for the binary that started us. On Windows, this
# prevents users from moving or renaming the exe file while running (doing which
# causes ImportErrors and other runtime failures). (see #4072)
_file = open(sys.executable, 'rb')
2016-01-28 14:38:10 +01:00
def check_imports():
2016-01-27 20:21:20 +05:30
# pure-python dependencies need to be imported here for pyinstaller
try:
import dns
2018-12-13 23:11:59 +01:00
import certifi
2016-01-27 20:21:20 +05:30
import qrcode
import google.protobuf
2018-07-27 12:29:04 +02:00
import aiorpcx
2016-01-27 20:21:20 +05:30
except ImportError as e:
2018-12-13 23:25:52 +01:00
sys.exit(f"Error: {str(e)}. Try 'sudo python3 -m pip install <module-name>'")
2022-02-08 12:34:49 +01:00
if not ((0, 22, 0) <= aiorpcx._version < (0, 23)):
raise RuntimeError(f'aiorpcX version {aiorpcx._version} does not match required: 0.22.0<=ver<0.23')
2016-01-27 20:21:20 +05:30
# the following imports are for pyinstaller
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
2016-01-28 14:38:10 +01:00
# make sure that certificates are here
2018-12-13 23:11:59 +01:00
assert os.path.exists(certifi.where())
2016-01-28 14:38:10 +01:00
2016-01-28 14:38:10 +01:00
if not is_android:
check_imports()
2017-03-28 15:49:50 +02:00
sys._ELECTRUM_RUNNING_VIA_RUNELECTRUM = True # used by logging.py
from electrum.logging import get_logger, configure_logging # import logging submodule first
from electrum import util
2023-03-19 13:32:43 +01:00
from electrum.payment_identifier import PaymentIdentifier
2018-03-04 22:10:59 +01:00
from electrum import constants
from electrum import SimpleConfig
2020-02-05 15:13:37 +01:00
from electrum.wallet_db import WalletDB
from electrum.wallet import Wallet
from electrum.storage import WalletStorage
2018-03-14 12:42:42 +01:00
from electrum.util import print_msg, print_stderr, json_encode, json_decode, UserCancelled
2021-11-23 14:42:43 +01:00
from electrum.util import InvalidPassword
2015-06-07 17:45:13 +02:00
from electrum.commands import get_parser, known_commands, Commands, config_variables
from electrum import daemon
from electrum import keystore
2019-08-15 13:17:16 +02:00
from electrum.util import create_and_start_event_loop
from electrum.i18n import set_language
2019-04-26 18:52:26 +02:00
if TYPE_CHECKING:
import threading
from electrum.plugin import Plugins
2019-04-26 18:52:26 +02:00
_logger = get_logger(__name__)
# get password routine
def prompt_password(prompt, confirm=True):
import getpass
password = getpass.getpass(prompt, stream=None)
if password and confirm:
password2 = getpass.getpass("Confirm: ")
if password != password2:
sys.exit("Error: Passwords do not match.")
if not password:
password = None
return password
2013-11-12 19:19:32 -08:00
def init_cmdline(config_options, wallet_path, server, *, config: 'SimpleConfig'):
2015-05-28 15:22:30 +02:00
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
2011-11-04 18:00:37 +01:00
if cmdname in ['payto', 'paytomany'] and config.get('unsigned'):
2015-05-31 17:38:57 +02:00
cmd.requires_password = False
if cmdname in ['payto', 'paytomany'] and config.get('broadcast'):
cmd.requires_network = True
2018-02-10 19:18:48 +01:00
# instantiate wallet for command-line
2019-09-10 17:14:25 +02:00
storage = WalletStorage(wallet_path)
2017-03-06 08:33:35 +01:00
if cmd.requires_wallet and not storage.file_exists():
2015-10-28 11:13:45 +01:00
print_msg("Error: Wallet file not found.")
print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
sys_exit(1)
2015-10-28 11:13:45 +01:00
2012-10-02 13:15:10 +02:00
# important warning
2015-08-16 16:30:55 +02:00
if cmd.name in ['getprivatekeys']:
2014-04-30 15:27:50 +02:00
print_stderr("WARNING: ALL your private keys are secret.")
print_stderr("Exposing a single private key can compromise your entire wallet!")
print_stderr("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
2012-10-02 13:15:10 +02:00
2020-02-05 15:13:37 +01:00
# will we need a password
if not storage.is_encrypted():
db = WalletDB(storage.read(), manual_upgrades=False)
use_encryption = db.get('use_encryption')
else:
use_encryption = True
2011-11-14 20:35:54 +01:00
# commands needing password
2021-03-21 00:34:25 -04:00
if ((cmd.requires_wallet and storage.is_encrypted() and server is False)\
2019-08-19 12:46:31 +02:00
or (cmdname == 'load_wallet' and storage.is_encrypted())\
2020-02-05 15:13:37 +01:00
or (cmd.requires_password and use_encryption)):
if storage.is_encrypted_with_hw_device():
2018-02-10 19:18:48 +01:00
# this case is handled later in the control flow
password = None
elif config.get('password'):
password = config.get('password')
else:
password = prompt_password('Password:', False)
if not password:
print_msg("Error: Password required")
sys_exit(1)
2013-02-26 13:56:48 +01:00
else:
password = None
config_options['password'] = config_options.get('password') or password
2012-05-13 01:32:28 +02:00
2021-09-10 18:19:06 -05:00
if cmd.name == 'password' and 'new_password' not in config_options:
new_password = prompt_password('New password:')
config_options['new_password'] = new_password
2015-08-26 17:44:19 +02:00
def get_connected_hw_devices(plugins: 'Plugins'):
supported_plugins = plugins.get_hardware_support()
2018-02-10 19:18:48 +01:00
# scan devices
devices = []
devmgr = plugins.device_manager
for splugin in supported_plugins:
name, plugin = splugin.name, splugin.plugin
if not plugin:
e = splugin.exception
2019-04-26 18:52:26 +02:00
_logger.error(f"{name}: error during plugin init: {repr(e)}")
continue
2018-02-10 19:18:48 +01:00
try:
u = devmgr.list_pairable_device_infos(handler=None, plugin=plugin)
2019-04-26 18:52:26 +02:00
except Exception as e:
_logger.error(f'error getting device infos for {name}: {repr(e)}')
2018-02-10 19:18:48 +01:00
continue
devices += list(map(lambda x: (name, x), u))
return devices
def get_password_for_hw_device_encrypted_storage(plugins: 'Plugins') -> str:
2018-02-10 19:18:48 +01:00
devices = get_connected_hw_devices(plugins)
if len(devices) == 0:
2018-04-15 20:45:30 +03:00
print_msg("Error: No connected hw device found. Cannot decrypt this wallet.")
2018-02-10 19:18:48 +01:00
sys.exit(1)
elif len(devices) > 1:
print_msg("Warning: multiple hardware devices detected. "
"The first one will be used to decrypt the wallet.")
# FIXME we use the "first" device, in case of multiple ones
name, device_info = devices[0]
devmgr = plugins.device_manager
2018-03-14 12:42:42 +01:00
try:
client = devmgr.client_by_id(device_info.device.id_)
return client.get_password_for_storage_encryption()
2018-03-14 12:42:42 +01:00
except UserCancelled:
sys.exit(0)
2018-02-10 19:18:48 +01:00
async def run_offline_command(config, config_options, plugins: 'Plugins'):
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
2017-02-09 17:08:27 +01:00
password = config_options.get('password')
if 'wallet_path' in cmd.options and config_options.get('wallet_path') is None:
config_options['wallet_path'] = config.get_wallet_path()
2017-03-03 16:05:13 +01:00
if cmd.requires_wallet:
storage = WalletStorage(config.get_wallet_path())
2017-03-06 08:33:35 +01:00
if storage.is_encrypted():
if storage.is_encrypted_with_hw_device():
2018-02-10 19:18:48 +01:00
password = get_password_for_hw_device_encrypted_storage(plugins)
config_options['password'] = password
2017-03-06 08:33:35 +01:00
storage.decrypt(password)
2020-02-05 15:13:37 +01:00
db = WalletDB(storage.read(), manual_upgrades=False)
wallet = Wallet(db, storage, config=config)
config_options['wallet'] = wallet
2017-03-03 16:05:13 +01:00
else:
wallet = None
# check password
if cmd.requires_password and wallet.has_password():
try:
wallet.check_password(password)
except InvalidPassword:
print_msg("Error: This password does not decode this wallet.")
sys.exit(1)
if cmd.requires_network:
2017-02-09 17:08:27 +01:00
print_msg("Warning: running command offline")
2015-08-26 17:44:19 +02:00
# arguments passed to function
2017-01-22 21:25:24 +03:00
args = [config.get(x) for x in cmd.params]
2015-08-30 17:46:51 +02:00
# decode json arguments
if cmdname not in ('setconfig',):
args = list(map(json_decode, args))
2015-08-26 17:44:19 +02:00
# options
2017-10-09 11:54:17 +02:00
kwargs = {}
for x in cmd.options:
kwargs[x] = (config_options.get(x) if x in ['wallet_path', 'wallet', 'password', 'new_password'] else config.get(x))
2019-09-05 18:30:04 +02:00
cmd_runner = Commands(config=config)
2015-08-26 17:44:19 +02:00
func = getattr(cmd_runner, cmd.name)
2019-08-15 13:17:16 +02:00
result = await func(*args, **kwargs)
# save wallet
2015-12-23 15:23:33 +01:00
if wallet:
2020-02-05 15:13:37 +01:00
wallet.save_db()
2015-08-26 17:44:19 +02:00
return result
2016-02-01 22:09:55 +01:00
def init_plugins(config, gui_name):
2018-07-11 17:38:47 +02:00
from electrum.plugin import Plugins
2018-10-22 18:21:38 +02:00
return Plugins(config, gui_name)
2015-08-26 17:44:19 +02:00
loop = None # type: Optional[asyncio.AbstractEventLoop]
stop_loop = None # type: Optional[asyncio.Future]
loop_thread = None # type: Optional[threading.Thread]
2019-08-15 13:17:16 +02:00
def sys_exit(i):
# stop event loop and exit
if loop:
loop.call_soon_threadsafe(stop_loop.set_result, 1)
loop_thread.join(timeout=1)
2019-08-15 13:17:16 +02:00
sys.exit(i)
2015-05-28 15:22:30 +02:00
def main():
global loop, stop_loop, loop_thread
2017-03-28 15:49:50 +02:00
# The hook will only be used in the Qt GUI right now
util.setup_thread_excepthook()
2018-04-15 20:45:30 +03:00
# on macOS, delete Process Serial Number arg generated for apps launched in Finder
2017-01-22 21:25:24 +03:00
sys.argv = list(filter(lambda x: not x.startswith('-psn'), sys.argv))
2015-05-28 15:22:30 +02:00
# old 'help' syntax
2017-01-22 21:25:24 +03:00
if len(sys.argv) > 1 and sys.argv[1] == 'help':
2015-05-28 15:22:30 +02:00
sys.argv.remove('help')
sys.argv.append('-h')
2018-08-30 18:34:04 +02:00
# old '-v' syntax
# Due to this workaround that keeps old -v working,
# more advanced usages of -v need to use '-v='.
# e.g. -v=debug,network=warning,interface=error
2018-08-30 18:34:04 +02:00
try:
i = sys.argv.index('-v')
except ValueError:
pass
else:
sys.argv[i] = '-v*'
2015-08-17 09:46:50 +02:00
# read arguments from stdin pipe and prompt
for i, arg in enumerate(sys.argv):
if arg == '-':
if not sys.stdin.isatty():
2015-08-30 17:46:51 +02:00
sys.argv[i] = sys.stdin.read()
2015-08-17 09:46:50 +02:00
break
else:
2018-04-07 17:10:30 +02:00
raise Exception('Cannot get argument from stdin')
2015-08-17 09:46:50 +02:00
elif arg == '?':
2017-01-22 21:25:24 +03:00
sys.argv[i] = input("Enter argument:")
elif arg == ':':
sys.argv[i] = prompt_password('Enter argument (will not echo):', False)
2015-08-17 09:46:50 +02:00
2015-08-26 17:44:19 +02:00
# parse command line
parser = get_parser()
2015-05-28 15:22:30 +02:00
args = parser.parse_args()
# config is an object passed to the various constructors (wallet, interface, gui)
if is_android:
import importlib.util
android_gui = 'kivy' if importlib.util.find_spec('kivy') else 'qml'
2015-05-28 15:22:30 +02:00
config_options = {
'verbosity': '*' if util.is_android_debug_apk() else '',
2015-09-07 16:44:17 +02:00
'cmd': 'gui',
2023-05-24 17:41:44 +00:00
SimpleConfig.GUI_NAME.key(): android_gui,
SimpleConfig.WALLET_USE_SINGLE_PASSWORD.key(): True,
2015-05-28 15:22:30 +02:00
}
if util.get_android_package_name() == "org.electrum.testnet.electrum":
# ~hack for easier testnet builds. pkgname subject to change.
config_options['testnet'] = True
2015-05-28 15:22:30 +02:00
else:
config_options = args.__dict__
2017-01-22 21:25:24 +03:00
f = lambda key: config_options[key] is not None and key not in config_variables.get(args.cmd, {}).keys()
config_options = {key: config_options[key] for key in filter(f, config_options.keys())}
2023-06-05 15:29:35 +00:00
if config_options.get(SimpleConfig.NETWORK_SERVER.key()):
config_options[SimpleConfig.NETWORK_AUTO_CONNECT.key()] = False
2015-05-28 15:22:30 +02:00
config_options['cwd'] = cwd = os.getcwd()
2016-02-24 16:57:58 +01:00
# fixme: this can probably be achieved with a runtime hook (pyinstaller)
if is_pyinstaller and os.path.exists(os.path.join(sys._MEIPASS, 'is_portable')):
2017-11-28 18:26:58 +01:00
config_options['portable'] = True
2015-07-06 18:15:22 -06:00
if config_options.get('portable'):
2022-03-23 20:06:42 +01:00
if is_local:
# running from git clone or local source: put datadir next to main script
datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data')
2022-03-23 20:06:42 +01:00
else:
# Running a binary or installed source. The most generic but still reasonable thing
# is to use the current working directory. (see #7732)
# note: The main script is often unpacked to a temporary directory from a bundled executable,
# and we don't want to put the datadir inside a temp dir.
# note: Re the portable .exe on Windows, when the user double-clicks it, CWD gets set
# to the parent dir, i.e. we will put the datadir next to the exe.
datadir = os.path.join(os.path.realpath(cwd), 'electrum_data')
config_options['electrum_path'] = datadir
2015-05-30 06:56:45 +02:00
if not config_options.get('verbosity'):
2019-03-27 18:09:26 +01:00
warnings.simplefilter('ignore', DeprecationWarning)
2015-05-28 15:22:30 +02:00
config = SimpleConfig(config_options)
cmdname = config.get('cmd')
# set language as early as possible
# Note: we are already too late for strings that are declared in the global scope
# of an already imported module. However, the GUI and the plugins at least have
# not been imported yet. (see #4621)
# Note: it is ok to call set_language() again later, but note that any call only applies
# to not-yet-evaluated strings.
if cmdname == 'gui':
2023-05-24 17:41:44 +00:00
gui_name = config.GUI_NAME
lang = config.LOCALIZATION_LANGUAGE
if not lang:
try:
from electrum.gui.default_lang import get_default_language
lang = get_default_language(gui_name=gui_name)
_logger.info(f"get_default_language: detected default as {lang=!r}")
except ImportError as e:
_logger.info(f"get_default_language: failed. got exc={e!r}")
set_language(lang)
2017-01-07 16:58:23 +01:00
if config.get('testnet'):
2018-03-04 22:10:59 +01:00
constants.set_testnet()
2018-04-11 20:10:14 +03:00
elif config.get('regtest'):
constants.set_regtest()
2018-06-22 17:07:07 +02:00
elif config.get('simnet'):
constants.set_simnet()
2021-05-02 05:54:58 +09:00
elif config.get('signet'):
constants.set_signet()
# check if we received a valid payment identifier
uri = config_options.get('url')
if uri and not PaymentIdentifier(None, uri).is_valid():
print_stderr('unknown command:', uri)
sys.exit(1)
2019-09-02 19:04:08 +02:00
if cmdname == 'daemon' and config.get("detach"):
# detect lockfile.
# This is not as good as get_file_descriptor, but that would require the asyncio loop
lockfile = daemon.get_lockfile(config)
if os.path.exists(lockfile):
print_stderr("Daemon already running (lockfile detected).")
print_stderr("Run 'electrum stop' to stop the daemon.")
sys.exit(1)
# Initialise rpc credentials to random if not set yet. This would normally be done
# later anyway, but we need to avoid the two sides of the fork setting conflicting random creds.
daemon.get_rpc_credentials(config) # inits creds as side-effect
2019-08-30 15:57:01 +02:00
# fork before creating the asyncio event loop
try:
pid = os.fork()
except AttributeError as e:
print_stderr(f"Error: {e!r}")
print_stderr("Running daemon in detached mode (-d) is not supported on this platform.")
print_stderr("Try running the daemon in the foreground (without -d).")
sys.exit(1)
2019-08-15 13:17:16 +02:00
if pid:
2019-08-30 15:57:01 +02:00
print_stderr("starting daemon (PID %d)" % pid)
loop, stop_loop, loop_thread = create_and_start_event_loop()
ready = daemon.wait_until_daemon_becomes_ready(config=config, timeout=5)
if ready:
sys_exit(0)
else:
print_stderr("timed out waiting for daemon to get ready")
sys_exit(1)
2019-08-15 13:17:16 +02:00
else:
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'w')
se = open(os.devnull, 'w')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
2019-08-30 15:57:01 +02:00
loop, stop_loop, loop_thread = create_and_start_event_loop()
try:
handle_cmd(
cmdname=cmdname,
config=config,
config_options=config_options,
)
except Exception:
_logger.exception("")
sys_exit(1)
def handle_cmd(*, cmdname: str, config: 'SimpleConfig', config_options: dict):
2015-12-23 15:59:32 +01:00
if cmdname == 'gui':
2019-06-25 15:26:24 +02:00
configure_logging(config)
2019-08-15 09:58:23 +02:00
fd = daemon.get_file_descriptor(config)
if fd is not None:
2023-05-24 17:41:44 +00:00
plugins = init_plugins(config, config.GUI_NAME)
d = daemon.Daemon(config, fd, start_network=False)
try:
d.run_gui(config, plugins)
except BaseException as e:
_logger.exception('daemon.run_gui errored')
sys_exit(1)
else:
sys_exit(0)
2016-02-01 09:25:57 +01:00
else:
2019-08-15 13:17:16 +02:00
result = daemon.request(config, 'gui', (config_options,))
2016-02-01 09:00:10 +01:00
2015-12-23 15:59:32 +01:00
elif cmdname == 'daemon':
2019-08-15 13:17:16 +02:00
2019-09-02 19:04:08 +02:00
configure_logging(config)
fd = daemon.get_file_descriptor(config)
if fd is not None:
# run daemon
init_plugins(config, 'cmdline')
d = daemon.Daemon(config, fd)
d.run_daemon()
sys_exit(0)
2016-02-01 09:00:10 +01:00
else:
2020-12-08 12:21:56 +01:00
# FIXME this message is lost in detached mode (parent process already exited after forking)
2019-09-02 19:04:08 +02:00
print_msg("Daemon already running")
sys_exit(1)
2015-08-26 17:44:19 +02:00
else:
2015-12-23 15:59:32 +01:00
# command line
configure_logging(config, log_to_file=False) # don't spam logfiles for each client-side RPC, but support "-v"
cmd = known_commands[cmdname]
2019-09-10 17:14:25 +02:00
wallet_path = config.get_wallet_path()
2023-05-24 17:41:44 +00:00
if not config.NETWORK_OFFLINE:
init_cmdline(config_options, wallet_path, True, config=config)
2023-05-24 17:41:44 +00:00
timeout = config.CLI_TIMEOUT
try:
result = daemon.request(config, 'run_cmdline', (config_options,), timeout)
except daemon.DaemonNotRunning:
2019-09-02 19:04:08 +02:00
print_msg("Daemon not running; try 'electrum daemon -d'")
if not cmd.requires_network:
print_msg("To run this command without a daemon, use --offline")
if cmd.name == "stop": # remove lockfile if it exists, as daemon looks dead
lockfile = daemon.get_lockfile(config)
if os.path.exists(lockfile):
print_msg("Found lingering lockfile for daemon. Removing.")
daemon.remove_lockfile(lockfile)
2019-08-15 13:17:16 +02:00
sys_exit(1)
except Exception as e:
2019-09-04 14:35:04 +02:00
print_stderr(str(e) or repr(e))
sys_exit(1)
else:
if cmd.requires_network:
print_msg("This command cannot be run offline")
sys_exit(1)
init_cmdline(config_options, wallet_path, False, config=config)
plugins = init_plugins(config, 'cmdline')
coro = run_offline_command(config, config_options, plugins)
fut = asyncio.run_coroutine_threadsafe(coro, loop)
try:
2019-09-04 14:35:04 +02:00
result = fut.result()
except Exception as e:
2019-09-04 14:35:04 +02:00
print_stderr(str(e) or repr(e))
sys_exit(1)
2017-10-24 14:04:16 +02:00
if isinstance(result, str):
2015-12-23 15:59:32 +01:00
print_msg(result)
elif type(result) is dict and result.get('error'):
print_stderr(result.get('error'))
sys_exit(1)
2015-12-23 15:59:32 +01:00
elif result is not None:
print_msg(json_encode(result))
2019-08-15 13:17:16 +02:00
sys_exit(0)
if __name__ == '__main__':
main()