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
|
|
|
|
2015-05-23 10:38:19 +02:00
|
|
|
import os
|
|
|
|
|
import pkgutil
|
2018-11-11 23:55:34 +01:00
|
|
|
import importlib.util
|
2015-12-03 11:18:10 +01:00
|
|
|
import time
|
2017-01-22 21:25:24 +03:00
|
|
|
import threading
|
2023-11-29 12:13:34 +01:00
|
|
|
import traceback
|
2019-06-12 20:07:36 +02:00
|
|
|
import sys
|
2024-06-19 11:24:13 +02:00
|
|
|
import aiohttp
|
|
|
|
|
|
2019-11-11 17:04:12 +01: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)
|
2020-04-17 19:05:56 +02:00
|
|
|
import concurrent
|
2023-11-29 12:13:34 +01:00
|
|
|
import zipimport
|
2020-04-17 19:05:56 +02:00
|
|
|
from concurrent import futures
|
2020-09-08 15:52:53 +00:00
|
|
|
from functools import wraps, partial
|
2025-03-17 14:22:01 +01:00
|
|
|
from itertools import chain
|
2015-05-23 10:38:19 +02:00
|
|
|
|
2017-01-22 21:25:24 +03:00
|
|
|
from .i18n import _
|
2019-09-03 19:19:58 +02:00
|
|
|
from .util import (profiler, DaemonThread, UserCancelled, ThreadJob, UserFacingException)
|
2018-10-25 22:20:33 +02:00
|
|
|
from . import bip32
|
2018-07-11 17:38:47 +02:00
|
|
|
from . import plugins
|
2018-10-22 16:41:25 +02:00
|
|
|
from .simple_config import SimpleConfig
|
2019-04-26 18:52:26 +02:00
|
|
|
from .logging import get_logger, Logger
|
2025-01-09 18:05:37 +01:00
|
|
|
from .crypto import sha256
|
2018-10-22 16:41:25 +02:00
|
|
|
|
2018-10-31 17:58:47 +01:00
|
|
|
if TYPE_CHECKING:
|
2020-03-31 14:40:25 +02:00
|
|
|
from .plugins.hw_wallet import HW_PluginBase, HardwareClientBase, HardwareHandlerBase
|
2022-06-03 15:11:48 +02:00
|
|
|
from .keystore import Hardware_KeyStore, KeyStore
|
2020-05-26 00:54:22 +02:00
|
|
|
from .wallet import Abstract_Wallet
|
2018-10-31 17:58:47 +01:00
|
|
|
|
2016-02-08 22:32:49 +09:00
|
|
|
|
2019-04-26 18:52:26 +02:00
|
|
|
_logger = get_logger(__name__)
|
2016-07-02 08:58:56 +02:00
|
|
|
plugin_loaders = {}
|
|
|
|
|
hook_names = set()
|
|
|
|
|
hooks = {}
|
|
|
|
|
|
2013-09-23 16:14:28 +02:00
|
|
|
|
2015-12-03 11:18:10 +01:00
|
|
|
class Plugins(DaemonThread):
|
2015-09-03 12:02:03 +09:00
|
|
|
|
2019-05-07 21:07:18 +02:00
|
|
|
LOGGING_SHORTCUT = 'p'
|
2023-09-08 14:48:36 +00:00
|
|
|
pkgpath = os.path.dirname(plugins.__file__)
|
2019-05-07 21:07:18 +02:00
|
|
|
|
2015-09-03 12:02:03 +09:00
|
|
|
@profiler
|
2025-03-15 11:40:26 +01:00
|
|
|
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 = {}
|
|
|
|
|
self.loaded_command_modules = set() # type: set[str]
|
|
|
|
|
if cmd_only:
|
|
|
|
|
# only import the command modules of plugins
|
2025-03-15 11:40:26 +01:00
|
|
|
Logger.__init__(self)
|
2025-03-06 11:43:50 +01:00
|
|
|
self.find_plugins()
|
|
|
|
|
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)
|
2021-11-09 01:02:57 +01:00
|
|
|
self.name = 'Plugins' # set name of thread
|
2015-12-31 11:36:33 +09:00
|
|
|
self.hw_wallets = {}
|
2020-02-28 19:47:56 +01:00
|
|
|
self.plugins = {} # type: Dict[str, BasePlugin]
|
2015-11-23 14:15:25 +01:00
|
|
|
self.gui_name = gui_name
|
2025-03-06 11:43:50 +01:00
|
|
|
self.find_plugins()
|
2016-01-24 19:59:58 +09:00
|
|
|
self.load_plugins()
|
2016-02-10 21:51:22 +09:00
|
|
|
self.add_jobs(self.device_manager.thread_jobs())
|
2016-01-24 19:59:58 +09:00
|
|
|
self.start()
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2024-04-06 11:35:57 +02:00
|
|
|
@property
|
|
|
|
|
def descriptions(self):
|
2023-11-29 12:13:34 +01:00
|
|
|
return dict(list(self.internal_plugin_metadata.items()) + list(self.external_plugin_metadata.items()))
|
2023-09-08 14:48:36 +00:00
|
|
|
|
2025-03-17 14:22:01 +01: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]))
|
2024-04-06 11:35:57 +02:00
|
|
|
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:
|
2024-04-18 17:28:20 +00:00
|
|
|
if loader.__class__.__qualname__ == "PyiFrozenImporter":
|
2024-04-06 11:35:57 +02:00
|
|
|
continue
|
2025-03-15 11:40:26 +01:00
|
|
|
if self.cmd_only and self.config.get('enable_plugin_' + name) is not True:
|
|
|
|
|
continue
|
2025-03-17 14:22:01 +01:00
|
|
|
base_name = 'electrum.plugins' if not external else 'electrum_external_plugins'
|
2025-03-17 17:29:38 +01:00
|
|
|
full_name = f'{base_name}.{name}'
|
2025-03-17 14:22:01 +01:00
|
|
|
if external:
|
|
|
|
|
module_path = os.path.join(pkg_path, name)
|
|
|
|
|
if not self._has_recursive_root_permissions(module_path):
|
|
|
|
|
self.logger.info(f"Not loading plugin {module_path}: directory has user write permissions")
|
|
|
|
|
continue
|
2025-03-17 17:29:38 +01:00
|
|
|
module_path = os.path.join(module_path, '__init__.py')
|
2025-03-17 14:22:01 +01:00
|
|
|
if not os.path.exists(module_path):
|
|
|
|
|
continue
|
|
|
|
|
spec = importlib.util.spec_from_file_location(full_name, module_path)
|
|
|
|
|
else:
|
|
|
|
|
spec = importlib.util.find_spec(full_name)
|
2025-03-06 11:43:50 +01:00
|
|
|
if spec is None:
|
|
|
|
|
if self.cmd_only:
|
|
|
|
|
continue # no commands module in this plugin
|
2024-04-06 11:35:57 +02:00
|
|
|
raise Exception(f"Error pre-loading {full_name}: no spec")
|
2024-05-09 15:38:57 +02:00
|
|
|
module = self.exec_module_from_spec(spec, full_name)
|
2025-03-06 11:43:50 +01:00
|
|
|
if self.cmd_only:
|
2025-03-17 17:29:38 +01:00
|
|
|
assert name not in self.loaded_command_modules, f"tried to load commands of {name} twice"
|
2025-03-06 11:43:50 +01:00
|
|
|
self.loaded_command_modules.add(name)
|
|
|
|
|
continue
|
2024-04-06 11:35:57 +02:00
|
|
|
d = module.__dict__
|
|
|
|
|
if 'fullname' not in d:
|
|
|
|
|
continue
|
|
|
|
|
d['display_name'] = d['fullname']
|
2016-01-24 19:59:58 +09:00
|
|
|
gui_good = self.gui_name in d.get('available_for', [])
|
2016-06-25 19:32:43 +02:00
|
|
|
if not gui_good:
|
|
|
|
|
continue
|
2015-12-31 11:36:33 +09:00
|
|
|
details = d.get('registers_wallet_type')
|
|
|
|
|
if details:
|
2016-07-02 08:58:56 +02:00
|
|
|
self.register_wallet_type(name, gui_good, details)
|
|
|
|
|
details = d.get('registers_keystore')
|
|
|
|
|
if details:
|
|
|
|
|
self.register_keystore(name, gui_good, details)
|
2024-04-06 11:35:57 +02:00
|
|
|
if d.get('requires_wallet_type'):
|
|
|
|
|
# trustedcoin will not be added to list
|
|
|
|
|
continue
|
2025-03-17 14:22:01 +01:00
|
|
|
if name in self.internal_plugin_metadata or name in self.external_plugin_metadata:
|
2024-04-06 11:35:57 +02:00
|
|
|
_logger.info(f"Found the following plugin modules: {iter_modules=}")
|
|
|
|
|
raise Exception(f"duplicate plugins? for {name=}")
|
2025-03-17 14:22:01 +01:00
|
|
|
if not external:
|
|
|
|
|
self.internal_plugin_metadata[name] = d
|
|
|
|
|
else:
|
|
|
|
|
self.external_plugin_metadata[name] = d
|
2024-04-06 11:35:57 +02:00
|
|
|
|
2025-03-06 11:43:50 +01:00
|
|
|
@staticmethod
|
|
|
|
|
def exec_module_from_spec(spec, path):
|
2024-05-09 15:38:57 +02:00
|
|
|
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
|
2025-01-10 13:26:39 +00:00
|
|
|
spec.loader.exec_module(module)
|
2024-05-09 15:38:57 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
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):
|
2025-03-17 14:22:01 +01:00
|
|
|
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
|
|
|
|
2024-04-06 11:35:57 +02:00
|
|
|
def load_plugins(self):
|
2025-03-17 14:22:01 +01:00
|
|
|
for name, d in chain(self.internal_plugin_metadata.items(), self.external_plugin_metadata.items()):
|
2023-11-29 12:13:34 +01:00
|
|
|
if not d.get('requires_wallet_type') and self.config.get('enable_plugin_' + name):
|
2016-01-24 19:39:59 +09:00
|
|
|
try:
|
2025-03-17 14:22:01 +01:00
|
|
|
self.load_plugin_by_name(name)
|
2016-01-24 19:39:59 +09:00
|
|
|
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
|
|
|
|
2024-05-09 15:38:57 +02:00
|
|
|
def _has_root_permissions(self, path):
|
|
|
|
|
return os.stat(path).st_uid == 0 and not os.access(path, os.W_OK)
|
2023-11-29 12:13:34 +01:00
|
|
|
|
2025-03-17 14:22:01 +01:00
|
|
|
@profiler(min_threshold=0.5)
|
|
|
|
|
def _has_recursive_root_permissions(self, path):
|
|
|
|
|
"""Check if a directory and all its subdirectories have root permissions"""
|
|
|
|
|
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
|
|
|
|
|
return True
|
|
|
|
|
|
2023-11-29 12:13:34 +01:00
|
|
|
def get_external_plugin_dir(self):
|
2024-05-09 15:38:57 +02:00
|
|
|
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')
|
2024-05-09 15:38:57 +02:00
|
|
|
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
|
2023-11-29 12:13:34 +01:00
|
|
|
|
2025-03-17 14:22:01 +01:00
|
|
|
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
|
|
|
|
2025-03-17 14:22:01 +01: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"""
|
2024-05-09 15:38:57 +02:00
|
|
|
if pkg_path is None:
|
|
|
|
|
return
|
|
|
|
|
for filename in os.listdir(pkg_path):
|
|
|
|
|
path = os.path.join(pkg_path, filename)
|
2025-03-17 14:22:01 +01:00
|
|
|
if not filename.endswith('.zip'):
|
|
|
|
|
continue
|
|
|
|
|
if external and not self._has_root_permissions(path):
|
2024-05-09 15:38:57 +02:00
|
|
|
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}")
|
2025-03-17 17:29:38 +01:00
|
|
|
if self.cmd_only and not self.config.get('enable_plugin_' + name):
|
|
|
|
|
continue
|
2025-03-17 14:22:01 +01:00
|
|
|
module_path = f'electrum_external_plugins.{name}' if external else f'electrum.plugins.{name}'
|
2025-01-10 13:26:39 +00:00
|
|
|
spec = zipfile.find_spec(name)
|
|
|
|
|
module = self.exec_module_from_spec(spec, module_path)
|
2025-03-06 11:43:50 +01:00
|
|
|
if self.cmd_only:
|
2025-03-17 17:29:38 +01:00
|
|
|
assert name not in self.loaded_command_modules, f"tried to load commands of {name} twice"
|
2025-03-06 11:43:50 +01:00
|
|
|
self.loaded_command_modules.add(name)
|
|
|
|
|
continue
|
2024-05-09 15:38:57 +02:00
|
|
|
d = module.__dict__
|
|
|
|
|
gui_good = self.gui_name in d.get('available_for', [])
|
|
|
|
|
if not gui_good:
|
|
|
|
|
continue
|
|
|
|
|
d['filename'] = filename
|
|
|
|
|
if 'fullname' not in d:
|
|
|
|
|
continue
|
|
|
|
|
d['display_name'] = d['fullname']
|
2025-01-09 18:05:37 +01:00
|
|
|
d['zip_hash_sha256'] = get_file_hash256(path)
|
2025-03-17 14:22:01 +01:00
|
|
|
d['is_zip'] = True
|
|
|
|
|
if external:
|
|
|
|
|
self.external_plugin_metadata[name] = d
|
|
|
|
|
else:
|
|
|
|
|
self.internal_plugin_metadata[name] = d
|
2023-11-29 12:13:34 +01:00
|
|
|
|
2015-09-03 12:02:03 +09:00
|
|
|
def get(self, name):
|
|
|
|
|
return self.plugins.get(name)
|
|
|
|
|
|
|
|
|
|
def count(self):
|
|
|
|
|
return len(self.plugins)
|
|
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def load_plugin(self, name) -> 'BasePlugin':
|
2023-12-17 06:07:37 +00:00
|
|
|
"""Imports the code of the given plugin.
|
|
|
|
|
note: can be called from any thread.
|
|
|
|
|
"""
|
2025-03-17 14:22:01 +01:00
|
|
|
if self.get_metadata(name):
|
|
|
|
|
return self.load_plugin_by_name(name)
|
2023-11-29 12:13:34 +01:00
|
|
|
else:
|
2024-04-18 16:53:48 +00:00
|
|
|
raise Exception(f"could not find plugin {name!r}")
|
2023-11-29 12:13:34 +01:00
|
|
|
|
2025-03-17 14:22:01 +01:00
|
|
|
def load_plugin_by_name(self, name) -> 'BasePlugin':
|
2016-07-02 08:58:56 +02:00
|
|
|
if name in self.plugins:
|
2017-10-22 23:47:11 +02:00
|
|
|
return self.plugins[name]
|
2025-03-17 14:22:01 +01:00
|
|
|
|
|
|
|
|
is_zip = self.is_plugin_zip(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}'
|
|
|
|
|
|
2018-11-11 23:55:34 +01:00
|
|
|
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")
|
2018-10-31 18:33:28 +01:00
|
|
|
try:
|
2025-03-17 14:22:01 +01:00
|
|
|
if is_zip:
|
|
|
|
|
module = self.exec_module_from_spec(spec, full_name)
|
|
|
|
|
else:
|
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
spec.loader.exec_module(module)
|
2018-11-11 23:55:34 +01:00
|
|
|
plugin = module.Plugin(self, self.config, name)
|
2018-10-31 18:33:28 +01:00
|
|
|
except Exception as e:
|
2018-11-11 23:55:34 +01:00
|
|
|
raise Exception(f"Error loading {name} plugin: {repr(e)}") from e
|
2016-01-24 19:39:59 +09:00
|
|
|
self.add_jobs(plugin.thread_jobs())
|
|
|
|
|
self.plugins[name] = plugin
|
2023-12-17 06:07:37 +00:00
|
|
|
self.logger.info(f"loaded plugin {name!r}. (from thread: {threading.current_thread().name!r})")
|
2016-01-24 19:39:59 +09:00
|
|
|
return plugin
|
2015-09-03 12:02:03 +09:00
|
|
|
|
2015-09-06 19:35:14 +09:00
|
|
|
def close_plugin(self, plugin):
|
2015-12-10 09:52:00 +01:00
|
|
|
self.remove_jobs(plugin.thread_jobs())
|
2015-09-06 19:35:14 +09:00
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def enable(self, name: str) -> 'BasePlugin':
|
2024-04-06 11:35:57 +02:00
|
|
|
self.config.set_key('enable_plugin_' + name, True, save=True)
|
2015-09-03 12:02:03 +09:00
|
|
|
p = self.get(name)
|
|
|
|
|
if p:
|
2016-01-19 10:03:05 +01:00
|
|
|
return p
|
|
|
|
|
return self.load_plugin(name)
|
|
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def disable(self, name: str) -> None:
|
2024-04-06 11:35:57 +02:00
|
|
|
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
|
|
|
|
2023-09-08 14:55:22 +00:00
|
|
|
@classmethod
|
|
|
|
|
def is_plugin_enabler_config_key(cls, key: str) -> bool:
|
2024-04-06 11:35:57 +02:00
|
|
|
return key.startswith('enable_plugin_')
|
2023-09-08 14:55:22 +00:00
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
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)
|
2015-09-03 12:02:03 +09:00
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
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:
|
2015-09-03 12:02:03 +09:00
|
|
|
return False
|
|
|
|
|
deps = d.get('requires', [])
|
|
|
|
|
for dep, s in deps:
|
|
|
|
|
try:
|
|
|
|
|
__import__(dep)
|
2018-07-13 15:24:16 +02:00
|
|
|
except ImportError as e:
|
2019-04-26 18:52:26 +02:00
|
|
|
self.logger.warning(f'Plugin {name} unavailable: {repr(e)}')
|
2015-09-03 12:02:03 +09:00
|
|
|
return False
|
2016-01-01 19:22:34 +09:00
|
|
|
requires = d.get('requires_wallet_type', [])
|
2020-05-26 00:54:22 +02:00
|
|
|
return not requires or wallet.wallet_type in requires
|
2015-09-03 12:02:03 +09:00
|
|
|
|
2016-08-23 13:40:11 +02:00
|
|
|
def get_hardware_support(self):
|
|
|
|
|
out = []
|
2015-12-31 11:36:33 +09:00
|
|
|
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)
|
2024-04-06 11:35:57 +02:00
|
|
|
if p.is_available():
|
2018-10-31 17:58:47 +01:00
|
|
|
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}")
|
2018-10-31 17:58:47 +01:00
|
|
|
out.append(HardwarePluginToScan(name=name,
|
|
|
|
|
description=details[2],
|
|
|
|
|
plugin=None,
|
|
|
|
|
exception=e))
|
2016-08-23 13:40:11 +02:00
|
|
|
return out
|
2015-12-31 11:36:33 +09:00
|
|
|
|
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
|
|
|
|
2016-07-02 08:58:56 +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
|
2016-07-02 08:58:56 +02:00
|
|
|
|
|
|
|
|
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
|
|
|
|
2016-08-21 11:58:15 +02:00
|
|
|
def dynamic_constructor(d):
|
|
|
|
|
return self.get_plugin(name).keystore_class(d)
|
2015-12-31 11:36:33 +09:00
|
|
|
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}")
|
2016-08-21 11:58:15 +02:00
|
|
|
register_keystore(details[1], dynamic_constructor)
|
2013-09-23 16:14:28 +02:00
|
|
|
|
2020-02-28 19:47:56 +01: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)
|
2015-12-31 11:36:33 +09:00
|
|
|
return self.plugins[name]
|
2015-09-04 09:12:11 +09:00
|
|
|
|
2025-03-17 14:22:01 +01:00
|
|
|
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():
|
2023-08-24 18:27:34 +00:00
|
|
|
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
|
|
|
|
2025-01-09 18:05:37 +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()
|
2015-09-05 21:47:35 +09:00
|
|
|
|
|
|
|
|
def hook(func):
|
2017-02-05 13:38:44 +03:00
|
|
|
hook_names.add(func.__name__)
|
2015-09-05 21:47:35 +09:00
|
|
|
return func
|
|
|
|
|
|
2023-07-11 12:51:37 +02:00
|
|
|
|
2014-08-31 11:42:40 +02:00
|
|
|
def run_hook(name, *args):
|
|
|
|
|
results = []
|
2015-04-18 14:59:46 +02:00
|
|
|
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():
|
2015-01-26 20:42:32 +01:00
|
|
|
try:
|
|
|
|
|
r = f(*args)
|
|
|
|
|
except Exception:
|
2019-04-26 18:52:26 +02:00
|
|
|
_logger.exception(f"Plugin error. plugin: {p}, hook: {name}")
|
2015-01-26 20:42:32 +01:00
|
|
|
r = False
|
|
|
|
|
if r:
|
|
|
|
|
results.append(r)
|
2014-07-01 18:46:11 +02:00
|
|
|
|
2014-07-10 17:27:54 +02:00
|
|
|
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
|
|
|
|
2020-12-20 13:26:35 +01:00
|
|
|
def __init__(self, parent, config: 'SimpleConfig', name):
|
2019-11-11 17:04:12 +01:00
|
|
|
self.parent = parent # type: Plugins # The plugins object
|
2013-08-05 17:15:01 +02:00
|
|
|
self.name = name
|
2014-08-31 15:33:20 +02:00
|
|
|
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
|
|
|
|
2016-01-11 14:23:35 +09:00
|
|
|
def __str__(self):
|
|
|
|
|
return self.name
|
|
|
|
|
|
2015-05-23 10:38:19 +02:00
|
|
|
def close(self):
|
|
|
|
|
# remove self from hooks
|
2018-12-19 02:10:47 +01:00
|
|
|
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
|
2015-09-06 19:35:14 +09:00
|
|
|
self.parent.close_plugin(self)
|
2015-12-09 09:41:24 +01:00
|
|
|
self.on_close()
|
|
|
|
|
|
|
|
|
|
def on_close(self):
|
|
|
|
|
pass
|
2013-08-05 17:15:01 +02:00
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def requires_settings(self) -> bool:
|
2013-03-17 11:52:58 +01:00
|
|
|
return False
|
2014-10-21 19:05:51 +02:00
|
|
|
|
2015-09-05 17:18:09 +09:00
|
|
|
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
|
|
|
|
|
|
2017-10-24 04:42:52 +02:00
|
|
|
def can_user_disable(self):
|
|
|
|
|
return True
|
|
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def settings_widget(self, window):
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
def settings_dialog(self, window):
|
|
|
|
|
raise NotImplementedError()
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2024-04-07 11:17:22 +02:00
|
|
|
def read_file(self, filename: str) -> bytes:
|
|
|
|
|
import zipfile
|
2025-03-17 14:22:01 +01:00
|
|
|
if self.parent.is_plugin_zip(self.name):
|
|
|
|
|
plugin_filename = self.parent.zip_plugin_path(self.name)
|
2024-10-17 13:01:41 +02:00
|
|
|
with zipfile.ZipFile(plugin_filename) as myzip:
|
|
|
|
|
with myzip.open(os.path.join(self.name, filename)) as myfile:
|
|
|
|
|
return myfile.read()
|
|
|
|
|
else:
|
2025-03-17 17:51:05 +00:00
|
|
|
if self.name in self.parent.internal_plugin_metadata:
|
2025-03-17 14:22:01 +01:00
|
|
|
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()
|
2016-01-31 19:36:21 +09:00
|
|
|
|
2024-06-19 11:24:13 +02:00
|
|
|
|
2019-09-03 19:19:58 +02:00
|
|
|
class DeviceUnpairableError(UserFacingException): pass
|
2019-05-26 17:01:01 +02:00
|
|
|
class HardwarePluginLibraryUnavailable(Exception): pass
|
2020-04-08 16:39:46 +02:00
|
|
|
class CannotAutoSelectDevice(Exception): pass
|
2016-01-31 19:36:21 +09:00
|
|
|
|
|
|
|
|
|
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
|
2018-11-16 19:03:25 +01:00
|
|
|
transport_ui_string: str
|
2018-10-28 00:28:29 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class DeviceInfo(NamedTuple):
|
|
|
|
|
device: Device
|
2019-01-21 18:44:36 +01:00
|
|
|
label: Optional[str] = None
|
|
|
|
|
initialized: Optional[bool] = None
|
|
|
|
|
exception: Optional[Exception] = None
|
2020-03-31 15:18:24 +02:00
|
|
|
plugin_name: Optional[str] = None # manufacturer, e.g. "trezor"
|
2020-04-08 14:43:01 +02:00
|
|
|
soft_device_id: Optional[str] = None # if available, used to distinguish same-type hw devices
|
2020-04-08 17:25:18 +02:00
|
|
|
model_name: Optional[str] = None # e.g. "Ledger Nano S"
|
2018-10-28 00:28:29 +02:00
|
|
|
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2018-10-31 17:58:47 +01:00
|
|
|
class HardwarePluginToScan(NamedTuple):
|
|
|
|
|
name: str
|
|
|
|
|
description: str
|
|
|
|
|
plugin: Optional['HW_PluginBase']
|
|
|
|
|
exception: Optional[Exception]
|
|
|
|
|
|
|
|
|
|
|
2019-11-18 18:13:26 +01:00
|
|
|
PLACEHOLDER_HW_CLIENT_LABELS = {None, "", " "}
|
2019-11-17 01:15:44 +01:00
|
|
|
|
|
|
|
|
|
2020-04-17 19:05:56 +02:00
|
|
|
# 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...
|
2020-09-08 15:52:53 +00:00
|
|
|
# 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'
|
|
|
|
|
)
|
|
|
|
|
|
2023-12-17 05:22:40 +00:00
|
|
|
# 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
|
|
|
|
|
|
2020-09-08 15:52:53 +00:00
|
|
|
|
|
|
|
|
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")
|
2020-04-17 19:05:56 +02:00
|
|
|
|
|
|
|
|
|
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
|
2016-01-09 14:18:06 +09:00
|
|
|
channel with the device.
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2016-01-09 14:18:06 +09:00
|
|
|
In addition to tracking device HID IDs, the device manager tracks
|
|
|
|
|
hardware wallets and manages wallet pairing. A HID ID may be
|
2016-01-05 06:47:14 +09:00
|
|
|
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
|
2016-01-09 14:18:06 +09:00
|
|
|
HID ID can be unpaired if e.g. it is wiped.
|
2016-01-05 06:47:14 +09:00
|
|
|
|
|
|
|
|
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
|
2016-01-09 14:18:06 +09:00
|
|
|
does hardware scans when needed. By tracking HID IDs, if a device
|
|
|
|
|
is plugged into a different port the wallet is automatically
|
|
|
|
|
re-paired.
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2016-01-06 23:08:02 +09:00
|
|
|
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.
|
|
|
|
|
|
2016-01-09 14:18:06 +09:00
|
|
|
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.
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2016-01-09 14:18:06 +09:00
|
|
|
This plugin is thread-safe. Currently only devices supported by
|
2024-06-19 11:24:13 +02:00
|
|
|
hidapi are implemented."""
|
2016-01-09 14:18:06 +09:00
|
|
|
|
2020-04-01 18:31:08 +02:00
|
|
|
def __init__(self, config: SimpleConfig):
|
2019-04-26 18:52:26 +02:00
|
|
|
ThreadJob.__init__(self)
|
2022-12-19 08:19:19 +00:00
|
|
|
# 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]
|
2022-12-12 11:33:13 +00:00
|
|
|
# A client->id_ map. Needs self.lock.
|
|
|
|
|
self.clients = {} # type: Dict[HardwareClientBase, str]
|
2020-04-06 18:20:21 +02:00
|
|
|
# What we recognise. (vendor_id, product_id) -> Plugin
|
|
|
|
|
self._recognised_hardware = {} # type: Dict[Tuple[int, int], HW_PluginBase]
|
2020-11-18 15:14:55 +01:00
|
|
|
self._recognised_vendor = {} # type: Dict[int, HW_PluginBase] # vendor_id -> Plugin
|
2018-02-06 19:11:14 +01:00
|
|
|
# Custom enumerate functions for devices we don't know about.
|
hww: fix threading issue in DeviceMgr: enumerate_func needs self.lock
E | gui.qt.main_window.[test_ms_p2wsh_2of3_cc3132_trezort_cc3133] | on_error
Traceback (most recent call last):
File "...\electrum\electrum\gui\qt\util.py", line 794, in run
result = task.task()
File "...\electrum\electrum\plugins\hw_wallet\qt.py", line 232, in trigger_pairings
devices = devmgr.scan_devices()
File "...\electrum\electrum\plugin.py", line 376, in func_wrapper
return func(self, *args, **kwargs)
File "...\electrum\electrum\plugin.py", line 656, in scan_devices
for f in self.enumerate_func:
RuntimeError: Set changed size during iteration
2020-04-08 18:46:28 +02:00
|
|
|
self._enumerate_func = set() # Needs self.lock.
|
2020-09-08 15:52:53 +00:00
|
|
|
|
2016-01-05 06:47:14 +09:00
|
|
|
self.lock = threading.RLock()
|
2020-04-01 18:31:08 +02:00
|
|
|
|
2016-02-10 21:51:22 +09: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)
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2020-04-06 18:20:21 +02:00
|
|
|
def register_devices(self, device_pairs, *, plugin: 'HW_PluginBase'):
|
2016-01-05 06:47:14 +09:00
|
|
|
for pair in device_pairs:
|
2020-04-06 18:20:21 +02:00
|
|
|
self._recognised_hardware[pair] = plugin
|
2016-01-09 14:18:06 +09:00
|
|
|
|
2020-11-18 15:14:55 +01:00
|
|
|
def register_vendor_ids(self, vendor_ids: Iterable[int], *, plugin: 'HW_PluginBase'):
|
|
|
|
|
for vendor_id in vendor_ids:
|
|
|
|
|
self._recognised_vendor[vendor_id] = plugin
|
|
|
|
|
|
2018-02-06 19:11:14 +01:00
|
|
|
def register_enumerate_func(self, func):
|
hww: fix threading issue in DeviceMgr: enumerate_func needs self.lock
E | gui.qt.main_window.[test_ms_p2wsh_2of3_cc3132_trezort_cc3133] | on_error
Traceback (most recent call last):
File "...\electrum\electrum\gui\qt\util.py", line 794, in run
result = task.task()
File "...\electrum\electrum\plugins\hw_wallet\qt.py", line 232, in trigger_pairings
devices = devmgr.scan_devices()
File "...\electrum\electrum\plugin.py", line 376, in func_wrapper
return func(self, *args, **kwargs)
File "...\electrum\electrum\plugin.py", line 656, in scan_devices
for f in self.enumerate_func:
RuntimeError: Set changed size during iteration
2020-04-08 18:46:28 +02:00
|
|
|
with self.lock:
|
|
|
|
|
self._enumerate_func.add(func)
|
2018-02-06 19:11:14 +01:00
|
|
|
|
2020-09-08 15:52:53 +00:00
|
|
|
@runs_in_hwd_thread
|
2020-03-31 14:40:25 +02:00
|
|
|
def create_client(self, device: 'Device', handler: Optional['HardwareHandlerBase'],
|
|
|
|
|
plugin: 'HW_PluginBase') -> Optional['HardwareClientBase']:
|
2016-01-21 23:33:15 +09:00
|
|
|
# Get from cache first
|
2020-04-09 18:00:35 +02:00
|
|
|
client = self._client_by_id(device.id_)
|
2016-01-21 23:33:15 +09:00
|
|
|
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:
|
2022-12-12 11:33:13 +00:00
|
|
|
self.clients[client] = device.id_
|
2016-01-20 00:28:54 +09:00
|
|
|
return client
|
|
|
|
|
|
2022-12-19 08:19:19 +00:00
|
|
|
def id_by_pairing_code(self, pairing_code):
|
2016-01-09 14:18:06 +09:00
|
|
|
with self.lock:
|
2022-12-19 08:19:19 +00:00
|
|
|
return self.pairing_code_to_id.get(pairing_code)
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2022-12-19 08:19:19 +00:00
|
|
|
def pairing_code_by_id(self, id_):
|
2016-01-05 06:47:14 +09:00
|
|
|
with self.lock:
|
2022-12-19 08:19:19 +00:00
|
|
|
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
|
|
|
|
|
|
2022-12-19 08:19:19 +00:00
|
|
|
def unpair_pairing_code(self, pairing_code):
|
2016-01-20 00:28:54 +09:00
|
|
|
with self.lock:
|
2022-12-19 08:19:19 +00:00
|
|
|
if pairing_code not in self.pairing_code_to_id:
|
2016-01-21 23:33:15 +09:00
|
|
|
return
|
2022-12-19 08:19:19 +00:00
|
|
|
_id = self.pairing_code_to_id.pop(pairing_code)
|
2020-09-08 15:52:53 +00:00
|
|
|
self._close_client(_id)
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2016-01-20 00:28:54 +09:00
|
|
|
def unpair_id(self, id_):
|
2022-12-19 08:19:19 +00:00
|
|
|
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_):
|
2020-09-08 15:52:53 +00:00
|
|
|
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()
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2020-04-09 18:00:35 +02:00
|
|
|
def _client_by_id(self, id_) -> Optional['HardwareClientBase']:
|
2016-01-05 06:47:14 +09:00
|
|
|
with self.lock:
|
2022-12-12 11:33:13 +00:00
|
|
|
for client, client_id in self.clients.items():
|
2016-01-20 00:28:54 +09:00
|
|
|
if client_id == id_:
|
2016-01-05 06:47:14 +09:00
|
|
|
return client
|
2016-01-20 00:28:54 +09:00
|
|
|
return None
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2020-04-09 18:00:35 +02:00
|
|
|
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.'''
|
2020-04-09 18:00:35 +02:00
|
|
|
if scan_now:
|
|
|
|
|
self.scan_devices()
|
|
|
|
|
return self._client_by_id(id_)
|
2016-01-09 14:18:06 +09:00
|
|
|
|
2020-09-08 15:52:53 +00:00
|
|
|
@runs_in_hwd_thread
|
2020-03-31 14:40:25 +02:00
|
|
|
def client_for_keystore(self, plugin: 'HW_PluginBase', handler: Optional['HardwareHandlerBase'],
|
|
|
|
|
keystore: 'Hardware_KeyStore',
|
2020-04-08 16:39:46 +02:00
|
|
|
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")
|
2017-11-05 12:49:38 +01:00
|
|
|
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)
|
2022-12-19 08:31:04 +00:00
|
|
|
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:
|
2020-04-08 16:39:46 +02:00
|
|
|
try:
|
|
|
|
|
info = self.select_device(plugin, handler, keystore, devices,
|
|
|
|
|
allow_user_interaction=allow_user_interaction)
|
|
|
|
|
except CannotAutoSelectDevice:
|
|
|
|
|
pass
|
|
|
|
|
else:
|
2022-12-19 08:19:19 +00:00
|
|
|
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)
|
2020-04-08 16:50:55 +02:00
|
|
|
# note: if select_device was called, we might also update label etc here:
|
2019-11-01 20:33:53 +01:00
|
|
|
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
|
2016-08-26 11:45:12 +02:00
|
|
|
|
2022-12-19 08:19:19 +00:00
|
|
|
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)
|
2020-04-09 18:00:35 +02:00
|
|
|
client = self._client_by_id(_id)
|
2016-01-20 00:28:54 +09:00
|
|
|
if client:
|
2022-03-03 13:24:28 +01:00
|
|
|
if type(client.plugin) != type(plugin):
|
|
|
|
|
return
|
2016-01-27 21:27:51 +09:00
|
|
|
# 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
|
|
|
|
2022-12-19 08:19:19 +00: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)
|
2020-04-09 18:00:35 +02:00
|
|
|
client = self._client_by_id(info.device.id_)
|
2022-03-03 13:24:28 +01:00
|
|
|
if client and client.is_pairable() and type(client.plugin) == type(plugin):
|
2016-02-06 19:51:39 +09:00
|
|
|
# See comment above for same code
|
2016-08-20 14:55:57 +02:00
|
|
|
client.handler = handler
|
2016-02-06 19:51:39 +09:00
|
|
|
# This will trigger a PIN/passphrase entry request
|
2016-02-07 17:16:29 +09:00
|
|
|
try:
|
2017-10-31 11:45:25 +01:00
|
|
|
client_xpub = client.get_xpub(derivation, xtype)
|
2016-02-07 17:16:29 +09:00
|
|
|
except (UserCancelled, RuntimeError):
|
2024-06-19 11:24:13 +02:00
|
|
|
# Bad / cancelled PIN / passphrase
|
2016-07-02 08:58:56 +02:00
|
|
|
client_xpub = None
|
|
|
|
|
if client_xpub == xpub:
|
2022-12-19 08:19:19 +00:00
|
|
|
keystore.opportunistically_fill_in_missing_info_from_device(client)
|
|
|
|
|
with self.lock:
|
|
|
|
|
self.pairing_code_to_id[keystore.pairing_code()] = info.device.id_
|
2016-02-06 19:51:39 +09:00
|
|
|
return client
|
2016-01-31 19:36:21 +09:00
|
|
|
|
2016-02-07 17:16:29 +09:00
|
|
|
# The user input has wrong PIN or passphrase, or cancelled input,
|
|
|
|
|
# or it is not pairable
|
2016-02-06 19:51:39 +09:00
|
|
|
raise DeviceUnpairableError(
|
2018-02-04 07:26:55 +01:00
|
|
|
_('Electrum cannot pair with your {}.\n\n'
|
2016-02-11 19:51:56 +09:00
|
|
|
'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 '
|
2018-02-04 07:26:55 +01:00
|
|
|
'receive will be unspendable.').format(plugin.device))
|
2016-01-31 19:36:21 +09:00
|
|
|
|
2022-12-19 13:08:27 +00:00
|
|
|
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.
|
|
|
|
|
"""
|
2018-04-03 14:21:22 +02:00
|
|
|
if not plugin.libraries_available:
|
2018-08-23 18:31:14 +02:00
|
|
|
message = plugin.get_library_not_available_message()
|
2019-05-26 17:01:01 +02:00
|
|
|
raise HardwarePluginLibraryUnavailable(message)
|
2016-01-24 13:01:04 +09:00
|
|
|
if devices is None:
|
2016-08-23 10:36:20 +02:00
|
|
|
devices = self.scan_devices()
|
2016-01-24 13:01:04 +09:00
|
|
|
infos = []
|
|
|
|
|
for device in devices:
|
2020-11-18 15:14:55 +01:00
|
|
|
if not plugin.can_recognize_device(device):
|
2016-01-24 13:01:04 +09:00
|
|
|
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)
|
2021-02-22 20:11:14 +01:00
|
|
|
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()
|
2019-01-21 18:44:36 +01:00
|
|
|
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)}')
|
2019-01-21 18:44:36 +01:00
|
|
|
if include_failing_clients:
|
2020-03-31 15:18:24 +02:00
|
|
|
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
|
2019-01-21 18:44:36 +01:00
|
|
|
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,
|
2020-04-08 14:43:01 +02:00
|
|
|
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))
|
2016-01-24 13:01:04 +09:00
|
|
|
|
|
|
|
|
return infos
|
|
|
|
|
|
2020-03-31 14:40:25 +02:00
|
|
|
def select_device(self, plugin: 'HW_PluginBase', handler: 'HardwareHandlerBase',
|
2020-04-08 16:39:46 +02:00
|
|
|
keystore: 'Hardware_KeyStore', devices: Sequence['Device'] = None,
|
|
|
|
|
*, allow_user_interaction: bool = True) -> 'DeviceInfo':
|
|
|
|
|
"""Select the device to use for keystore."""
|
2020-04-01 18:42:06 +02:00
|
|
|
# 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'
|
2016-02-06 19:51:39 +09:00
|
|
|
while True:
|
2022-12-19 13:08:27 +00:00
|
|
|
infos = self.list_pairable_device_infos(handler=handler, plugin=plugin, devices=devices)
|
2016-02-06 19:51:39 +09:00
|
|
|
if infos:
|
|
|
|
|
break
|
2020-04-08 16:39:46 +02:00
|
|
|
if not allow_user_interaction:
|
|
|
|
|
raise CannotAutoSelectDevice()
|
2018-03-22 21:48:51 +01:00
|
|
|
msg = _('Please insert your {}').format(plugin.device)
|
2022-06-03 18:02:58 +02:00
|
|
|
msg += " ("
|
2022-04-28 21:12:54 +02:00
|
|
|
if keystore.label and keystore.label not in PLACEHOLDER_HW_CLIENT_LABELS:
|
2022-06-03 18:02:58 +02:00
|
|
|
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):
|
2016-02-06 19:51:39 +09:00
|
|
|
raise UserCancelled()
|
|
|
|
|
devices = None
|
2020-04-08 16:39:46 +02:00
|
|
|
|
|
|
|
|
# select device automatically. (but only if we have reasonable expectation it is the correct one)
|
|
|
|
|
# method 1: select device by id
|
2020-04-08 14:43:01 +02:00
|
|
|
if keystore.soft_device_id:
|
|
|
|
|
for info in infos:
|
|
|
|
|
if info.soft_device_id == keystore.soft_device_id:
|
2022-03-11 15:49:30 +01:00
|
|
|
self.logger.debug(f"select_device. auto-selected(1) {plugin.device}: soft_device_id matched")
|
2020-04-08 14:43:01 +02:00
|
|
|
return info
|
2020-04-08 16:39:46 +02:00
|
|
|
# method 2: select device by label
|
|
|
|
|
# but only if not a placeholder label and only if there is no collision
|
2019-11-17 01:15:44 +01:00
|
|
|
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:
|
2022-03-11 15:49:30 +01:00
|
|
|
self.logger.debug(f"select_device. auto-selected(2) {plugin.device}: label recognised")
|
2019-11-17 01:15:44 +01:00
|
|
|
return info
|
2020-04-08 16:39:46 +02:00
|
|
|
# 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):
|
2022-03-11 15:49:30 +01:00
|
|
|
self.logger.debug(f"select_device. auto-selected(3) {plugin.device}: only one device")
|
2020-04-08 16:39:46 +02:00
|
|
|
return infos[0]
|
|
|
|
|
|
2022-03-11 15:49:30 +01:00
|
|
|
self.logger.debug(f"select_device. auto-select failed for {plugin.device}. {allow_user_interaction=}")
|
2020-04-08 16:39:46 +02:00
|
|
|
if not allow_user_interaction:
|
|
|
|
|
raise CannotAutoSelectDevice()
|
2020-04-08 14:43:01 +02:00
|
|
|
# ask user to select device manually
|
2022-06-03 16:18:16 +02:00
|
|
|
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")
|
2022-04-28 21:12:54 +02:00
|
|
|
msg += _("Please select which {} device to use:").format(plugin.device)
|
2022-06-03 16:18:16 +02:00
|
|
|
msg += "\n(" + _("Or click cancel to skip this keystore instead.") + ")"
|
2020-04-08 17:25:18 +02:00
|
|
|
descriptions = ["{label} ({maybe_model}{init}, {transport})"
|
2020-03-31 15:18:24 +02:00
|
|
|
.format(label=info.label or _("An unnamed {}").format(info.plugin_name),
|
2019-11-17 01:15:44 +01:00
|
|
|
init=(_("initialized") if info.initialized else _("wiped")),
|
2020-04-08 17:25:18 +02:00
|
|
|
transport=info.device.transport_ui_string,
|
|
|
|
|
maybe_model=f"{info.model_name}, " if info.model_name else "")
|
2019-11-17 01:15:44 +01:00
|
|
|
for info in infos]
|
2022-03-11 15:49:30 +01:00
|
|
|
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]
|
2022-03-11 15:49:30 +01:00
|
|
|
self.logger.debug(f"select_device. user manually selected {plugin.device}. device info: {info}")
|
2020-04-08 16:50:55 +02:00
|
|
|
# note: updated label/soft_device_id will be saved after pairing succeeds
|
2016-08-26 11:45:12 +02:00
|
|
|
return info
|
2016-01-24 13:01:04 +09:00
|
|
|
|
2020-09-08 15:52:53 +00:00
|
|
|
@runs_in_hwd_thread
|
2019-11-11 17:04:12 +01:00
|
|
|
def _scan_devices_with_hid(self) -> List['Device']:
|
2018-03-16 00:55:45 +01:00
|
|
|
try:
|
|
|
|
|
import hid
|
|
|
|
|
except ImportError:
|
|
|
|
|
return []
|
|
|
|
|
|
2016-01-20 00:28:54 +09:00
|
|
|
devices = []
|
2020-09-08 15:52:53 +00:00
|
|
|
for d in hid.enumerate(0, 0):
|
2020-11-18 15:14:55 +01:00
|
|
|
vendor_id = d['vendor_id']
|
|
|
|
|
product_key = (vendor_id, d['product_id'])
|
|
|
|
|
plugin = None
|
2020-04-06 18:20:21 +02:00
|
|
|
if product_key in self._recognised_hardware:
|
|
|
|
|
plugin = self._recognised_hardware[product_key]
|
2020-11-18 15:14:55 +01:00
|
|
|
elif vendor_id in self._recognised_vendor:
|
|
|
|
|
plugin = self._recognised_vendor[vendor_id]
|
|
|
|
|
if plugin:
|
2020-04-06 18:20:21 +02:00
|
|
|
device = plugin.create_device_from_hid_enumeration(d, product_key=product_key)
|
2020-11-18 15:14:55 +01:00
|
|
|
if device:
|
|
|
|
|
devices.append(device)
|
2018-03-16 00:55:45 +01:00
|
|
|
return devices
|
|
|
|
|
|
2020-09-08 15:52:53 +00:00
|
|
|
@runs_in_hwd_thread
|
2020-08-31 22:17:44 +02:00
|
|
|
@profiler
|
2020-04-08 16:39:46 +02:00
|
|
|
def scan_devices(self) -> Sequence['Device']:
|
2019-04-26 18:52:26 +02:00
|
|
|
self.logger.info("scanning devices...")
|
2018-03-16 00:55:45 +01:00
|
|
|
|
|
|
|
|
# First see what's connected that we know about
|
|
|
|
|
devices = self._scan_devices_with_hid()
|
2016-01-05 06:47:14 +09:00
|
|
|
|
2018-02-06 19:11:14 +01:00
|
|
|
# Let plugin handlers enumerate devices we don't know about
|
hww: fix threading issue in DeviceMgr: enumerate_func needs self.lock
E | gui.qt.main_window.[test_ms_p2wsh_2of3_cc3132_trezort_cc3133] | on_error
Traceback (most recent call last):
File "...\electrum\electrum\gui\qt\util.py", line 794, in run
result = task.task()
File "...\electrum\electrum\plugins\hw_wallet\qt.py", line 232, in trigger_pairings
devices = devmgr.scan_devices()
File "...\electrum\electrum\plugin.py", line 376, in func_wrapper
return func(self, *args, **kwargs)
File "...\electrum\electrum\plugin.py", line 656, in scan_devices
for f in self.enumerate_func:
RuntimeError: Set changed size during iteration
2020-04-08 18:46:28 +02:00
|
|
|
with self.lock:
|
|
|
|
|
enumerate_funcs = list(self._enumerate_func)
|
|
|
|
|
for f in enumerate_funcs:
|
2018-03-07 16:11:20 +01:00
|
|
|
try:
|
2020-09-08 15:52:53 +00:00
|
|
|
new_devices = f()
|
2018-03-07 16:11:20 +01:00
|
|
|
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}')
|
2018-03-07 16:11:20 +01:00
|
|
|
else:
|
|
|
|
|
devices.extend(new_devices)
|
2018-02-06 19:11:14 +01:00
|
|
|
|
2018-03-16 00:55:45 +01:00
|
|
|
# find out what was disconnected
|
2022-12-12 11:33:13 +00:00
|
|
|
client_ids = [dev.id_ for dev in devices]
|
2020-09-07 17:16:06 +02:00
|
|
|
disconnected_clients = []
|
2016-01-05 06:47:14 +09:00
|
|
|
with self.lock:
|
2016-01-20 00:28:54 +09:00
|
|
|
connected = {}
|
2022-12-12 11:33:13 +00:00
|
|
|
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:
|
2022-12-12 11:33:13 +00:00
|
|
|
disconnected_clients.append((client, id_))
|
2016-01-20 00:28:54 +09:00
|
|
|
self.clients = connected
|
|
|
|
|
|
|
|
|
|
# Unpair disconnected devices
|
2020-09-07 17:16:06 +02:00
|
|
|
for client, id_ in disconnected_clients:
|
2016-01-20 00:28:54 +09:00
|
|
|
self.unpair_id(id_)
|
2020-09-07 17:16:06 +02:00
|
|
|
if client.handler:
|
|
|
|
|
client.handler.update_status(False)
|
2016-01-20 00:28:54 +09:00
|
|
|
|
|
|
|
|
return devices
|
commands: add "version_info" cmd
example:
```
$ ./run_electrum -o version_info
{
"aiohttp.version": "3.8.1",
"aiorpcx.version": "0.22.1",
"certifi.version": "2021.10.08",
"cryptodome.version": null,
"cryptography.path": "/home/user/.local/lib/python3.8/site-packages/cryptography",
"cryptography.version": "3.4.6",
"dnspython.version": "2.2.0",
"electrum.path": "/home/user/wspace/electrum/electrum",
"electrum.version": "4.2.1",
"hidapi.version": "0.11.0.post2",
"libsecp256k1.path": "/home/user/wspace/electrum/electrum/libsecp256k1.so.0",
"libusb.path": "libusb-1.0.so",
"libusb.version": "1.0.23.11397",
"libzbar.path": "/home/user/wspace/electrum/electrum/libzbar.so.0",
"pyaes.version": "1.3.0",
"pyqt.path": "/usr/lib/python3/dist-packages/PyQt5",
"pyqt.version": "5.14.1",
"qt.version": "5.12.8"
}
```
2022-04-11 17:05:26 +02:00
|
|
|
|
|
|
|
|
@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:
|
2023-05-30 22:54:26 +00:00
|
|
|
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
|
commands: add "version_info" cmd
example:
```
$ ./run_electrum -o version_info
{
"aiohttp.version": "3.8.1",
"aiorpcx.version": "0.22.1",
"certifi.version": "2021.10.08",
"cryptodome.version": null,
"cryptography.path": "/home/user/.local/lib/python3.8/site-packages/cryptography",
"cryptography.version": "3.4.6",
"dnspython.version": "2.2.0",
"electrum.path": "/home/user/wspace/electrum/electrum",
"electrum.version": "4.2.1",
"hidapi.version": "0.11.0.post2",
"libsecp256k1.path": "/home/user/wspace/electrum/electrum/libsecp256k1.so.0",
"libusb.path": "libusb-1.0.so",
"libusb.version": "1.0.23.11397",
"libzbar.path": "/home/user/wspace/electrum/electrum/libzbar.so.0",
"pyaes.version": "1.3.0",
"pyqt.path": "/usr/lib/python3/dist-packages/PyQt5",
"pyqt.version": "5.14.1",
"qt.version": "5.12.8"
}
```
2022-04-11 17:05:26 +02:00
|
|
|
return ret
|
2022-06-03 15:11:48 +02:00
|
|
|
|
|
|
|
|
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:
|
2022-06-03 15:29:25 +02:00
|
|
|
ks.get_client(
|
2022-06-03 15:11:48 +02:00
|
|
|
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:
|
2022-06-03 15:29:25 +02:00
|
|
|
ks.get_client(
|
2022-06-03 15:11:48 +02:00
|
|
|
force_pair=True,
|
|
|
|
|
allow_user_interaction=True,
|
|
|
|
|
devices=devices,
|
|
|
|
|
)
|
|
|
|
|
except UserCancelled:
|
|
|
|
|
pass
|