Files
pallectrum/electrum/plugin.py

1099 lines
45 KiB
Python
Raw Normal View History

2015-05-23 10:38:19 +02:00
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
2024-06-19 11:24:13 +02:00
# Copyright (C) 2015-2024 Thomas Voegtlin
2015-05-23 10:38:19 +02:00
#
2016-02-23 11:36:42 +01:00
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
2015-05-23 10:38:19 +02:00
#
2016-02-23 11:36:42 +01:00
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
2015-05-23 10:38:19 +02: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.
2024-06-19 11:24:13 +02:00
import json
2015-05-23 10:38:19 +02:00
import os
import pkgutil
import importlib.util
2015-12-03 11:18:10 +01:00
import time
2017-01-22 21:25:24 +03:00
import threading
import traceback
import sys
2024-06-19 11:24:13 +02:00
import aiohttp
import zipfile as zipfile_lib
2024-06-19 11:24:13 +02:00
from typing import (NamedTuple, Any, Union, TYPE_CHECKING, Optional, Tuple,
2024-06-19 11:24:13 +02:00
Dict, Iterable, List, Sequence, Callable, TypeVar, Mapping)
import concurrent
import zipimport
from concurrent import futures
from functools import wraps, partial
from itertools import chain
2015-05-23 10:38:19 +02:00
2017-01-22 21:25:24 +03:00
from .i18n import _
from .util import (profiler, DaemonThread, UserCancelled, ThreadJob, UserFacingException)
2018-10-25 22:20:33 +02:00
from . import bip32
from . import plugins
2025-03-15 18:57:25 +01:00
from .simple_config import ConfigVar, SimpleConfig
2019-04-26 18:52:26 +02:00
from .logging import get_logger, Logger
from .crypto import sha256
2018-10-22 16:41:25 +02:00
if TYPE_CHECKING:
from .plugins.hw_wallet import HW_PluginBase, HardwareClientBase, HardwareHandlerBase
from .keystore import Hardware_KeyStore, KeyStore
from .wallet import Abstract_Wallet
2019-04-26 18:52:26 +02:00
_logger = get_logger(__name__)
plugin_loaders = {}
hook_names = set()
hooks = {}
_root_permission_cache = {}
plugins: better handle exceptions in __init__ When importing a plugin, if it raised an exception in its `__init__` file, we ignored it, and still loaded the plugin, in a potentially half-broken state. This is because maybe_load_plugin_init_method only calls exec_module_from_spec if the plugin is not already in sys.modules, but exec_module_from_spec will put the plugin into sys.modules even if it errors. Consider this patch to test with, enable the "labels" plugin: ```patch diff --git a/electrum/plugins/labels/__init__.py b/electrum/plugins/labels/__init__.py index b68127df8e..0d6d95abce 100644 --- a/electrum/plugins/labels/__init__.py +++ b/electrum/plugins/labels/__init__.py @@ -21,3 +21,5 @@ async def pull(self: 'Commands', plugin: 'LabelsPlugin' = None, wallet=None, for arg:bool:force:pull all labels """ return await plugin.pull_thread(wallet, force=force) + +raise Exception("heyheyhey") ``` I would expect we don't load the labels plugin due to the error, but we do: ``` >>> plugins.get_plugin("labels") <electrum.plugins.labels.qt.Plugin object at 0x7801df30fb50> ``` Log: ``` $ ./run_electrum -v --testnet -o 0.75 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.75 | E | p/plugin.Plugins | cannot initialize plugin labels: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 148, in exec_module_from_spec spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/user/wspace/electrum/electrum/plugins/labels/__init__.py", line 25, in <module> raise Exception("heyheyhey") Exception: heyheyhey The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 167, in load_plugins self.maybe_load_plugin_init_method(name) File "/home/user/wspace/electrum/electrum/plugin.py", line 293, in maybe_load_plugin_init_method module = self.exec_module_from_spec(init_spec, base_name) File "/home/user/wspace/electrum/electrum/plugin.py", line 150, in exec_module_from_spec raise Exception(f"Error pre-loading {path}: {repr(e)}") from e Exception: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') 0.75 | D | util.profiler | Plugins.__init__ 0.0030 sec 0.84 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.89 | I | __main__ | get_default_language: detected default as lang='en_UK' 0.89 | I | i18n | setting language to 'en_UK' 0.89 | I | logging | Electrum version: 4.5.8 - https://electrum.org - https://github.com/spesmilo/electrum 0.89 | I | logging | Python version: 3.10.12 (main, Feb 4 2025, 14:57:36) [GCC 11.4.0]. On platform: Linux-6.8.0-52-generic-x86_64-with-glibc2.35 0.89 | I | logging | Logging to file: /home/user/.electrum/testnet/logs/electrum_log_20250319T161247Z_6605.log 0.89 | I | logging | Log filters: verbosity '*', verbosity_shortcuts '' 0.89 | I | exchange_rate.FxThread | using exchange CoinGecko 0.90 | D | util.profiler | Daemon.__init__ 0.0047 sec 0.90 | I | daemon.Daemon | starting taskgroup. 0.90 | I | daemon.CommandsServer | now running and listening. socktype=unix, addr=/home/user/.electrum/testnet/daemon_rpc_socket 0.90 | I | p/plugin.Plugins | registering hardware bitbox02: ['hardware', 'bitbox02', 'BitBox02'] 0.90 | I | p/plugin.Plugins | registering hardware coldcard: ['hardware', 'coldcard', 'Coldcard Wallet'] 0.90 | I | p/plugin.Plugins | registering hardware digitalbitbox: ['hardware', 'digitalbitbox', 'Digital Bitbox wallet'] 0.90 | I | p/plugin.Plugins | could not find manifest.json of plugin hw_wallet, skipping... 0.90 | I | p/plugin.Plugins | registering hardware jade: ['hardware', 'jade', 'Jade wallet'] 0.90 | I | p/plugin.Plugins | registering hardware keepkey: ['hardware', 'keepkey', 'KeepKey wallet'] 0.90 | I | p/plugin.Plugins | registering hardware ledger: ['hardware', 'ledger', 'Ledger wallet'] 0.90 | I | p/plugin.Plugins | registering hardware safe_t: ['hardware', 'safe_t', 'Safe-T mini wallet'] 0.90 | I | p/plugin.Plugins | registering hardware trezor: ['hardware', 'trezor', 'Trezor wallet'] 0.90 | I | p/plugin.Plugins | registering wallet type ('2fa', 'trustedcoin') 1.01 | I | p/plugin.Plugins | loaded plugin 'labels'. (from thread: 'GUI') 1.01 | D | util.profiler | Plugins.__init__ 0.1183 sec ```
2025-03-19 16:27:23 +00:00
_exec_module_failure = {} # type: Dict[str, Exception]
2013-09-23 16:14:28 +02:00
2015-12-03 11:18:10 +01:00
class Plugins(DaemonThread):
LOGGING_SHORTCUT = 'p'
2023-09-08 14:48:36 +00:00
pkgpath = os.path.dirname(plugins.__file__)
@profiler
def __init__(self, config: SimpleConfig, gui_name = None, cmd_only: bool = False):
self.config = config
2025-03-06 11:43:50 +01:00
self.cmd_only = cmd_only # type: bool
self.internal_plugin_metadata = {}
self.external_plugin_metadata = {}
if cmd_only:
# only import the command modules of plugins
Logger.__init__(self)
2025-03-06 11:43:50 +01:00
self.find_plugins()
self.load_plugins()
2025-03-06 11:43:50 +01:00
return
2015-12-03 11:18:10 +01:00
DaemonThread.__init__(self)
2025-03-06 11:43:50 +01:00
self.device_manager = DeviceMgr(config)
self.name = 'Plugins' # set name of thread
self.hw_wallets = {}
self.plugins = {} # type: Dict[str, BasePlugin]
self.gui_name = gui_name
2025-03-06 11:43:50 +01:00
self.find_plugins()
self.load_plugins()
self.add_jobs(self.device_manager.thread_jobs())
self.start()
@property
def descriptions(self):
return dict(list(self.internal_plugin_metadata.items()) + list(self.external_plugin_metadata.items()))
2023-09-08 14:48:36 +00:00
def find_directory_plugins(self, pkg_path: str, external: bool):
"""Finds plugins in directory form from the given pkg_path and populates the metadata dicts"""
iter_modules = list(pkgutil.iter_modules([pkg_path]))
for loader, name, ispkg in iter_modules:
# FIXME pyinstaller binaries are packaging each built-in plugin twice:
# once as data and once as code. To honor the "no duplicates" rule below,
# we exclude the ones packaged as *code*, here:
if loader.__class__.__qualname__ == "PyiFrozenImporter":
continue
module_path = os.path.join(pkg_path, name)
if external and not self._has_recursive_root_permissions(module_path):
self.logger.info(f"Not loading plugin {module_path}: directory has user write permissions")
continue
if self.cmd_only and not self.config.get('enable_plugin_' + name) is True:
continue
try:
with open(os.path.join(module_path, 'manifest.json'), 'r') as f:
d = json.load(f)
except FileNotFoundError:
self.logger.info(f"could not find manifest.json of plugin {name}, skipping...")
2025-03-06 11:43:50 +01:00
continue
if 'fullname' not in d:
continue
d['display_name'] = d['fullname']
d['path'] = module_path
if not self.cmd_only:
gui_good = self.gui_name in d.get('available_for', [])
if not gui_good:
continue
details = d.get('registers_wallet_type')
if details:
self.register_wallet_type(name, gui_good, details)
details = d.get('registers_keystore')
if details:
self.register_keystore(name, gui_good, details)
if name in self.internal_plugin_metadata or name in self.external_plugin_metadata:
_logger.info(f"Found the following plugin modules: {iter_modules=}")
raise Exception(f"duplicate plugins? for {name=}")
if not external:
self.internal_plugin_metadata[name] = d
else:
self.external_plugin_metadata[name] = d
2025-03-06 11:43:50 +01:00
@staticmethod
plugins: better handle exceptions in __init__ When importing a plugin, if it raised an exception in its `__init__` file, we ignored it, and still loaded the plugin, in a potentially half-broken state. This is because maybe_load_plugin_init_method only calls exec_module_from_spec if the plugin is not already in sys.modules, but exec_module_from_spec will put the plugin into sys.modules even if it errors. Consider this patch to test with, enable the "labels" plugin: ```patch diff --git a/electrum/plugins/labels/__init__.py b/electrum/plugins/labels/__init__.py index b68127df8e..0d6d95abce 100644 --- a/electrum/plugins/labels/__init__.py +++ b/electrum/plugins/labels/__init__.py @@ -21,3 +21,5 @@ async def pull(self: 'Commands', plugin: 'LabelsPlugin' = None, wallet=None, for arg:bool:force:pull all labels """ return await plugin.pull_thread(wallet, force=force) + +raise Exception("heyheyhey") ``` I would expect we don't load the labels plugin due to the error, but we do: ``` >>> plugins.get_plugin("labels") <electrum.plugins.labels.qt.Plugin object at 0x7801df30fb50> ``` Log: ``` $ ./run_electrum -v --testnet -o 0.75 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.75 | E | p/plugin.Plugins | cannot initialize plugin labels: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 148, in exec_module_from_spec spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/user/wspace/electrum/electrum/plugins/labels/__init__.py", line 25, in <module> raise Exception("heyheyhey") Exception: heyheyhey The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 167, in load_plugins self.maybe_load_plugin_init_method(name) File "/home/user/wspace/electrum/electrum/plugin.py", line 293, in maybe_load_plugin_init_method module = self.exec_module_from_spec(init_spec, base_name) File "/home/user/wspace/electrum/electrum/plugin.py", line 150, in exec_module_from_spec raise Exception(f"Error pre-loading {path}: {repr(e)}") from e Exception: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') 0.75 | D | util.profiler | Plugins.__init__ 0.0030 sec 0.84 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.89 | I | __main__ | get_default_language: detected default as lang='en_UK' 0.89 | I | i18n | setting language to 'en_UK' 0.89 | I | logging | Electrum version: 4.5.8 - https://electrum.org - https://github.com/spesmilo/electrum 0.89 | I | logging | Python version: 3.10.12 (main, Feb 4 2025, 14:57:36) [GCC 11.4.0]. On platform: Linux-6.8.0-52-generic-x86_64-with-glibc2.35 0.89 | I | logging | Logging to file: /home/user/.electrum/testnet/logs/electrum_log_20250319T161247Z_6605.log 0.89 | I | logging | Log filters: verbosity '*', verbosity_shortcuts '' 0.89 | I | exchange_rate.FxThread | using exchange CoinGecko 0.90 | D | util.profiler | Daemon.__init__ 0.0047 sec 0.90 | I | daemon.Daemon | starting taskgroup. 0.90 | I | daemon.CommandsServer | now running and listening. socktype=unix, addr=/home/user/.electrum/testnet/daemon_rpc_socket 0.90 | I | p/plugin.Plugins | registering hardware bitbox02: ['hardware', 'bitbox02', 'BitBox02'] 0.90 | I | p/plugin.Plugins | registering hardware coldcard: ['hardware', 'coldcard', 'Coldcard Wallet'] 0.90 | I | p/plugin.Plugins | registering hardware digitalbitbox: ['hardware', 'digitalbitbox', 'Digital Bitbox wallet'] 0.90 | I | p/plugin.Plugins | could not find manifest.json of plugin hw_wallet, skipping... 0.90 | I | p/plugin.Plugins | registering hardware jade: ['hardware', 'jade', 'Jade wallet'] 0.90 | I | p/plugin.Plugins | registering hardware keepkey: ['hardware', 'keepkey', 'KeepKey wallet'] 0.90 | I | p/plugin.Plugins | registering hardware ledger: ['hardware', 'ledger', 'Ledger wallet'] 0.90 | I | p/plugin.Plugins | registering hardware safe_t: ['hardware', 'safe_t', 'Safe-T mini wallet'] 0.90 | I | p/plugin.Plugins | registering hardware trezor: ['hardware', 'trezor', 'Trezor wallet'] 0.90 | I | p/plugin.Plugins | registering wallet type ('2fa', 'trustedcoin') 1.01 | I | p/plugin.Plugins | loaded plugin 'labels'. (from thread: 'GUI') 1.01 | D | util.profiler | Plugins.__init__ 0.1183 sec ```
2025-03-19 16:27:23 +00:00
def exec_module_from_spec(spec, path: str):
if prev_fail := _exec_module_failure.get(path):
raise Exception(f"exec_module already failed once before, with: {prev_fail!r}")
try:
module = importlib.util.module_from_spec(spec)
# sys.modules needs to be modified for relative imports to work
# see https://stackoverflow.com/a/50395128
sys.modules[path] = module
spec.loader.exec_module(module)
except Exception as e:
plugins: better handle exceptions in __init__ When importing a plugin, if it raised an exception in its `__init__` file, we ignored it, and still loaded the plugin, in a potentially half-broken state. This is because maybe_load_plugin_init_method only calls exec_module_from_spec if the plugin is not already in sys.modules, but exec_module_from_spec will put the plugin into sys.modules even if it errors. Consider this patch to test with, enable the "labels" plugin: ```patch diff --git a/electrum/plugins/labels/__init__.py b/electrum/plugins/labels/__init__.py index b68127df8e..0d6d95abce 100644 --- a/electrum/plugins/labels/__init__.py +++ b/electrum/plugins/labels/__init__.py @@ -21,3 +21,5 @@ async def pull(self: 'Commands', plugin: 'LabelsPlugin' = None, wallet=None, for arg:bool:force:pull all labels """ return await plugin.pull_thread(wallet, force=force) + +raise Exception("heyheyhey") ``` I would expect we don't load the labels plugin due to the error, but we do: ``` >>> plugins.get_plugin("labels") <electrum.plugins.labels.qt.Plugin object at 0x7801df30fb50> ``` Log: ``` $ ./run_electrum -v --testnet -o 0.75 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.75 | E | p/plugin.Plugins | cannot initialize plugin labels: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 148, in exec_module_from_spec spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/user/wspace/electrum/electrum/plugins/labels/__init__.py", line 25, in <module> raise Exception("heyheyhey") Exception: heyheyhey The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/wspace/electrum/electrum/plugin.py", line 167, in load_plugins self.maybe_load_plugin_init_method(name) File "/home/user/wspace/electrum/electrum/plugin.py", line 293, in maybe_load_plugin_init_method module = self.exec_module_from_spec(init_spec, base_name) File "/home/user/wspace/electrum/electrum/plugin.py", line 150, in exec_module_from_spec raise Exception(f"Error pre-loading {path}: {repr(e)}") from e Exception: Error pre-loading electrum.plugins.labels: Exception('heyheyhey') 0.75 | D | util.profiler | Plugins.__init__ 0.0030 sec 0.84 | I | simple_config.SimpleConfig | electrum directory /home/user/.electrum/testnet 0.89 | I | __main__ | get_default_language: detected default as lang='en_UK' 0.89 | I | i18n | setting language to 'en_UK' 0.89 | I | logging | Electrum version: 4.5.8 - https://electrum.org - https://github.com/spesmilo/electrum 0.89 | I | logging | Python version: 3.10.12 (main, Feb 4 2025, 14:57:36) [GCC 11.4.0]. On platform: Linux-6.8.0-52-generic-x86_64-with-glibc2.35 0.89 | I | logging | Logging to file: /home/user/.electrum/testnet/logs/electrum_log_20250319T161247Z_6605.log 0.89 | I | logging | Log filters: verbosity '*', verbosity_shortcuts '' 0.89 | I | exchange_rate.FxThread | using exchange CoinGecko 0.90 | D | util.profiler | Daemon.__init__ 0.0047 sec 0.90 | I | daemon.Daemon | starting taskgroup. 0.90 | I | daemon.CommandsServer | now running and listening. socktype=unix, addr=/home/user/.electrum/testnet/daemon_rpc_socket 0.90 | I | p/plugin.Plugins | registering hardware bitbox02: ['hardware', 'bitbox02', 'BitBox02'] 0.90 | I | p/plugin.Plugins | registering hardware coldcard: ['hardware', 'coldcard', 'Coldcard Wallet'] 0.90 | I | p/plugin.Plugins | registering hardware digitalbitbox: ['hardware', 'digitalbitbox', 'Digital Bitbox wallet'] 0.90 | I | p/plugin.Plugins | could not find manifest.json of plugin hw_wallet, skipping... 0.90 | I | p/plugin.Plugins | registering hardware jade: ['hardware', 'jade', 'Jade wallet'] 0.90 | I | p/plugin.Plugins | registering hardware keepkey: ['hardware', 'keepkey', 'KeepKey wallet'] 0.90 | I | p/plugin.Plugins | registering hardware ledger: ['hardware', 'ledger', 'Ledger wallet'] 0.90 | I | p/plugin.Plugins | registering hardware safe_t: ['hardware', 'safe_t', 'Safe-T mini wallet'] 0.90 | I | p/plugin.Plugins | registering hardware trezor: ['hardware', 'trezor', 'Trezor wallet'] 0.90 | I | p/plugin.Plugins | registering wallet type ('2fa', 'trustedcoin') 1.01 | I | p/plugin.Plugins | loaded plugin 'labels'. (from thread: 'GUI') 1.01 | D | util.profiler | Plugins.__init__ 0.1183 sec ```
2025-03-19 16:27:23 +00:00
# We can't undo all side-effects, but we at least rm the module from sys.modules,
# so the import system knows it failed. If called again for the same plugin, we do not
# retry due to potential interactions with not-undone side-effects (e.g. plugin
# might have defined commands).
_exec_module_failure[path] = e
if path in sys.modules:
sys.modules.pop(path, None)
raise Exception(f"Error pre-loading {path}: {repr(e)}") from e
return module
2025-03-06 11:43:50 +01:00
def find_plugins(self):
internal_plugins_path = (self.pkgpath, False)
external_plugins_path = (self.get_external_plugin_dir(), True)
for pkg_path, external in (internal_plugins_path, external_plugins_path):
# external plugins enforce root permissions on the directory
if pkg_path and os.path.exists(pkg_path):
self.find_directory_plugins(pkg_path=pkg_path, external=external)
self.find_zip_plugins(pkg_path=pkg_path, external=external)
2025-03-06 11:43:50 +01:00
def load_plugins(self):
for name, d in chain(self.internal_plugin_metadata.items(), self.external_plugin_metadata.items()):
if not d.get('requires_wallet_type') and self.config.get('enable_plugin_' + name):
try:
if self.cmd_only: # only load init method to register commands
self.maybe_load_plugin_init_method(name)
else:
self.load_plugin_by_name(name)
except BaseException as e:
2019-04-26 18:52:26 +02:00
self.logger.exception(f"cannot initialize plugin {name}: {e}")
2015-05-23 10:38:19 +02:00
def _has_root_permissions(self, path):
return os.stat(path).st_uid == 0 and not os.access(path, os.W_OK)
@profiler(min_threshold=0.5)
def _has_recursive_root_permissions(self, path):
"""Check if a directory and all its subdirectories have root permissions"""
if _root_permission_cache.get(path) is not None:
return _root_permission_cache[path]
_root_permission_cache[path] = False
for root, dirs, files in os.walk(path):
if not self._has_root_permissions(root):
return False
for f in files:
if not self._has_root_permissions(os.path.join(root, f)):
return False
_root_permission_cache[path] = True
return True
def get_external_plugin_dir(self):
if sys.platform not in ['linux', 'darwin'] and not sys.platform.startswith('freebsd'):
return
pkg_path = '/opt/electrum_plugins'
if not os.path.exists(pkg_path):
2025-03-06 11:43:50 +01:00
self.logger.info(f'directory {pkg_path} does not exist')
return
if not self._has_root_permissions(pkg_path):
self.logger.info(f'not loading {pkg_path}: directory has user write permissions')
return
return pkg_path
def zip_plugin_path(self, name):
filename = self.get_metadata(name)['filename']
if name in self.internal_plugin_metadata:
pkg_path = self.pkgpath
else:
pkg_path = self.get_external_plugin_dir()
return os.path.join(pkg_path, filename)
2024-04-08 09:54:48 +02:00
def find_zip_plugins(self, pkg_path: str, external: bool):
"""Finds plugins in zip form in the given pkg_path and populates the metadata dicts"""
if pkg_path is None:
return
for filename in os.listdir(pkg_path):
path = os.path.join(pkg_path, filename)
if not filename.endswith('.zip'):
continue
if external and not self._has_root_permissions(path):
self.logger.info(f'not loading {path}: file has user write permissions')
continue
try:
zipfile = zipimport.zipimporter(path)
except zipimport.ZipImportError:
self.logger.exception(f"unable to load zip plugin '{filename}'")
continue
for name, b in pkgutil.iter_zipimport_modules(zipfile):
if b is False:
continue
if name in self.internal_plugin_metadata:
raise Exception(f"duplicate plugins for name={name}")
if name in self.external_plugin_metadata:
raise Exception(f"duplicate plugins for name={name}")
if self.cmd_only and not self.config.get('enable_plugin_' + name):
continue
try:
with zipfile_lib.ZipFile(path) as file:
manifest_path = os.path.join(name, 'manifest.json')
with file.open(manifest_path, 'r') as f:
d = json.load(f)
except Exception:
self.logger.info(f"could not load manifest.json from zip plugin {filename}", exc_info=True)
continue
d['filename'] = filename
d['is_zip'] = True
d['path'] = path
if not self.cmd_only:
gui_good = self.gui_name in d.get('available_for', [])
if not gui_good:
continue
if 'fullname' not in d:
continue
d['display_name'] = d['fullname']
d['zip_hash_sha256'] = get_file_hash256(path)
if external:
self.external_plugin_metadata[name] = d
else:
self.internal_plugin_metadata[name] = d
def get(self, name):
return self.plugins.get(name)
def count(self):
return len(self.plugins)
def load_plugin(self, name) -> 'BasePlugin':
"""Imports the code of the given plugin.
note: can be called from any thread.
"""
if self.get_metadata(name):
return self.load_plugin_by_name(name)
else:
raise Exception(f"could not find plugin {name!r}")
def maybe_load_plugin_init_method(self, name: str) -> None:
"""Loads the __init__.py module of the plugin if it is not already loaded."""
is_external = name in self.external_plugin_metadata
base_name = (f'electrum_external_plugins.' if is_external else 'electrum.plugins.') + name
if base_name not in sys.modules:
metadata = self.get_metadata(name)
is_zip = metadata.get('is_zip', False)
# if the plugin was not enabled on startup the init module hasn't been loaded yet
if not is_zip:
if is_external:
path = os.path.join(metadata['path'], '__init__.py')
init_spec = importlib.util.spec_from_file_location(base_name, path)
else:
init_spec = importlib.util.find_spec(base_name)
else:
zipfile = zipimport.zipimporter(metadata['path'])
init_spec = zipfile.find_spec(name)
self.exec_module_from_spec(init_spec, base_name)
if name == "trustedcoin":
# removes trustedcoin after loading to not show it in the list of plugins
del self.internal_plugin_metadata[name]
def load_plugin_by_name(self, name: str) -> 'BasePlugin':
if name in self.plugins:
2017-10-22 23:47:11 +02:00
return self.plugins[name]
# if the plugin was not enabled on startup the init module hasn't been loaded yet
self.maybe_load_plugin_init_method(name)
is_external = name in self.external_plugin_metadata
if not is_external:
full_name = f'electrum.plugins.{name}.{self.gui_name}'
else:
full_name = f'electrum_external_plugins.{name}.{self.gui_name}'
spec = importlib.util.find_spec(full_name)
if spec is None:
2024-06-19 11:24:13 +02:00
raise RuntimeError(f"{self.gui_name} implementation for {name} plugin not found")
try:
module = self.exec_module_from_spec(spec, full_name)
plugin = module.Plugin(self, self.config, name)
except Exception as e:
raise Exception(f"Error loading {name} plugin: {repr(e)}") from e
self.add_jobs(plugin.thread_jobs())
self.plugins[name] = plugin
self.logger.info(f"loaded plugin {name!r}. (from thread: {threading.current_thread().name!r})")
return plugin
def close_plugin(self, plugin):
self.remove_jobs(plugin.thread_jobs())
def enable(self, name: str) -> 'BasePlugin':
self.config.set_key('enable_plugin_' + name, True, save=True)
p = self.get(name)
if p:
2016-01-19 10:03:05 +01:00
return p
return self.load_plugin(name)
def disable(self, name: str) -> None:
self.config.set_key('enable_plugin_' + name, False, save=True)
2016-01-19 10:03:05 +01:00
p = self.get(name)
if not p:
return
self.plugins.pop(name)
p.close()
2019-04-26 18:52:26 +02:00
self.logger.info(f"closed {name}")
2016-01-19 10:03:05 +01:00
@classmethod
def is_plugin_enabler_config_key(cls, key: str) -> bool:
return key.startswith('enable_plugin_')
def toggle(self, name: str) -> Optional['BasePlugin']:
2016-01-19 10:03:05 +01:00
p = self.get(name)
return self.disable(name) if p else self.enable(name)
def is_available(self, name: str, wallet: 'Abstract_Wallet') -> bool:
2016-01-21 12:12:55 +01:00
d = self.descriptions.get(name)
if not d:
return False
deps = d.get('requires', [])
for dep, s in deps:
try:
__import__(dep)
except ImportError as e:
2019-04-26 18:52:26 +02:00
self.logger.warning(f'Plugin {name} unavailable: {repr(e)}')
return False
requires = d.get('requires_wallet_type', [])
return not requires or wallet.wallet_type in requires
2016-08-23 13:40:11 +02:00
def get_hardware_support(self):
out = []
for name, (gui_good, details) in self.hw_wallets.items():
if gui_good:
try:
2016-08-20 14:55:57 +02:00
p = self.get_plugin(name)
if p.is_available():
out.append(HardwarePluginToScan(name=name,
description=details[2],
plugin=p,
exception=None))
except Exception as e:
2019-04-26 18:52:26 +02:00
self.logger.exception(f"cannot load plugin for: {name}")
out.append(HardwarePluginToScan(name=name,
description=details[2],
plugin=None,
exception=e))
2016-08-23 13:40:11 +02:00
return out
2016-08-19 17:26:57 +02:00
def register_wallet_type(self, name, gui_good, wallet_type):
2017-01-22 21:25:24 +03:00
from .wallet import register_wallet_type, register_constructor
2019-04-26 18:52:26 +02:00
self.logger.info(f"registering wallet type {(wallet_type, name)}")
2024-06-19 11:24:13 +02:00
def loader():
2016-08-20 14:55:57 +02:00
plugin = self.get_plugin(name)
2016-08-19 17:26:57 +02:00
register_constructor(wallet_type, plugin.wallet_class)
register_wallet_type(wallet_type)
plugin_loaders[wallet_type] = loader
def register_keystore(self, name, gui_good, details):
2017-01-22 21:25:24 +03:00
from .keystore import register_keystore
2024-06-19 11:24:13 +02:00
def dynamic_constructor(d):
return self.get_plugin(name).keystore_class(d)
if details[0] == 'hardware':
self.hw_wallets[name] = (gui_good, details)
2019-04-26 18:52:26 +02:00
self.logger.info(f"registering hardware {name}: {details}")
register_keystore(details[1], dynamic_constructor)
2013-09-23 16:14:28 +02:00
def get_plugin(self, name: str) -> 'BasePlugin':
if name not in self.plugins:
2016-01-19 10:03:05 +01:00
self.load_plugin(name)
return self.plugins[name]
def is_plugin_zip(self, name: str) -> bool:
"""Returns True if the plugin is a zip file"""
if (metadata := self.get_metadata(name)) is None:
return False
return metadata.get('is_zip', False)
def get_metadata(self, name: str) -> Optional[dict]:
"""Returns the metadata of the plugin"""
metadata = self.internal_plugin_metadata.get(name) or self.external_plugin_metadata.get(name)
if not metadata:
return None
return metadata
2015-12-03 11:18:10 +01:00
def run(self):
while self.is_running():
self.wake_up_event.wait(0.1) # time.sleep(0.1) OR event
2015-12-03 11:18:10 +01:00
self.run_jobs()
2016-06-04 12:58:29 +02:00
self.on_stop()
2015-05-24 20:37:05 +02:00
2025-03-06 11:43:50 +01:00
def get_file_hash256(path: str) -> str:
'''Get the sha256 hash of a file in hex, similar to `sha256sum`.'''
with open(path, 'rb') as f:
return sha256(f.read()).hex()
def hook(func):
2017-02-05 13:38:44 +03:00
hook_names.add(func.__name__)
return func
2023-07-11 12:51:37 +02:00
2014-08-31 11:42:40 +02:00
def run_hook(name, *args):
results = []
f_list = hooks.get(name, [])
2014-08-31 11:42:40 +02:00
for p, f in f_list:
2016-01-01 19:15:01 +09:00
if p.is_enabled():
try:
r = f(*args)
except Exception:
2019-04-26 18:52:26 +02:00
_logger.exception(f"Plugin error. plugin: {p}, hook: {name}")
r = False
if r:
results.append(r)
if results:
assert len(results) == 1, results
return results[0]
2013-09-23 16:14:28 +02:00
2013-03-15 09:58:05 +01:00
2019-04-26 18:52:26 +02:00
class BasePlugin(Logger):
2013-03-15 09:58:05 +01:00
def __init__(self, parent, config: 'SimpleConfig', name):
self.parent = parent # type: Plugins # The plugins object
self.name = name
self.config = config
2024-06-19 11:24:13 +02:00
self.wallet = None # fixme: this field should not exist
2019-04-26 18:52:26 +02:00
Logger.__init__(self)
2014-08-31 11:42:40 +02:00
# add self to hooks
for k in dir(self):
if k in hook_names:
l = hooks.get(k, [])
l.append((self, getattr(self, k)))
hooks[k] = l
2013-03-17 11:52:58 +01:00
def __str__(self):
return self.name
2015-05-23 10:38:19 +02:00
def close(self):
# remove self from hooks
for attr_name in dir(self):
if attr_name in hook_names:
# found attribute in self that is also the name of a hook
l = hooks.get(attr_name, [])
try:
l.remove((self, getattr(self, attr_name)))
except ValueError:
# maybe attr name just collided with hook name and was not hook
continue
hooks[attr_name] = l
self.parent.close_plugin(self)
2015-12-09 09:41:24 +01:00
self.on_close()
def on_close(self):
pass
def requires_settings(self) -> bool:
2013-03-17 11:52:58 +01:00
return False
def thread_jobs(self):
return []
2013-03-15 09:58:05 +01:00
def is_enabled(self):
2024-06-19 11:24:13 +02:00
return self.is_available() and self.config.get('enable_plugin_' + self.name) is True
2013-03-15 09:58:05 +01:00
def is_available(self):
return True
def can_user_disable(self):
return True
def settings_widget(self, window):
raise NotImplementedError()
def settings_dialog(self, window):
raise NotImplementedError()
def read_file(self, filename: str) -> bytes:
if self.parent.is_plugin_zip(self.name):
plugin_filename = self.parent.zip_plugin_path(self.name)
with zipfile_lib.ZipFile(plugin_filename) as myzip:
2024-10-17 13:01:41 +02:00
with myzip.open(os.path.join(self.name, filename)) as myfile:
return myfile.read()
else:
if self.name in self.parent.internal_plugin_metadata:
path = os.path.join(os.path.dirname(__file__), 'plugins', self.name, filename)
else:
path = os.path.join(self.parent.get_external_plugin_dir(), self.name, filename)
2024-10-17 13:01:41 +02:00
with open(path, 'rb') as myfile:
return myfile.read()
2024-06-19 11:24:13 +02:00
class DeviceUnpairableError(UserFacingException): pass
class HardwarePluginLibraryUnavailable(Exception): pass
class CannotAutoSelectDevice(Exception): pass
2018-10-28 00:28:29 +02:00
class Device(NamedTuple):
path: Union[str, bytes]
interface_number: int
id_: str
product_key: Any # when using hid, often Tuple[int, int]
usage_page: int
transport_ui_string: str
2018-10-28 00:28:29 +02:00
class DeviceInfo(NamedTuple):
device: Device
label: Optional[str] = None
initialized: Optional[bool] = None
exception: Optional[Exception] = None
plugin_name: Optional[str] = None # manufacturer, e.g. "trezor"
soft_device_id: Optional[str] = None # if available, used to distinguish same-type hw devices
model_name: Optional[str] = None # e.g. "Ledger Nano S"
2018-10-28 00:28:29 +02:00
class HardwarePluginToScan(NamedTuple):
name: str
description: str
plugin: Optional['HW_PluginBase']
exception: Optional[Exception]
PLACEHOLDER_HW_CLIENT_LABELS = {None, "", " "}
# hidapi is not thread-safe
# see https://github.com/signal11/hidapi/issues/205#issuecomment-527654560
# https://github.com/libusb/hidapi/issues/45
# https://github.com/signal11/hidapi/issues/45#issuecomment-4434598
# https://github.com/signal11/hidapi/pull/414#issuecomment-445164238
# It is not entirely clear to me, exactly what is safe and what isn't, when
# using multiple threads...
# Hence, we use a single thread for all device communications, including
# enumeration. Everything that uses hidapi, libusb, etc, MUST run on
# the following thread:
_hwd_comms_executor = concurrent.futures.ThreadPoolExecutor(
max_workers=1,
thread_name_prefix='hwd_comms_thread'
)
# hidapi needs to be imported from the main thread. Otherwise, at least on macOS,
# segfaults will follow. (see https://github.com/trezor/cython-hidapi/pull/150#issuecomment-1542391087)
# To keep it simple, let's just import it now, as we are likely in the main thread here.
if threading.current_thread() is not threading.main_thread():
_logger.warning("expected to be in main thread... hidapi will not be safe to use now!")
try:
import hid
except ImportError:
pass
T = TypeVar('T')
def run_in_hwd_thread(func: Callable[[], T]) -> T:
if threading.current_thread().name.startswith("hwd_comms_thread"):
return func()
else:
fut = _hwd_comms_executor.submit(func)
return fut.result()
#except (concurrent.futures.CancelledError, concurrent.futures.TimeoutError) as e:
def runs_in_hwd_thread(func):
@wraps(func)
def wrapper(*args, **kwargs):
return run_in_hwd_thread(partial(func, *args, **kwargs))
return wrapper
def assert_runs_in_hwd_thread():
if not threading.current_thread().name.startswith("hwd_comms_thread"):
raise Exception("must only be called from HWD communication thread")
2019-04-26 18:52:26 +02:00
class DeviceMgr(ThreadJob):
2024-06-19 11:24:13 +02:00
"""Manages hardware clients. A client communicates over a hardware
channel with the device.
In addition to tracking device HID IDs, the device manager tracks
hardware wallets and manages wallet pairing. A HID ID may be
paired with a wallet when it is confirmed that the hardware device
matches the wallet, i.e. they have the same master public key. A
HID ID can be unpaired if e.g. it is wiped.
Because of hotplugging, a wallet must request its client
dynamically each time it is required, rather than caching it
itself.
The device manager is shared across plugins, so just one place
does hardware scans when needed. By tracking HID IDs, if a device
is plugged into a different port the wallet is automatically
re-paired.
Wallets are informed on connect / disconnect events. It must
implement connected(), disconnected() callbacks. Being connected
implies a pairing. Callbacks can happen in any thread context,
and we do them without holding the lock.
Confusingly, the HID ID (serial number) reported by the HID system
doesn't match the device ID reported by the device itself. We use
the HID IDs.
This plugin is thread-safe. Currently only devices supported by
2024-06-19 11:24:13 +02:00
hidapi are implemented."""
2020-04-01 18:31:08 +02:00
def __init__(self, config: SimpleConfig):
2019-04-26 18:52:26 +02:00
ThreadJob.__init__(self)
# A pairing_code->id_ map. Item only present if we have active pairing. Needs self.lock.
self.pairing_code_to_id = {} # type: Dict[str, str]
# A client->id_ map. Needs self.lock.
self.clients = {} # type: Dict[HardwareClientBase, str]
# What we recognise. (vendor_id, product_id) -> Plugin
self._recognised_hardware = {} # type: Dict[Tuple[int, int], HW_PluginBase]
self._recognised_vendor = {} # type: Dict[int, HW_PluginBase] # vendor_id -> Plugin
# Custom enumerate functions for devices we don't know about.
self._enumerate_func = set() # Needs self.lock.
self.lock = threading.RLock()
2020-04-01 18:31:08 +02:00
self.config = config
def thread_jobs(self):
# Thread job to handle device timeouts
return [self]
def run(self):
'''Handle device timeouts. Runs in the context of the Plugins
thread.'''
with self.lock:
clients = list(self.clients.keys())
cutoff = time.time() - self.config.get_session_timeout()
for client in clients:
client.timeout(cutoff)
def register_devices(self, device_pairs, *, plugin: 'HW_PluginBase'):
for pair in device_pairs:
self._recognised_hardware[pair] = plugin
def register_vendor_ids(self, vendor_ids: Iterable[int], *, plugin: 'HW_PluginBase'):
for vendor_id in vendor_ids:
self._recognised_vendor[vendor_id] = plugin
def register_enumerate_func(self, func):
with self.lock:
self._enumerate_func.add(func)
@runs_in_hwd_thread
def create_client(self, device: 'Device', handler: Optional['HardwareHandlerBase'],
plugin: 'HW_PluginBase') -> Optional['HardwareClientBase']:
# Get from cache first
client = self._client_by_id(device.id_)
if client:
return client
2016-01-20 00:28:54 +09:00
client = plugin.create_client(device, handler)
if client:
2019-04-26 18:52:26 +02:00
self.logger.info(f"Registering {client}")
2016-01-20 00:28:54 +09:00
with self.lock:
self.clients[client] = device.id_
2016-01-20 00:28:54 +09:00
return client
def id_by_pairing_code(self, pairing_code):
with self.lock:
return self.pairing_code_to_id.get(pairing_code)
def pairing_code_by_id(self, id_):
with self.lock:
for pairing_code, id2 in self.pairing_code_to_id.items():
if id2 == id_:
return pairing_code
2016-01-20 00:28:54 +09:00
return None
def unpair_pairing_code(self, pairing_code):
2016-01-20 00:28:54 +09:00
with self.lock:
if pairing_code not in self.pairing_code_to_id:
return
_id = self.pairing_code_to_id.pop(pairing_code)
self._close_client(_id)
2016-01-20 00:28:54 +09:00
def unpair_id(self, id_):
pairing_code = self.pairing_code_by_id(id_)
if pairing_code:
self.unpair_pairing_code(pairing_code)
2018-02-04 21:59:58 +01:00
else:
self._close_client(id_)
def _close_client(self, id_):
with self.lock:
client = self._client_by_id(id_)
self.clients.pop(client, None)
2018-02-04 21:59:58 +01:00
if client:
client.close()
def _client_by_id(self, id_) -> Optional['HardwareClientBase']:
with self.lock:
for client, client_id in self.clients.items():
2016-01-20 00:28:54 +09:00
if client_id == id_:
return client
2016-01-20 00:28:54 +09:00
return None
def client_by_id(self, id_, *, scan_now: bool = True) -> Optional['HardwareClientBase']:
2016-01-20 00:28:54 +09:00
'''Returns a client for the device ID if one is registered. If
a device is wiped or in bootloader mode pairing is impossible;
in such cases we communicate by device ID and not wallet.'''
if scan_now:
self.scan_devices()
return self._client_by_id(id_)
@runs_in_hwd_thread
def client_for_keystore(self, plugin: 'HW_PluginBase', handler: Optional['HardwareHandlerBase'],
keystore: 'Hardware_KeyStore',
force_pair: bool, *,
devices: Sequence['Device'] = None,
allow_user_interaction: bool = True) -> Optional['HardwareClientBase']:
2019-04-26 18:52:26 +02:00
self.logger.info("getting client for keystore")
if handler is None:
2024-06-19 11:24:13 +02:00
raise Exception(_("Handler not found for {}").format(plugin.name) + '\n' + _("A library is probably missing."))
2016-08-27 14:56:31 +02:00
handler.update_status(False)
pcode = keystore.pairing_code()
client = None
# search existing clients first (fast-path)
if not devices:
client = self.client_by_pairing_code(plugin=plugin, pairing_code=pcode, handler=handler, devices=[])
# search clients again, now allowing a (slow) scan
if client is None:
if devices is None:
devices = self.scan_devices()
client = self.client_by_pairing_code(plugin=plugin, pairing_code=pcode, handler=handler, devices=devices)
2016-08-27 13:12:52 +02:00
if client is None and force_pair:
try:
info = self.select_device(plugin, handler, keystore, devices,
allow_user_interaction=allow_user_interaction)
except CannotAutoSelectDevice:
pass
else:
client = self.force_pair_keystore(plugin=plugin, handler=handler, info=info, keystore=keystore)
2016-08-27 13:12:52 +02:00
if client:
2016-08-27 14:56:31 +02:00
handler.update_status(True)
# note: if select_device was called, we might also update label etc here:
keystore.opportunistically_fill_in_missing_info_from_device(client)
2019-04-26 18:52:26 +02:00
self.logger.info("end client for keystore")
2016-08-27 13:12:52 +02:00
return client
def client_by_pairing_code(
self, *, plugin: 'HW_PluginBase', pairing_code: str, handler: 'HardwareHandlerBase',
devices: Sequence['Device'],
) -> Optional['HardwareClientBase']:
_id = self.id_by_pairing_code(pairing_code)
client = self._client_by_id(_id)
2016-01-20 00:28:54 +09:00
if client:
if type(client.plugin) != type(plugin):
return
# An unpaired client might have another wallet's handler
# from a prior scan. Replace to fix dialog parenting.
2016-08-20 14:55:57 +02:00
client.handler = handler
2016-01-20 00:28:54 +09:00
return client
for device in devices:
2016-08-20 14:55:57 +02:00
if device.id_ == _id:
return self.create_client(device, handler, plugin)
2016-01-20 00:28:54 +09:00
def force_pair_keystore(
self,
*,
plugin: 'HW_PluginBase',
handler: 'HardwareHandlerBase',
info: 'DeviceInfo',
keystore: 'Hardware_KeyStore',
) -> 'HardwareClientBase':
xpub = keystore.xpub
derivation = keystore.get_derivation_prefix()
assert derivation is not None
2018-10-25 22:20:33 +02:00
xtype = bip32.xpub_type(xpub)
client = self._client_by_id(info.device.id_)
if client and client.is_pairable() and type(client.plugin) == type(plugin):
# See comment above for same code
2016-08-20 14:55:57 +02:00
client.handler = handler
# This will trigger a PIN/passphrase entry request
try:
client_xpub = client.get_xpub(derivation, xtype)
except (UserCancelled, RuntimeError):
2024-06-19 11:24:13 +02:00
# Bad / cancelled PIN / passphrase
client_xpub = None
if client_xpub == xpub:
keystore.opportunistically_fill_in_missing_info_from_device(client)
with self.lock:
self.pairing_code_to_id[keystore.pairing_code()] = info.device.id_
return client
# The user input has wrong PIN or passphrase, or cancelled input,
# or it is not pairable
raise DeviceUnpairableError(
_('Electrum cannot pair with your {}.\n\n'
'Before you request bitcoins to be sent to addresses in this '
'wallet, ensure you can pair with your device, or that you have '
'its seed (and passphrase, if any). Otherwise all bitcoins you '
'receive will be unspendable.').format(plugin.device))
def list_pairable_device_infos(
self,
*,
handler: Optional['HardwareHandlerBase'],
plugin: 'HW_PluginBase',
devices: Sequence['Device'] = None,
include_failing_clients: bool = False,
) -> List['DeviceInfo']:
"""Returns a list of DeviceInfo objects: one for each connected device accepted by the plugin.
Already paired devices are also included, as it is okay to reuse them.
"""
if not plugin.libraries_available:
message = plugin.get_library_not_available_message()
raise HardwarePluginLibraryUnavailable(message)
if devices is None:
devices = self.scan_devices()
infos = []
for device in devices:
if not plugin.can_recognize_device(device):
continue
trezor: don't let bridge transport failing block all other transports [trezor] connecting to device at bridge:hid... [trezor] connected to device at bridge:hid... Traceback (most recent call last): File "...\electrum\electrum\base_wizard.py", line 255, in choose_hw_device u = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices) File "...\electrum\electrum\plugin.py", line 501, in unpaired_device_infos client = self.create_client(device, handler, plugin) File "...\electrum\electrum\plugin.py", line 374, in create_client client = plugin.create_client(device, handler) File "...\electrum\electrum\plugins\trezor\trezor.py", line 124, in create_client client = self.client_class(transport, handler, self) File "...\electrum\electrum\plugins\trezor\client.py", line 7, in __init__ ProtocolMixin.__init__(self, transport=transport) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 444, in __init__ self.init_device() File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 454, in init_device self.features = expect(proto.Features)(self.call)(init_msg) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 115, in wrapped_f ret = f(*args, **kwargs) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 129, in wrapped_f client.transport.session_begin() File "...\Python36-32\lib\site-packages\trezorlib\transport\__init__.py", line 42, in session_begin self.open() File "...\Python36-32\lib\site-packages\trezorlib\transport\bridge.py", line 69, in open raise TransportException('trezord: Could not acquire session' + get_error(r)) trezorlib.transport.TransportException: trezord: Could not acquire session (error=400 str=wrong previous session) [DeviceMgr] error getting device infos for trezor: trezord: Could not acquire session (error=400 str=wrong previous session)
2018-11-08 17:07:05 +01:00
try:
client = self.create_client(device, handler, plugin)
if not client:
continue
ledger: suppress traceback during device enumeration for locked device ledger now gives an error if querying xpub while device is not (unlocked and in bitcoin app). we do query the xpub however, to calc root fingerprint to be used as soft device id. trace: I | plugin.DeviceMgr | scanning devices... D | util.profiler | DeviceMgr.scan_devices 3.4463 I | plugin.DeviceMgr | Registering <electrum.plugins.ledger.ledger.Ledger_Client object at 0x0000029DF6B08520> E | gui.qt.installwizard.InstallWizard | Traceback (most recent call last): File "...\electrum\electrum\plugins\ledger\ledger.py", line 225, in checkDevice self.perform_hw1_preflight() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 219, in perform_hw1_preflight raise e File "...\electrum\electrum\plugins\ledger\ledger.py", line 179, in perform_hw1_preflight firmwareInfo = self.dongleObject.getFirmwareVersion() File "...\Python38\site-packages\btchip\btchip.py", line 563, in getFirmwareVersion response = self.dongle.exchange(bytearray(apdu)) File "...\Python38\site-packages\btchip\btchipComm.py", line 127, in exchange raise BTChipException("Invalid status %04x" % sw, sw) btchip.btchipException.BTChipException: Exception : Invalid status 6700 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "...\electrum\electrum\base_wizard.py", line 317, in _choose_hw_device device_infos = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices, File "...\electrum\electrum\plugin.py", line 612, in unpaired_device_infos soft_device_id=client.get_soft_device_id(), File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 355, in run_in_hwd_thread return fut.result() File "...\Python38\lib\concurrent\futures\_base.py", line 439, in result return self.__get_result() File "...\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result raise self._exception File "...\Python38\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 91, in get_soft_device_id self._soft_device_id = self.request_root_fingerprint_from_device() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\hw_wallet\plugin.py", line 259, in request_root_fingerprint_from_device child_of_root_xpub = self.get_xpub("m/0'", xtype='standard') File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 57, in catch_exception return func(self, *args, **kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 111, in get_xpub self.checkDevice() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 228, in checkDevice raise UserFacingException(_("Device not in Bitcoin mode")) from e electrum.util.UserFacingException: Device not in Bitcoin mode W | gui.qt.installwizard.InstallWizard | error getting device infos for ledger: Device not in Bitcoin mode
2020-11-18 15:34:47 +01:00
label = client.label()
is_initialized = client.is_initialized()
soft_device_id = client.get_soft_device_id()
model_name = client.device_model_name()
except Exception as e:
2019-04-26 18:52:26 +02:00
self.logger.error(f'failed to create client for {plugin.name} at {device.path}: {repr(e)}')
if include_failing_clients:
infos.append(DeviceInfo(device=device, exception=e, plugin_name=plugin.name))
trezor: don't let bridge transport failing block all other transports [trezor] connecting to device at bridge:hid... [trezor] connected to device at bridge:hid... Traceback (most recent call last): File "...\electrum\electrum\base_wizard.py", line 255, in choose_hw_device u = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices) File "...\electrum\electrum\plugin.py", line 501, in unpaired_device_infos client = self.create_client(device, handler, plugin) File "...\electrum\electrum\plugin.py", line 374, in create_client client = plugin.create_client(device, handler) File "...\electrum\electrum\plugins\trezor\trezor.py", line 124, in create_client client = self.client_class(transport, handler, self) File "...\electrum\electrum\plugins\trezor\client.py", line 7, in __init__ ProtocolMixin.__init__(self, transport=transport) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 444, in __init__ self.init_device() File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 454, in init_device self.features = expect(proto.Features)(self.call)(init_msg) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 115, in wrapped_f ret = f(*args, **kwargs) File "...\Python36-32\lib\site-packages\trezorlib\client.py", line 129, in wrapped_f client.transport.session_begin() File "...\Python36-32\lib\site-packages\trezorlib\transport\__init__.py", line 42, in session_begin self.open() File "...\Python36-32\lib\site-packages\trezorlib\transport\bridge.py", line 69, in open raise TransportException('trezord: Could not acquire session' + get_error(r)) trezorlib.transport.TransportException: trezord: Could not acquire session (error=400 str=wrong previous session) [DeviceMgr] error getting device infos for trezor: trezord: Could not acquire session (error=400 str=wrong previous session)
2018-11-08 17:07:05 +01:00
continue
infos.append(DeviceInfo(device=device,
ledger: suppress traceback during device enumeration for locked device ledger now gives an error if querying xpub while device is not (unlocked and in bitcoin app). we do query the xpub however, to calc root fingerprint to be used as soft device id. trace: I | plugin.DeviceMgr | scanning devices... D | util.profiler | DeviceMgr.scan_devices 3.4463 I | plugin.DeviceMgr | Registering <electrum.plugins.ledger.ledger.Ledger_Client object at 0x0000029DF6B08520> E | gui.qt.installwizard.InstallWizard | Traceback (most recent call last): File "...\electrum\electrum\plugins\ledger\ledger.py", line 225, in checkDevice self.perform_hw1_preflight() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 219, in perform_hw1_preflight raise e File "...\electrum\electrum\plugins\ledger\ledger.py", line 179, in perform_hw1_preflight firmwareInfo = self.dongleObject.getFirmwareVersion() File "...\Python38\site-packages\btchip\btchip.py", line 563, in getFirmwareVersion response = self.dongle.exchange(bytearray(apdu)) File "...\Python38\site-packages\btchip\btchipComm.py", line 127, in exchange raise BTChipException("Invalid status %04x" % sw, sw) btchip.btchipException.BTChipException: Exception : Invalid status 6700 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "...\electrum\electrum\base_wizard.py", line 317, in _choose_hw_device device_infos = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices, File "...\electrum\electrum\plugin.py", line 612, in unpaired_device_infos soft_device_id=client.get_soft_device_id(), File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 355, in run_in_hwd_thread return fut.result() File "...\Python38\lib\concurrent\futures\_base.py", line 439, in result return self.__get_result() File "...\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result raise self._exception File "...\Python38\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 91, in get_soft_device_id self._soft_device_id = self.request_root_fingerprint_from_device() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\hw_wallet\plugin.py", line 259, in request_root_fingerprint_from_device child_of_root_xpub = self.get_xpub("m/0'", xtype='standard') File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 57, in catch_exception return func(self, *args, **kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 111, in get_xpub self.checkDevice() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 228, in checkDevice raise UserFacingException(_("Device not in Bitcoin mode")) from e electrum.util.UserFacingException: Device not in Bitcoin mode W | gui.qt.installwizard.InstallWizard | error getting device infos for ledger: Device not in Bitcoin mode
2020-11-18 15:34:47 +01:00
label=label,
initialized=is_initialized,
plugin_name=plugin.name,
ledger: suppress traceback during device enumeration for locked device ledger now gives an error if querying xpub while device is not (unlocked and in bitcoin app). we do query the xpub however, to calc root fingerprint to be used as soft device id. trace: I | plugin.DeviceMgr | scanning devices... D | util.profiler | DeviceMgr.scan_devices 3.4463 I | plugin.DeviceMgr | Registering <electrum.plugins.ledger.ledger.Ledger_Client object at 0x0000029DF6B08520> E | gui.qt.installwizard.InstallWizard | Traceback (most recent call last): File "...\electrum\electrum\plugins\ledger\ledger.py", line 225, in checkDevice self.perform_hw1_preflight() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 219, in perform_hw1_preflight raise e File "...\electrum\electrum\plugins\ledger\ledger.py", line 179, in perform_hw1_preflight firmwareInfo = self.dongleObject.getFirmwareVersion() File "...\Python38\site-packages\btchip\btchip.py", line 563, in getFirmwareVersion response = self.dongle.exchange(bytearray(apdu)) File "...\Python38\site-packages\btchip\btchipComm.py", line 127, in exchange raise BTChipException("Invalid status %04x" % sw, sw) btchip.btchipException.BTChipException: Exception : Invalid status 6700 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "...\electrum\electrum\base_wizard.py", line 317, in _choose_hw_device device_infos = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices, File "...\electrum\electrum\plugin.py", line 612, in unpaired_device_infos soft_device_id=client.get_soft_device_id(), File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 355, in run_in_hwd_thread return fut.result() File "...\Python38\lib\concurrent\futures\_base.py", line 439, in result return self.__get_result() File "...\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result raise self._exception File "...\Python38\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 91, in get_soft_device_id self._soft_device_id = self.request_root_fingerprint_from_device() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\hw_wallet\plugin.py", line 259, in request_root_fingerprint_from_device child_of_root_xpub = self.get_xpub("m/0'", xtype='standard') File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 57, in catch_exception return func(self, *args, **kwargs) File "...\electrum\electrum\plugins\ledger\ledger.py", line 111, in get_xpub self.checkDevice() File "...\electrum\electrum\plugin.py", line 362, in wrapper return run_in_hwd_thread(partial(func, *args, **kwargs)) File "...\electrum\electrum\plugin.py", line 352, in run_in_hwd_thread return func() File "...\electrum\electrum\plugins\ledger\ledger.py", line 228, in checkDevice raise UserFacingException(_("Device not in Bitcoin mode")) from e electrum.util.UserFacingException: Device not in Bitcoin mode W | gui.qt.installwizard.InstallWizard | error getting device infos for ledger: Device not in Bitcoin mode
2020-11-18 15:34:47 +01:00
soft_device_id=soft_device_id,
model_name=model_name))
return infos
def select_device(self, plugin: 'HW_PluginBase', handler: 'HardwareHandlerBase',
keystore: 'Hardware_KeyStore', devices: Sequence['Device'] = None,
*, allow_user_interaction: bool = True) -> 'DeviceInfo':
"""Select the device to use for keystore."""
# ideally this should not be called from the GUI thread...
# assert handler.get_gui_thread() != threading.current_thread(), 'must not be called from GUI thread'
while True:
infos = self.list_pairable_device_infos(handler=handler, plugin=plugin, devices=devices)
if infos:
break
if not allow_user_interaction:
raise CannotAutoSelectDevice()
2018-03-22 21:48:51 +01:00
msg = _('Please insert your {}').format(plugin.device)
msg += " ("
if keystore.label and keystore.label not in PLACEHOLDER_HW_CLIENT_LABELS:
msg += f"label: {keystore.label}, "
msg += f"bip32 root fingerprint: {keystore.get_root_fingerprint()!r}"
msg += ').\n\n{}\n\n{}'.format(
2018-03-22 21:48:51 +01:00
_('Verify the cable is connected and that '
'no other application is using it.'),
_('Try to connect again?')
)
2016-08-20 14:55:57 +02:00
if not handler.yes_no_question(msg):
raise UserCancelled()
devices = None
# select device automatically. (but only if we have reasonable expectation it is the correct one)
# method 1: select device by id
if keystore.soft_device_id:
for info in infos:
if info.soft_device_id == keystore.soft_device_id:
self.logger.debug(f"select_device. auto-selected(1) {plugin.device}: soft_device_id matched")
return info
# method 2: select device by label
# but only if not a placeholder label and only if there is no collision
device_labels = [info.label for info in infos]
if (keystore.label not in PLACEHOLDER_HW_CLIENT_LABELS
and device_labels.count(keystore.label) == 1):
for info in infos:
if info.label == keystore.label:
self.logger.debug(f"select_device. auto-selected(2) {plugin.device}: label recognised")
return info
# method 3: if there is only one device connected, and we don't have useful label/soft_device_id
# saved for keystore anyway, select it
if (len(infos) == 1
and keystore.label in PLACEHOLDER_HW_CLIENT_LABELS
and keystore.soft_device_id is None):
self.logger.debug(f"select_device. auto-selected(3) {plugin.device}: only one device")
return infos[0]
self.logger.debug(f"select_device. auto-select failed for {plugin.device}. {allow_user_interaction=}")
if not allow_user_interaction:
raise CannotAutoSelectDevice()
# ask user to select device manually
msg = (
_("Could not automatically pair with device for given keystore.") + "\n"
+ f"(keystore label: {keystore.label!r}, "
+ f"bip32 root fingerprint: {keystore.get_root_fingerprint()!r})\n\n")
msg += _("Please select which {} device to use:").format(plugin.device)
msg += "\n(" + _("Or click cancel to skip this keystore instead.") + ")"
descriptions = ["{label} ({maybe_model}{init}, {transport})"
.format(label=info.label or _("An unnamed {}").format(info.plugin_name),
init=(_("initialized") if info.initialized else _("wiped")),
transport=info.device.transport_ui_string,
maybe_model=f"{info.model_name}, " if info.model_name else "")
for info in infos]
self.logger.debug(f"select_device. prompting user for manual selection of {plugin.device}. "
f"num options: {len(infos)}. options: {infos}")
2016-08-26 12:26:43 +02:00
c = handler.query_choice(msg, descriptions)
if c is None:
raise UserCancelled()
info = infos[c]
self.logger.debug(f"select_device. user manually selected {plugin.device}. device info: {info}")
# note: updated label/soft_device_id will be saved after pairing succeeds
return info
@runs_in_hwd_thread
def _scan_devices_with_hid(self) -> List['Device']:
try:
import hid
except ImportError:
return []
2016-01-20 00:28:54 +09:00
devices = []
for d in hid.enumerate(0, 0):
vendor_id = d['vendor_id']
product_key = (vendor_id, d['product_id'])
plugin = None
if product_key in self._recognised_hardware:
plugin = self._recognised_hardware[product_key]
elif vendor_id in self._recognised_vendor:
plugin = self._recognised_vendor[vendor_id]
if plugin:
device = plugin.create_device_from_hid_enumeration(d, product_key=product_key)
if device:
devices.append(device)
return devices
@runs_in_hwd_thread
@profiler
def scan_devices(self) -> Sequence['Device']:
2019-04-26 18:52:26 +02:00
self.logger.info("scanning devices...")
# First see what's connected that we know about
devices = self._scan_devices_with_hid()
# Let plugin handlers enumerate devices we don't know about
with self.lock:
enumerate_funcs = list(self._enumerate_func)
for f in enumerate_funcs:
try:
new_devices = f()
except BaseException as e:
2024-06-19 11:24:13 +02:00
self.logger.error(f'custom device enum failed. func {str(f)}, error {e!r}')
else:
devices.extend(new_devices)
# find out what was disconnected
client_ids = [dev.id_ for dev in devices]
disconnected_clients = []
with self.lock:
2016-01-20 00:28:54 +09:00
connected = {}
for client, id_ in self.clients.items():
if id_ in client_ids and client.has_usable_connection_with_device():
connected[client] = id_
2016-01-20 00:28:54 +09:00
else:
disconnected_clients.append((client, id_))
2016-01-20 00:28:54 +09:00
self.clients = connected
# Unpair disconnected devices
for client, id_ in disconnected_clients:
2016-01-20 00:28:54 +09:00
self.unpair_id(id_)
if client.handler:
client.handler.update_status(False)
2016-01-20 00:28:54 +09:00
return devices
@classmethod
def version_info(cls) -> Mapping[str, Optional[str]]:
ret = {}
# add libusb
try:
import usb1
except Exception as e:
ret["libusb.version"] = None
else:
ret["libusb.version"] = ".".join(map(str, usb1.getVersion()[:4]))
try:
ret["libusb.path"] = usb1.libusb1.libusb._name
except AttributeError:
ret["libusb.path"] = None
# add hidapi
try:
import hid
ret["hidapi.version"] = hid.__version__ # available starting with 0.12.0.post2
except Exception as e:
from importlib.metadata import version
try:
ret["hidapi.version"] = version("hidapi")
except ImportError:
ret["hidapi.version"] = None
return ret
def trigger_pairings(
self,
keystores: Sequence['KeyStore'],
*,
allow_user_interaction: bool = True,
devices: Sequence['Device'] = None,
) -> None:
"""Given a list of keystores, try to pair each with a connected hardware device.
E.g. for a multisig-wallet, it is more user-friendly to use this method than to
try to pair each keystore individually. Consider the following scenario:
- three hw keystores in a 2-of-3 multisig wallet, devices d2 (for ks2) and d3 (for ks3) are connected
- assume none of the devices are paired yet
1. if we tried to individually pair keystores, we might try with ks1 first
- but ks1 cannot be paired automatically, as neither d2 nor d3 matches the stored fingerprint
- the user might then be prompted if they want to manually pair ks1 with either d2 or d3,
which is confusing and error-prone. It's especially problematic if the hw device does
not support labels (such as Ledger), as then the user cannot easily distinguish
same-type devices. (see #4199)
2. instead, if using this method, we would auto-pair ks2-d2 and ks3-d3 first,
and then tell the user ks1 could not be paired (and there are no devices left to try)
"""
from .keystore import Hardware_KeyStore
keystores = [ks for ks in keystores if isinstance(ks, Hardware_KeyStore)]
if not keystores:
return
if devices is None:
devices = self.scan_devices()
# first pair with all devices that can be auto-selected
for ks in keystores:
try:
ks.get_client(
force_pair=True,
allow_user_interaction=False,
devices=devices,
)
except UserCancelled:
pass
if allow_user_interaction:
# now do manual selections
for ks in keystores:
try:
ks.get_client(
force_pair=True,
allow_user_interaction=True,
devices=devices,
)
except UserCancelled:
pass