Files
pallectrum/run_electrum

613 lines
25 KiB
Plaintext
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
MIN_PYTHON_VERSION = "3.10.0" # FIXME duplicated from setup.py
_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, Dict
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 unless explicitly overruled
if not any(['DeprecationWarning' in x for x in sys.warnoptions]):
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
# when running from source, on Windows, also search for DLLs in inner 'electrum' folder
if is_local and os.name == 'nt': # fixme: duplicated between main script and __init__.py :(
os.add_dll_directory(os.path.join(os.path.dirname(__file__), 'electrum'))
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
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
run_electrum: improve check_imports() $ ./run_electrum Error: No module named 'dns'. Try 'sudo python3 -m pip install <module-name>' $ pip install dns ERROR: Could not find a version that satisfies the requirement dns (from versions: none) ERROR: No matching distribution found for dns $ pip install dnspython Collecting dnspython Downloading dnspython-2.7.0-py3-none-any.whl (313 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 313.6/313.6 kB 3.4 MB/s eta 0:00:00 Installing collected packages: dnspython Successfully installed dnspython-2.7.0 $ ./run_electrum Error: No module named 'certifi'. Try 'sudo python3 -m pip install <module-name>' $ ./run_electrum Error: No module named 'google'. Try 'sudo python3 -m pip install <module-name>' $ pip install google Collecting google Downloading google-3.0.0-py2.py3-none-any.whl (45 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 45.3/45.3 kB 569.4 kB/s eta 0:00:00 Collecting beautifulsoup4 Downloading beautifulsoup4-4.13.4-py3-none-any.whl (187 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 187.3/187.3 kB 3.4 MB/s eta 0:00:00 Collecting soupsieve>1.2 Downloading soupsieve-2.7-py3-none-any.whl (36 kB) Collecting typing-extensions>=4.0.0 Using cached typing_extensions-4.14.0-py3-none-any.whl (43 kB) Installing collected packages: typing-extensions, soupsieve, beautifulsoup4, google Successfully installed beautifulsoup4-4.13.4 google-3.0.0 soupsieve-2.7 typing-extensions-4.14.0 $ ./run_electrum Error: No module named 'google'. Try 'sudo python3 -m pip install <module-name>' $ pip install protobuf Collecting protobuf Downloading protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl (321 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 321.1/321.1 kB 3.6 MB/s eta 0:00:00 Installing collected packages: protobuf Successfully installed protobuf-6.31.1 $ ./run_electrum Error: No module named 'aiorpcx'. Try 'sudo python3 -m pip install <module-name>' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 18, in <module> from .util import format_satoshis File "/home/nabijaczleweli/uwu/electrum/electrum/util.py", line 58, in <module> import aiohttp ModuleNotFoundError: No module named 'aiohttp' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 18, in <module> from .util import format_satoshis File "/home/nabijaczleweli/uwu/electrum/electrum/util.py", line 59, in <module> from aiohttp_socks import ProxyConnector, ProxyType ModuleNotFoundError: No module named 'aiohttp_socks' $ pip install aiohttp aiohttp-socks Requirement already satisfied: aiohttp in ./venv/lib/python3.11/site-packages (3.12.13) Collecting aiohttp-socks Downloading aiohttp_socks-0.10.1-py3-none-any.whl (10 kB) Requirement already satisfied: aiohappyeyeballs>=2.5.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (2.6.1) Requirement already satisfied: aiosignal>=1.1.2 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.3.2) Requirement already satisfied: attrs>=17.3.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (25.3.0) Requirement already satisfied: frozenlist>=1.1.1 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.7.0) Requirement already satisfied: multidict<7.0,>=4.5 in ./venv/lib/python3.11/site-packages (from aiohttp) (6.4.4) Requirement already satisfied: propcache>=0.2.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (0.3.2) Requirement already satisfied: yarl<2.0,>=1.17.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.20.1) Collecting python-socks[asyncio]<3.0.0,>=2.4.3 Downloading python_socks-2.7.1-py3-none-any.whl (54 kB) $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 44, in <module> import electrum_ecc as ecc ModuleNotFoundError: No module named 'electrum_ecc' $ pip install electrum_ecc Collecting electrum_ecc Downloading electrum_ecc-0.0.5.tar.gz (2.0 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.0/2.0 MB 7.9 MB/s eta 0:00:00 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: electrum_ecc Building wheel for electrum_ecc (pyproject.toml) ... done Created wheel for electrum_ecc: filename=electrum_ecc-0.0.5-py3-none-linux_x86_64.whl size=1285621 sha256=f2d27f7635ad82efa533055a4952e92f4db08ccab60d5dea0f3443e1ab57d5a7 Stored in directory: /mnt/filling/store/nabijaczleweli/.cache/pip/wheels/ad/4d/86/1607d5642f3437553a45658305d979155f8007a7108f5e6d79 Successfully built electrum_ecc Installing collected packages: electrum_ecc Successfully installed electrum_ecc-0.0.5 $ ./run_electrum Error: at least one of ('pycryptodomex', 'cryptography') needs to be installed. $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 97, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 47, in <module> from . import util, keystore, transaction, bitcoin, coinchooser, bip32, descriptor File "/home/nabijaczleweli/uwu/electrum/electrum/keystore.py", line 53, in <module> from .plugin import run_hook File "/home/nabijaczleweli/uwu/electrum/electrum/plugin.py", line 53, in <module> from .simple_config import SimpleConfig File "/home/nabijaczleweli/uwu/electrum/electrum/simple_config.py", line 12, in <module> from . import invoices File "/home/nabijaczleweli/uwu/electrum/electrum/invoices.py", line 7, in <module> from .json_db import StoredObject, stored_in File "/home/nabijaczleweli/uwu/electrum/electrum/json_db.py", line 29, in <module> import jsonpatch ModuleNotFoundError: No module named 'jsonpatch' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 99, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 77, in <module> from .lnworker import LNWallet File "/home/nabijaczleweli/uwu/electrum/electrum/lnworker.py", line 78, in <module> from .submarine_swaps import SwapManager File "/home/nabijaczleweli/uwu/electrum/electrum/submarine_swaps.py", line 16, in <module> import electrum_aionostr as aionostr ModuleNotFoundError: No module named 'electrum_aionostr'
2025-06-15 15:17:59 +02:00
import aiohttp
import aiohttp_socks
import electrum_ecc
import jsonpatch
import electrum_aionostr
2016-01-27 20:21:20 +05:30
except ImportError as e:
run_electrum: improve check_imports() $ ./run_electrum Error: No module named 'dns'. Try 'sudo python3 -m pip install <module-name>' $ pip install dns ERROR: Could not find a version that satisfies the requirement dns (from versions: none) ERROR: No matching distribution found for dns $ pip install dnspython Collecting dnspython Downloading dnspython-2.7.0-py3-none-any.whl (313 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 313.6/313.6 kB 3.4 MB/s eta 0:00:00 Installing collected packages: dnspython Successfully installed dnspython-2.7.0 $ ./run_electrum Error: No module named 'certifi'. Try 'sudo python3 -m pip install <module-name>' $ ./run_electrum Error: No module named 'google'. Try 'sudo python3 -m pip install <module-name>' $ pip install google Collecting google Downloading google-3.0.0-py2.py3-none-any.whl (45 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 45.3/45.3 kB 569.4 kB/s eta 0:00:00 Collecting beautifulsoup4 Downloading beautifulsoup4-4.13.4-py3-none-any.whl (187 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 187.3/187.3 kB 3.4 MB/s eta 0:00:00 Collecting soupsieve>1.2 Downloading soupsieve-2.7-py3-none-any.whl (36 kB) Collecting typing-extensions>=4.0.0 Using cached typing_extensions-4.14.0-py3-none-any.whl (43 kB) Installing collected packages: typing-extensions, soupsieve, beautifulsoup4, google Successfully installed beautifulsoup4-4.13.4 google-3.0.0 soupsieve-2.7 typing-extensions-4.14.0 $ ./run_electrum Error: No module named 'google'. Try 'sudo python3 -m pip install <module-name>' $ pip install protobuf Collecting protobuf Downloading protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl (321 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 321.1/321.1 kB 3.6 MB/s eta 0:00:00 Installing collected packages: protobuf Successfully installed protobuf-6.31.1 $ ./run_electrum Error: No module named 'aiorpcx'. Try 'sudo python3 -m pip install <module-name>' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 18, in <module> from .util import format_satoshis File "/home/nabijaczleweli/uwu/electrum/electrum/util.py", line 58, in <module> import aiohttp ModuleNotFoundError: No module named 'aiohttp' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 18, in <module> from .util import format_satoshis File "/home/nabijaczleweli/uwu/electrum/electrum/util.py", line 59, in <module> from aiohttp_socks import ProxyConnector, ProxyType ModuleNotFoundError: No module named 'aiohttp_socks' $ pip install aiohttp aiohttp-socks Requirement already satisfied: aiohttp in ./venv/lib/python3.11/site-packages (3.12.13) Collecting aiohttp-socks Downloading aiohttp_socks-0.10.1-py3-none-any.whl (10 kB) Requirement already satisfied: aiohappyeyeballs>=2.5.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (2.6.1) Requirement already satisfied: aiosignal>=1.1.2 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.3.2) Requirement already satisfied: attrs>=17.3.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (25.3.0) Requirement already satisfied: frozenlist>=1.1.1 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.7.0) Requirement already satisfied: multidict<7.0,>=4.5 in ./venv/lib/python3.11/site-packages (from aiohttp) (6.4.4) Requirement already satisfied: propcache>=0.2.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (0.3.2) Requirement already satisfied: yarl<2.0,>=1.17.0 in ./venv/lib/python3.11/site-packages (from aiohttp) (1.20.1) Collecting python-socks[asyncio]<3.0.0,>=2.4.3 Downloading python_socks-2.7.1-py3-none-any.whl (54 kB) $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 95, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 44, in <module> import electrum_ecc as ecc ModuleNotFoundError: No module named 'electrum_ecc' $ pip install electrum_ecc Collecting electrum_ecc Downloading electrum_ecc-0.0.5.tar.gz (2.0 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.0/2.0 MB 7.9 MB/s eta 0:00:00 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: electrum_ecc Building wheel for electrum_ecc (pyproject.toml) ... done Created wheel for electrum_ecc: filename=electrum_ecc-0.0.5-py3-none-linux_x86_64.whl size=1285621 sha256=f2d27f7635ad82efa533055a4952e92f4db08ccab60d5dea0f3443e1ab57d5a7 Stored in directory: /mnt/filling/store/nabijaczleweli/.cache/pip/wheels/ad/4d/86/1607d5642f3437553a45658305d979155f8007a7108f5e6d79 Successfully built electrum_ecc Installing collected packages: electrum_ecc Successfully installed electrum_ecc-0.0.5 $ ./run_electrum Error: at least one of ('pycryptodomex', 'cryptography') needs to be installed. $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 97, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 47, in <module> from . import util, keystore, transaction, bitcoin, coinchooser, bip32, descriptor File "/home/nabijaczleweli/uwu/electrum/electrum/keystore.py", line 53, in <module> from .plugin import run_hook File "/home/nabijaczleweli/uwu/electrum/electrum/plugin.py", line 53, in <module> from .simple_config import SimpleConfig File "/home/nabijaczleweli/uwu/electrum/electrum/simple_config.py", line 12, in <module> from . import invoices File "/home/nabijaczleweli/uwu/electrum/electrum/invoices.py", line 7, in <module> from .json_db import StoredObject, stored_in File "/home/nabijaczleweli/uwu/electrum/electrum/json_db.py", line 29, in <module> import jsonpatch ModuleNotFoundError: No module named 'jsonpatch' $ ./run_electrum Traceback (most recent call last): File "/home/nabijaczleweli/uwu/electrum/./run_electrum", line 99, in <module> from electrum.logging import get_logger, configure_logging # import logging submodule first ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/nabijaczleweli/uwu/electrum/electrum/__init__.py", line 19, in <module> from .wallet import Wallet File "/home/nabijaczleweli/uwu/electrum/electrum/wallet.py", line 77, in <module> from .lnworker import LNWallet File "/home/nabijaczleweli/uwu/electrum/electrum/lnworker.py", line 78, in <module> from .submarine_swaps import SwapManager File "/home/nabijaczleweli/uwu/electrum/electrum/submarine_swaps.py", line 16, in <module> import electrum_aionostr as aionostr ModuleNotFoundError: No module named 'electrum_aionostr'
2025-06-15 15:17:59 +02:00
sys.exit(f"Error: {str(e)}. Some dependencies are missing. Have you read the README? Or just try '$ python3 -m pip install -r contrib/requirements/requirements.txt'")
if not ((0, 25, 0) <= aiorpcx._version < (0, 26)):
raise RuntimeError(f'aiorpcX version {aiorpcx._version} does not match required: 0.25.0<=ver<0.26')
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
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()
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
from electrum.payment_identifier import PaymentIdentifier
from electrum import SimpleConfig
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
from electrum.util import InvalidPassword
2025-03-06 11:43:50 +01:00
from electrum.plugin import Plugins
from electrum.commands import get_parser, get_simple_parser, known_commands, Commands, config_variables
from electrum import daemon
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
from electrum.util import create_and_start_event_loop, UserFacingException, JsonRPCError
from electrum.i18n import set_language
2019-04-26 18:52:26 +02:00
if TYPE_CHECKING:
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
import threading
2019-04-26 18:52:26 +02:00
_logger = get_logger(__name__)
# get password routine
def prompt_password(prompt: str, *, confirm: bool = True) -> Optional[str]:
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, *, rpcserver: bool, config: 'SimpleConfig'):
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
if cmd.requires_wallet and not wallet_path:
print_msg("wallet path not provided.")
sys_exit(1)
2018-02-10 19:18:48 +01:00
# instantiate wallet for command-line
storage = WalletStorage(wallet_path, allow_partial_writes=config.WALLET_PARTIAL_WRITES) if wallet_path else None
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
# 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.")
2011-11-14 20:35:54 +01:00
# commands needing password
if ((cmd.requires_wallet and storage.is_encrypted() and not rpcserver)
or (cmdname == 'load_wallet' and storage.is_encrypted())
or (cmdname in ['password', 'unlock'])
or (cmd.requires_password and not rpcserver)):
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') is not None:
password = config.get('password')
if password == '':
password = None
else:
password = prompt_password('Password:', confirm=False)
else:
password = None
config_options['password'] = config_options.get('password') or password
2012-05-13 01:32:28 +02:00
if cmd.name == 'password' and 'new_password' not in config_options:
new_password = prompt_password('New password:')
config_options['new_password'] = new_password
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:
raise UserFacingException("Error: No connected hw device found. Cannot decrypt this wallet.")
2018-02-10 19:18:48 +01:00
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_)
hw plugins: cmdline: fix offline commands for encrypted hw wallets ``` $ ./run_electrum --testnet signmessage -w /home/user/.electrum/testnet/wallets/test_trezor_white_bip84 tb1q5pguna9y2g9y2gsu8r8gmxeye2cefvyly8dg02 heyheyhey -o 0.84 | W | plugins.jade.jadepy.jade | No module named 'electrum.plugins.jade.jadepy.jade_ble' 0.84 | W | plugins.jade.jadepy.jade | BLE scanning/connectivity will not be available 3.73 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugins/trezor/clientbase.py", line 151, in get_xpub node = trezorlib.btc.get_public_node(self.client, address_n).node File "/home/user/.local/lib/python3.10/site-packages/trezorlib/tools.py", line 274, in wrapped_f ret = f(*args, **kwargs) File "/home/user/.local/lib/python3.10/site-packages/trezorlib/btc.py", line 125, in get_public_node return client.call( File "/home/user/.local/lib/python3.10/site-packages/trezorlib/tools.py", line 297, in wrapped_f return f(client, *args, **kwargs) File "/home/user/.local/lib/python3.10/site-packages/trezorlib/client.py", line 260, in call resp = self._callback_pin(resp) File "/home/user/.local/lib/python3.10/site-packages/trezorlib/client.py", line 186, in _callback_pin pin = self.ui.get_pin(msg.type) File "/home/user/wspace/electrum/electrum/plugins/trezor/clientbase.py", line 308, in get_pin pin = self.handler.get_pin(msg.format(self.device), show_strength=show_strength) AttributeError: 'NoneType' object has no attribute 'get_pin' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 540, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 227, in run_offline_command password = get_password_for_hw_device_encrypted_storage(plugins) File "/home/user/wspace/electrum/./run_electrum", line 212, in get_password_for_hw_device_encrypted_storage return client.get_password_for_storage_encryption() File "/home/user/wspace/electrum/electrum/plugin.py", line 523, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "/home/user/wspace/electrum/electrum/plugin.py", line 516, in run_in_hwd_thread return fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/home/user/wspace/electrum/electrum/plugins/hw_wallet/plugin.py", line 260, in get_password_for_storage_encryption xpub = self.get_xpub(derivation, "standard") File "/home/user/wspace/electrum/electrum/plugin.py", line 523, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "/home/user/wspace/electrum/electrum/plugin.py", line 513, in run_in_hwd_thread return func() File "/home/user/wspace/electrum/electrum/plugins/trezor/clientbase.py", line 150, in get_xpub with self.run_flow(creating_wallet=creating): File "/home/user/wspace/electrum/electrum/plugins/trezor/clientbase.py", line 89, in __exit__ self.end_flow() File "/home/user/wspace/electrum/electrum/plugins/trezor/clientbase.py", line 82, in end_flow self.handler.finished() AttributeError: 'NoneType' object has no attribute 'finished' ```
2024-10-10 21:25:34 +00:00
client.handler = client.plugin.create_handler(None)
return client.get_password_for_storage_encryption()
2018-03-14 12:42:42 +01:00
except UserCancelled:
raise
2018-02-10 19:18:48 +01:00
async def run_offline_command(config: 'SimpleConfig', config_options: dict, wallet_path: str, plugins: 'Plugins'):
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
password = config_options.get('password')
if 'wallet_path' in cmd.options and config_options.get('wallet_path') is None:
config_options['wallet_path'] = wallet_path
2017-03-03 16:05:13 +01:00
if cmd.requires_wallet:
storage = WalletStorage(wallet_path, allow_partial_writes=config.WALLET_PARTIAL_WRITES)
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)
db = WalletDB(storage.read(), storage=storage, upgrade=True)
wallet = Wallet(db, 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.")
raise
if cmd.requires_network:
print_msg("Warning: running command offline")
# arguments passed to function
2017-01-22 21:25:24 +03:00
args = [config.get(x) for x in cmd.params]
# decode json arguments
if cmdname not in ('setconfig',):
args = list(map(json_decode, args))
# options
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)
func = getattr(cmd_runner, cmd.name)
result = await func(*args, **kwargs)
# save wallet
2015-12-23 15:23:33 +01:00
if wallet:
wallet.save_db()
return result
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
loop = None # type: Optional[asyncio.AbstractEventLoop]
stop_loop = None # type: Optional[asyncio.Future]
loop_thread = None # type: Optional[threading.Thread]
2025-06-03 11:26:23 +02:00
def sys_exit(i):
# stop event loop and exit
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
if loop:
loop.call_soon_threadsafe(stop_loop.set_result, 1)
loop_thread.join(timeout=1)
sys.exit(i)
2025-06-03 11:26:23 +02:00
def read_config(config_options: dict) -> SimpleConfig:
"""
Reads the config file and returns SimpleConfig, on failure it will potentially
show a GUI error dialog if a gui is available, and then re-raise the exception.
"""
try:
return SimpleConfig(config_options)
except Exception as config_error:
# parse full cmd to find out which UI is being used
full_config_options = parse_command_line(simple_parser=False)
if full_config_options.get("cmd") == 'gui':
gui_name = full_config_options.get(SimpleConfig.GUI_NAME.key(), 'qt')
try:
gui = __import__(f'electrum.gui.{gui_name}', fromlist=['electrum'])
gui.standalone_exception_dialog(config_error) # type: ignore
except Exception as e:
print_stderr(f"Error showing standalone gui dialog: {e}")
raise
2025-06-03 11:26:23 +02:00
def parse_command_line(simple_parser=False) -> Dict:
# parse command line from sys.argv
if simple_parser:
parser = get_simple_parser()
options, args = parser.parse_args()
config_options = options.__dict__
config_options['cmd'] = 'gui'
else:
parser = get_parser()
args = parser.parse_args()
config_options = args.__dict__
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())}
if config_options.get(SimpleConfig.NETWORK_SERVER.key()):
config_options[SimpleConfig.NETWORK_AUTO_CONNECT.key()] = False
config_options['cwd'] = cwd = os.getcwd()
# 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')):
config_options['portable'] = True
if config_options.get('portable'):
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')
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
if not config_options.get('verbosity'):
warnings.simplefilter('ignore', DeprecationWarning)
return config_options
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
2025-06-03 11:26:23 +02:00
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
def main():
global loop, stop_loop, loop_thread
# 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))
# old 'help' syntax
2017-01-22 21:25:24 +03:00
if len(sys.argv) > 1 and sys.argv[1] == 'help':
sys.argv.remove('help')
sys.argv.append('-h')
# 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
try:
i = sys.argv.index('-v')
except ValueError:
pass
else:
sys.argv[i] = '-v*'
# read arguments from stdin pipe and prompt
for i, arg in enumerate(sys.argv):
if arg == '-':
if not sys.stdin.isatty():
sys.argv[i] = sys.stdin.read()
break
else:
2018-04-07 17:10:30 +02:00
raise Exception('Cannot get argument from stdin')
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):', confirm=False)
# config is an object passed to the various constructors (wallet, interface, gui)
if is_android:
import importlib.util
config_options = {
'verbosity': '*' if util.is_android_debug_apk() else '',
2015-09-07 16:44:17 +02:00
'cmd': 'gui',
SimpleConfig.GUI_NAME.key(): 'qml',
SimpleConfig.WALLET_USE_SINGLE_PASSWORD.key(): True,
}
SimpleConfig.set_chain_config_opt_based_on_android_packagename(config_options)
else:
# save sys args for next parser
saved_sys_argv = sys.argv[:]
# disable help, the next parser will display it
for x in sys.argv:
if x in ['-h', '--help']:
sys.argv.remove(x)
# parse first without plugins
config_options = parse_command_line(simple_parser=True)
tmp_config = read_config(config_options)
# load (only) the commands modules of plugins so their commands are registered
_plugin_commands = Plugins(tmp_config, cmd_only=True)
# re-parse command line
sys.argv = saved_sys_argv[:]
config_options = parse_command_line()
2015-05-30 06:56:45 +02:00
config = read_config(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.
# Note: the CLI is intentionally always non-localized.
# Note: Some unit tests might rely on the default non-localized strings.
if cmdname == 'gui':
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)
chain = config.get_selected_chain()
chain.set_as_network()
# 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)
if sys.platform == "linux" and not is_android:
import electrum.harden_memory_linux
electrum.harden_memory_linux.set_dumpable_safe(False)
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
# 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)
if pid:
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)
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())
loop, stop_loop, loop_thread = create_and_start_event_loop()
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
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):
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:
d = daemon.Daemon(config, fd, start_network=False)
try:
d.run_gui()
except BaseException as e:
_logger.exception('daemon.run_gui errored')
sys_exit(1)
else:
sys_exit(0)
else:
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
try:
result = daemon.request(config, 'gui', (config_options,))
except JsonRPCError as e:
if e.code == JsonRPCError.Codes.USERFACING:
print_stderr(e.message)
elif e.code == JsonRPCError.Codes.INTERNAL:
print_stderr("(inside daemon): " + e.data["traceback"])
print_stderr(e.message)
else:
raise Exception(f"unknown error code {e.code}")
sys_exit(1)
elif cmdname == 'daemon':
configure_logging(config)
fd = daemon.get_file_descriptor(config)
if fd is not None:
# run daemon
d = daemon.Daemon(config, fd)
d.run_daemon()
sys_exit(0)
else:
# FIXME this message is lost in detached mode (parent process already exited after forking)
print_msg("Daemon already running")
sys_exit(1)
else:
# 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]
wallet_path = config.get_wallet_path()
if cmd.requires_wallet and not wallet_path:
print_stderr('wallet path not provided')
sys_exit(1)
if not config.NETWORK_OFFLINE:
init_cmdline(config_options, wallet_path, rpcserver=True, config=config)
timeout = config.CLI_TIMEOUT
try:
result = daemon.request(config, 'run_cmdline', (config_options,), timeout)
except daemon.DaemonNotRunning:
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)
sys_exit(1)
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
except JsonRPCError as e:
if e.code == JsonRPCError.Codes.USERFACING:
print_stderr(e.message)
elif e.code == JsonRPCError.Codes.INTERNAL:
print_stderr("(inside daemon): " + e.data["traceback"])
print_stderr(e.message)
else:
raise Exception(f"unknown error code {e.code}")
sys_exit(1)
except Exception as e:
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
_logger.exception("error running command (with daemon)")
sys_exit(1)
else:
if cmd.requires_network:
print_msg("This command cannot be run offline")
sys_exit(1)
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.")
print_stderr("Run this command without --offline to interact with the daemon")
sys_exit(1)
init_cmdline(config_options, wallet_path, rpcserver=False, config=config)
2025-03-06 11:43:50 +01:00
plugins = Plugins(config, 'cmdline')
coro = run_offline_command(config, config_options, wallet_path, plugins)
fut = asyncio.run_coroutine_threadsafe(coro, loop)
try:
try:
result = fut.result()
finally:
plugins.stop()
plugins.stopped_event.wait(1)
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
except UserFacingException as e:
print_stderr(str(e))
sys_exit(1)
except InvalidPassword:
print_stderr("Invalid password")
sys_exit(1)
except UserCancelled:
print_stderr("Aborted by user")
sys_exit(1)
except Exception as e:
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
_logger.exception("error running command (without daemon)")
sys_exit(1)
cli/rpc: nicer error messages and error-passing Previously, generally, in case of any error, commands would raise a generic "Exception()" and the CLI/RPC would convert that and return it as `str(e)`. With this change, we now distinguish "user-facing exceptions" (e.g. "Password required" or "wallet not loaded") and "internal errors" (e.g. bugs). - for "user-facing exceptions", the behaviour is unchanged - for "internal errors", we now pass around the traceback (e.g. from daemon server to rpc client) and show it to the user (previously, assuming there was a daemon running, the user could only retrieve the exception from the log of that daemon). These errors use a new jsonrpc error code int (code 2). As the logic only changes for "internal errors", I deem this change not to be compatibility-breaking. ---------- Examples follow. Consider the following two commands: ``` @command('') async def errorgood(self): from electrum.util import UserFacingException raise UserFacingException("heyheyhey") @command('') async def errorbad(self): raise Exception("heyheyhey") ``` ---------- (before change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9221) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad heyheyhey $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} ``` ---------- (after change) CLI with daemon: ``` $ ./run_electrum --testnet daemon -d starting daemon (PID 9254) $ ./run_electrum --testnet errorgood heyheyhey $ ./run_electrum --testnet errorbad (inside daemon): Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/daemon.py", line 254, in handle response['result'] = await f(*params) File "/home/user/wspace/electrum/electrum/daemon.py", line 361, in run_cmdline result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey internal error while executing RPC $ ./run_electrum --testnet stop Daemon stopped ``` CLI without daemon: ``` $ ./run_electrum --testnet -o errorgood heyheyhey $ ./run_electrum --testnet -o errorbad 0.78 | E | __main__ | error running command (without daemon) Traceback (most recent call last): File "/home/user/wspace/electrum/./run_electrum", line 534, in handle_cmd result = fut.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/home/user/wspace/electrum/./run_electrum", line 255, in run_offline_command result = await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 163, in func_wrapper return await func(*args, **kwargs) File "/home/user/wspace/electrum/electrum/commands.py", line 217, in errorbad raise Exception("heyheyhey") Exception: heyheyhey ``` RPC: ``` $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorgood","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 1, "message": "heyheyhey"}} $ curl --data-binary '{"id":"curltext","jsonrpc":"2.0","method":"errorbad","params":[]}' http://user:pass@127.0.0.1:7777 {"id": "curltext", "jsonrpc": "2.0", "error": {"code": 2, "message": "internal error while executing RPC", "data": {"exception": "Exception('heyheyhey')", "traceback": "Traceback (most recent call last):\n File \"/home/user/wspace/electrum/electrum/daemon.py\", line 254, in handle\n response['result'] = await f(*params)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 163, in func_wrapper\n return await func(*args, **kwargs)\n File \"/home/user/wspace/electrum/electrum/commands.py\", line 217, in errorbad\n raise Exception(\"heyheyhey\")\nException: heyheyhey\n"}}} ```
2024-02-12 19:02:02 +00:00
# print result
2017-10-24 14:04:16 +02:00
if isinstance(result, str):
print_msg(result)
elif result is not None:
print_msg(json_encode(result))
sys_exit(0)
fix main script hanging (not exiting after exception) in some cases Previously an unhandled exception in the main script could cause the main thread to die but the process to hang, as the event loop thread would keep running. example: $ ./run_electrum -o signmessage tb1qeh090ruc3cs5hry90tev4fsvrnegulw8xssdzx "mymsg" -w ~/.electrum/testnet/wallets/test_segwit_2 Traceback (most recent call last): File "./run_electrum", line 424, in <module> init_cmdline(config_options, wallet_path, False) File "./run_electrum", line 146, in init_cmdline db = WalletDB(storage.read(), manual_upgrades=False) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 72, in __init__ self.load_data(raw) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 103, in load_data self._after_upgrade_tasks() File "/home/user/wspace/electrum/electrum/wallet_db.py", line 189, in _after_upgrade_tasks self._load_transactions() File "/home/user/wspace/electrum/electrum/util.py", line 406, in <lambda> return lambda *args, **kw_args: do_profile(args, kw_args) File "/home/user/wspace/electrum/electrum/util.py", line 402, in do_profile o = func(*args, **kw_args) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1139, in _load_transactions self.data = StoredDict(self.data, self, []) File "/home/user/wspace/electrum/electrum/json_db.py", line 79, in __init__ self.__setitem__(k, v) File "/home/user/wspace/electrum/electrum/json_db.py", line 44, in wrapper return func(self, *args, **kwargs) File "/home/user/wspace/electrum/electrum/json_db.py", line 105, in __setitem__ v = self.db._convert_dict(self.path, key, v) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in _convert_dict v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/wallet_db.py", line 1182, in <genexpr> v = dict((k, Invoice.from_json(x)) for k, x in v.items()) File "/home/user/wspace/electrum/electrum/invoices.py", line 110, in from_json return OnchainInvoice(**x) File "<attrs generated init electrum.invoices.OnchainInvoice>", line 8, in __init__ File "/home/user/wspace/electrum/electrum/invoices.py", line 68, in _decode_outputs output = PartialTxOutput.from_legacy_tuple(*output) File "/home/user/wspace/electrum/electrum/transaction.py", line 131, in from_legacy_tuple return cls.from_address_and_value(addr, val) File "/home/user/wspace/electrum/electrum/transaction.py", line 104, in from_address_and_value return cls(scriptpubkey=bfh(bitcoin.address_to_script(address)), File "/home/user/wspace/electrum/electrum/bitcoin.py", line 422, in address_to_script raise BitcoinException(f"invalid bitcoin address: {addr}") electrum.util.BitcoinException: invalid bitcoin address: tb1qckp4ztmstwtyxzml3dmfvegeq5mfxwu2h3q94l
2020-10-05 17:07:33 +02:00
if __name__ == '__main__':
main()