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
|
|
|
|
2025-03-17 17:29:38 +01:00
|
|
|
import json
|
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
|
2019-06-12 20:07:36 +02:00
|
|
|
import sys
|
2024-06-19 11:24:13 +02:00
|
|
|
import aiohttp
|
2025-03-17 17:29:38 +01:00
|
|
|
import zipfile as zipfile_lib
|
2025-04-04 14:23:52 +02:00
|
|
|
from urllib.parse import urlparse
|
2024-06-19 11:24:13 +02:00
|
|
|
|
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-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
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
from electrum_ecc import ECPrivkey, ECPubkey
|
|
|
|
|
|
|
|
|
|
from ._vendor.distutils.version import StrictVersion
|
|
|
|
|
from .version import ELECTRUM_VERSION
|
2017-01-22 21:25:24 +03:00
|
|
|
from .i18n import _
|
2025-05-23 15:46:08 +00:00
|
|
|
from .util import (profiler, DaemonThread, UserCancelled, ThreadJob, UserFacingException, ChoiceItem, make_dir)
|
2018-10-25 22:20:33 +02:00
|
|
|
from . import bip32
|
2018-07-11 17:38:47 +02:00
|
|
|
from . import plugins
|
2025-04-04 14:23:52 +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:
|
2025-04-10 10:13:24 +02:00
|
|
|
from .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 = {}
|
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]
|
2016-07-02 08:58:56 +02:00
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
PLUGIN_PASSWORD_VERSION = 1
|
|
|
|
|
|
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
|
|
|
|
2023-09-08 14:48:36 +00:00
|
|
|
pkgpath = os.path.dirname(plugins.__file__)
|
2025-04-28 10:17:53 +02:00
|
|
|
# TODO: use XDG Base Directory Specification instead of hardcoding /etc
|
|
|
|
|
keyfile_posix = '/etc/electrum/plugins_key'
|
|
|
|
|
keyfile_windows = r'HKEY_LOCAL_MACHINE\SOFTWARE\Electrum\PluginsKey'
|
2019-05-07 21:07:18 +02:00
|
|
|
|
2015-09-03 12:02:03 +09:00
|
|
|
@profiler
|
2025-04-04 14:23:52 +02:00
|
|
|
def __init__(self, config: SimpleConfig, gui_name: str = None, cmd_only: bool = False):
|
2025-03-15 11:40:26 +01:00
|
|
|
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
|
2025-03-15 11:40:26 +01:00
|
|
|
Logger.__init__(self)
|
2025-03-06 11:43:50 +01:00
|
|
|
self.find_plugins()
|
2025-03-17 17:29:38 +01:00
|
|
|
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)
|
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-17 17:29:38 +01:00
|
|
|
module_path = os.path.join(pkg_path, name)
|
2025-04-11 18:24:59 +02:00
|
|
|
if self.cmd_only and not self.config.get(f'plugins.{name}.enabled') is True:
|
2025-03-17 17:29:38 +01:00
|
|
|
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
|
2024-04-06 11:35:57 +02:00
|
|
|
if 'fullname' not in d:
|
|
|
|
|
continue
|
2025-03-17 17:29:38 +01:00
|
|
|
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)
|
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=}")
|
2025-04-14 12:08:32 +02:00
|
|
|
_logger.info(f"duplicate plugins? for {name=}")
|
|
|
|
|
continue
|
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
|
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}")
|
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:
|
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)
|
2024-05-09 15:38:57 +02:00
|
|
|
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):
|
|
|
|
|
if pkg_path and os.path.exists(pkg_path):
|
2025-04-04 14:23:52 +02:00
|
|
|
if not external:
|
|
|
|
|
self.find_directory_plugins(pkg_path=pkg_path, external=external)
|
|
|
|
|
else:
|
|
|
|
|
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()):
|
2025-04-11 18:24:59 +02:00
|
|
|
if not d.get('requires_wallet_type') and self.config.get(f'plugins.{name}.enabled'):
|
2016-01-24 19:39:59 +09:00
|
|
|
try:
|
2025-03-17 17:29:38 +01:00
|
|
|
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)
|
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-04-28 10:17:53 +02:00
|
|
|
def get_keyfile_path(self, key_hex: Optional[str]) -> Tuple[str, str]:
|
2025-04-04 14:23:52 +02:00
|
|
|
if sys.platform in ['windows', 'win32']:
|
|
|
|
|
keyfile_path = self.keyfile_windows
|
|
|
|
|
keyfile_help = _('This file can be edited with Regdit')
|
|
|
|
|
elif 'ANDROID_DATA' in os.environ:
|
|
|
|
|
raise Exception('platform not supported')
|
|
|
|
|
else:
|
2025-04-28 10:17:53 +02:00
|
|
|
# treat unknown platforms and macOS as linux-like
|
|
|
|
|
keyfile_path = self.keyfile_posix
|
|
|
|
|
keyfile_help = "" if not key_hex else "".join([
|
|
|
|
|
_('The file must have root permissions'),
|
|
|
|
|
".\n\n",
|
|
|
|
|
_("To set it you can also use the Auto-Setup or run "
|
|
|
|
|
"the following terminal command"),
|
|
|
|
|
":\n\n",
|
|
|
|
|
f"sudo sh -c \"{self._posix_plugin_key_creation_command(key_hex)}\"",
|
|
|
|
|
])
|
2025-04-04 14:23:52 +02:00
|
|
|
return keyfile_path, keyfile_help
|
|
|
|
|
|
2025-04-28 10:17:53 +02:00
|
|
|
def try_auto_key_setup(self, pubkey_hex: str) -> bool:
|
|
|
|
|
"""Can be called from the GUI to store the plugin pubkey as root/admin user"""
|
|
|
|
|
try:
|
|
|
|
|
if sys.platform in ['windows', 'win32']:
|
|
|
|
|
self._write_key_to_regedit_windows(pubkey_hex)
|
|
|
|
|
elif 'ANDROID_DATA' in os.environ:
|
|
|
|
|
raise Exception('platform not supported')
|
|
|
|
|
elif sys.platform.startswith('darwin'): # macOS
|
|
|
|
|
self._write_key_to_root_file_macos(pubkey_hex)
|
|
|
|
|
else:
|
|
|
|
|
self._write_key_to_root_file_linux(pubkey_hex)
|
|
|
|
|
except Exception:
|
|
|
|
|
self.logger.exception(f"auto-key setup for {pubkey_hex} failed")
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def try_auto_key_reset(self) -> bool:
|
|
|
|
|
try:
|
|
|
|
|
if sys.platform in ['windows', 'win32']:
|
|
|
|
|
self._delete_plugin_key_from_windows_registry()
|
|
|
|
|
elif 'ANDROID_DATA' in os.environ:
|
|
|
|
|
raise Exception('platform not supported')
|
|
|
|
|
elif sys.platform.startswith('darwin'): # macOS
|
|
|
|
|
self._delete_macos_plugin_keyfile()
|
|
|
|
|
else:
|
|
|
|
|
self._delete_linux_plugin_keyfile()
|
|
|
|
|
except Exception:
|
|
|
|
|
self.logger.exception(f'auto-reset of plugin key failed')
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def _posix_plugin_key_creation_command(self, pubkey_hex: str) -> str:
|
|
|
|
|
"""creates the dir (dir_path), writes the key in file, and sets permissions to 644"""
|
|
|
|
|
dir_path: str = os.path.dirname(self.keyfile_posix)
|
|
|
|
|
sh_command = (
|
|
|
|
|
f"mkdir -p {dir_path} " # create the /etc/electrum dir
|
|
|
|
|
f"&& printf '%s' '{pubkey_hex}' > {self.keyfile_posix} " # write the key to the file
|
|
|
|
|
f"&& chmod 644 {self.keyfile_posix} " # set read permissions for the file
|
|
|
|
|
f"&& chmod 755 {dir_path}" # set read permissions for the dir
|
|
|
|
|
)
|
|
|
|
|
return sh_command
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _get_macos_osascript_command(commands: List[str]) -> List[str]:
|
|
|
|
|
"""
|
|
|
|
|
Inspired by
|
|
|
|
|
https://github.com/barneygale/elevate/blob/01263b690288f022bf6fa702711ac96816bc0e74/elevate/posix.py
|
|
|
|
|
Wraps the given commands in a macOS osascript command to prompt for root permissions.
|
|
|
|
|
"""
|
|
|
|
|
from shlex import quote
|
|
|
|
|
|
|
|
|
|
def quote_shell(args):
|
|
|
|
|
return " ".join(quote(arg) for arg in args)
|
|
|
|
|
|
|
|
|
|
def quote_applescript(string):
|
|
|
|
|
charmap = {
|
|
|
|
|
"\n": "\\n",
|
|
|
|
|
"\r": "\\r",
|
|
|
|
|
"\t": "\\t",
|
|
|
|
|
"\"": "\\\"",
|
|
|
|
|
"\\": "\\\\",
|
|
|
|
|
}
|
|
|
|
|
return '"%s"' % "".join(charmap.get(char, char) for char in string)
|
|
|
|
|
|
|
|
|
|
commands = [
|
|
|
|
|
"osascript",
|
|
|
|
|
"-e",
|
|
|
|
|
"do shell script %s "
|
|
|
|
|
"with administrator privileges "
|
|
|
|
|
"without altering line endings"
|
|
|
|
|
% quote_applescript(quote_shell(commands))
|
|
|
|
|
]
|
|
|
|
|
return commands
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _run_win_regedit_as_admin(reg_exe_command: str) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Runs reg.exe reg_exe_command and requests admin privileges through UAC prompt.
|
|
|
|
|
"""
|
|
|
|
|
# has to use ShellExecuteEx as ShellExecuteW (the simpler api) doesn't allow to wait
|
|
|
|
|
# for the result of the process (returns no process handle)
|
|
|
|
|
from ctypes import byref, sizeof, windll, Structure, c_ulong
|
|
|
|
|
from ctypes.wintypes import HANDLE, DWORD, HWND, HINSTANCE, HKEY, LPCWSTR
|
|
|
|
|
|
|
|
|
|
# https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa
|
|
|
|
|
class SHELLEXECUTEINFO(Structure):
|
|
|
|
|
_fields_ = [
|
|
|
|
|
('cbSize', DWORD),
|
|
|
|
|
('fMask', c_ulong),
|
|
|
|
|
('hwnd', HWND),
|
|
|
|
|
('lpVerb', LPCWSTR),
|
|
|
|
|
('lpFile', LPCWSTR),
|
|
|
|
|
('lpParameters', LPCWSTR),
|
|
|
|
|
('lpDirectory', LPCWSTR),
|
|
|
|
|
('nShow', c_ulong),
|
|
|
|
|
('hInstApp', HINSTANCE),
|
|
|
|
|
('lpIDList', c_ulong),
|
|
|
|
|
('lpClass', LPCWSTR),
|
|
|
|
|
('hkeyClass', HKEY),
|
|
|
|
|
('dwHotKey', DWORD),
|
|
|
|
|
('hIcon', HANDLE),
|
|
|
|
|
('hProcess', HANDLE)
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
info = SHELLEXECUTEINFO()
|
|
|
|
|
info.cbSize = sizeof(SHELLEXECUTEINFO)
|
|
|
|
|
info.fMask = 0x00000040 # SEE_MASK_NOCLOSEPROCESS (so we can check the result of the process)
|
|
|
|
|
info.hwnd = None
|
|
|
|
|
info.lpVerb = 'runas' # run as administrator
|
|
|
|
|
info.lpFile = 'reg.exe' # the executable to run
|
|
|
|
|
info.lpParameters = reg_exe_command # the registry edit command
|
|
|
|
|
info.lpDirectory = None
|
|
|
|
|
info.nShow = 1
|
|
|
|
|
|
|
|
|
|
# Execute and wait
|
|
|
|
|
if not windll.shell32.ShellExecuteExW(byref(info)):
|
|
|
|
|
error = windll.kernel32.GetLastError()
|
|
|
|
|
raise Exception(f'Error executing registry command: {error}')
|
|
|
|
|
|
|
|
|
|
# block until the process is done or 5 sec timeout
|
|
|
|
|
windll.kernel32.WaitForSingleObject(info.hProcess, 0x1338)
|
|
|
|
|
|
|
|
|
|
# Close handle
|
|
|
|
|
windll.kernel32.CloseHandle(info.hProcess)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _execute_commands_in_subprocess(commands: List[str]) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Executes the given commands in a subprocess and asserts that it was successful.
|
|
|
|
|
"""
|
|
|
|
|
import subprocess
|
2025-05-22 21:48:27 +00:00
|
|
|
with subprocess.Popen(
|
2025-04-28 10:17:53 +02:00
|
|
|
commands,
|
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
|
stderr=subprocess.PIPE,
|
2025-05-22 21:48:27 +00:00
|
|
|
text=True,
|
|
|
|
|
) as process:
|
|
|
|
|
stdout, stderr = process.communicate()
|
|
|
|
|
if process.returncode != 0:
|
|
|
|
|
raise Exception(f'error executing command ({process.returncode}): {stderr}')
|
2025-04-28 10:17:53 +02:00
|
|
|
|
|
|
|
|
def _write_key_to_root_file_linux(self, key_hex: str) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Spawns a pkexec subprocess to write the key to a file with root permissions.
|
|
|
|
|
This will open an OS dialog asking for the root password. Can only succeed if
|
|
|
|
|
the system has polkit installed.
|
|
|
|
|
"""
|
|
|
|
|
assert os.path.exists("/etc"), "System does not have /etc directory"
|
|
|
|
|
|
|
|
|
|
sh_command: str = self._posix_plugin_key_creation_command(key_hex)
|
|
|
|
|
commands = ['pkexec', 'sh', '-c', sh_command]
|
|
|
|
|
self._execute_commands_in_subprocess(commands)
|
|
|
|
|
|
|
|
|
|
# check if the key was written correctly
|
|
|
|
|
with open(self.keyfile_posix, 'r') as f:
|
|
|
|
|
assert f.read() == key_hex, f'file content mismatch: {f.read()} != {key_hex}'
|
|
|
|
|
self.logger.debug(f'file saved successfully to {self.keyfile_posix}')
|
|
|
|
|
|
|
|
|
|
def _delete_linux_plugin_keyfile(self) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Deletes the root owned key file at self.keyfile_posix.
|
|
|
|
|
"""
|
|
|
|
|
if not os.path.exists(self.keyfile_posix):
|
|
|
|
|
self.logger.debug(f'file {self.keyfile_posix} does not exist')
|
|
|
|
|
return
|
|
|
|
|
if not self._has_root_permissions(self.keyfile_posix):
|
|
|
|
|
os.unlink(self.keyfile_posix)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
# use pkexec to delete the file as root user
|
|
|
|
|
commands = ['pkexec', 'rm', self.keyfile_posix]
|
|
|
|
|
self._execute_commands_in_subprocess(commands)
|
|
|
|
|
assert not os.path.exists(self.keyfile_posix), f'file {self.keyfile_posix} still exists'
|
|
|
|
|
|
|
|
|
|
def _write_key_to_root_file_macos(self, key_hex: str) -> None:
|
|
|
|
|
assert os.path.exists("/etc"), "System does not have /etc directory"
|
|
|
|
|
|
|
|
|
|
sh_command: str = self._posix_plugin_key_creation_command(key_hex)
|
|
|
|
|
macos_commands = self._get_macos_osascript_command(["sh", "-c", sh_command])
|
|
|
|
|
|
|
|
|
|
self._execute_commands_in_subprocess(macos_commands)
|
|
|
|
|
with open(self.keyfile_posix, 'r') as f:
|
|
|
|
|
assert f.read() == key_hex, f'file content mismatch: {f.read()} != {key_hex}'
|
|
|
|
|
self.logger.debug(f'file saved successfully to {self.keyfile_posix}')
|
|
|
|
|
|
|
|
|
|
def _delete_macos_plugin_keyfile(self) -> None:
|
|
|
|
|
if not os.path.exists(self.keyfile_posix):
|
|
|
|
|
self.logger.debug(f'file {self.keyfile_posix} does not exist')
|
|
|
|
|
return
|
|
|
|
|
if not self._has_root_permissions(self.keyfile_posix):
|
|
|
|
|
os.unlink(self.keyfile_posix)
|
|
|
|
|
return
|
|
|
|
|
# use osascript to delete the file as root user
|
|
|
|
|
macos_commands = self._get_macos_osascript_command(["rm", self.keyfile_posix])
|
|
|
|
|
self._execute_commands_in_subprocess(macos_commands)
|
|
|
|
|
assert not os.path.exists(self.keyfile_posix), f'file {self.keyfile_posix} still exists'
|
|
|
|
|
|
|
|
|
|
def _write_key_to_regedit_windows(self, key_hex: str) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Writes the key to the Windows registry with windows UAC prompt.
|
|
|
|
|
"""
|
|
|
|
|
from winreg import ConnectRegistry, OpenKey, QueryValue, HKEY_LOCAL_MACHINE
|
|
|
|
|
|
|
|
|
|
value_type = 'REG_SZ'
|
|
|
|
|
command = f'add "{self.keyfile_windows}" /ve /t {value_type} /d "{key_hex}" /f'
|
|
|
|
|
|
|
|
|
|
self._run_win_regedit_as_admin(command)
|
|
|
|
|
|
|
|
|
|
# check if the key was written correctly
|
|
|
|
|
with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hkey:
|
|
|
|
|
with OpenKey(hkey, r'SOFTWARE\Electrum') as key:
|
|
|
|
|
assert key_hex == QueryValue(key, 'PluginsKey'), "incorrect registry key value"
|
|
|
|
|
self.logger.debug(f'key saved successfully to {self.keyfile_windows}')
|
|
|
|
|
|
|
|
|
|
def _delete_plugin_key_from_windows_registry(self) -> None:
|
|
|
|
|
"""
|
|
|
|
|
Deletes the PluginsKey dir in the Windows registry.
|
|
|
|
|
"""
|
|
|
|
|
from winreg import ConnectRegistry, OpenKey, HKEY_LOCAL_MACHINE
|
|
|
|
|
|
|
|
|
|
command = f'delete "{self.keyfile_windows}" /f'
|
|
|
|
|
self._run_win_regedit_as_admin(command)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
# do a sanity check to see if the key has been deleted
|
|
|
|
|
with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hkey:
|
|
|
|
|
with OpenKey(hkey, r'SOFTWARE\Electrum\PluginsKey'):
|
|
|
|
|
raise Exception(f'Key {self.keyfile_windows} still exists, deletion failed')
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
pass
|
|
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
def create_new_key(self, password:str) -> str:
|
|
|
|
|
salt = os.urandom(32)
|
|
|
|
|
privkey = self.derive_privkey(password, salt)
|
|
|
|
|
pubkey = privkey.get_public_key_bytes()
|
2025-04-11 10:05:58 +02:00
|
|
|
key = bytes([PLUGIN_PASSWORD_VERSION]) + salt + pubkey
|
2025-04-04 14:23:52 +02:00
|
|
|
return key.hex()
|
|
|
|
|
|
|
|
|
|
def get_pubkey_bytes(self) -> Tuple[Optional[bytes], bytes]:
|
|
|
|
|
"""
|
|
|
|
|
returns pubkey, salt
|
|
|
|
|
returns None, None if the pubkey has not been set
|
|
|
|
|
"""
|
|
|
|
|
if sys.platform in ['windows', 'win32']:
|
|
|
|
|
import winreg
|
|
|
|
|
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
|
|
|
|
|
try:
|
|
|
|
|
with winreg.OpenKey(hkey, r"SOFTWARE\\Electrum") as key:
|
|
|
|
|
key_hex = winreg.QueryValue(key, "PluginsKey")
|
|
|
|
|
except Exception as e:
|
|
|
|
|
self.logger.info(f'winreg error: {e}')
|
|
|
|
|
return None, None
|
|
|
|
|
elif 'ANDROID_DATA' in os.environ:
|
|
|
|
|
return None, None
|
|
|
|
|
else:
|
|
|
|
|
# treat unknown platforms as linux-like
|
2025-04-28 10:17:53 +02:00
|
|
|
if not os.path.exists(self.keyfile_posix):
|
2025-04-04 14:23:52 +02:00
|
|
|
return None, None
|
2025-04-28 10:17:53 +02:00
|
|
|
if not self._has_root_permissions(self.keyfile_posix):
|
2025-04-04 14:23:52 +02:00
|
|
|
return
|
2025-04-28 10:17:53 +02:00
|
|
|
with open(self.keyfile_posix) as f:
|
2025-04-04 14:23:52 +02:00
|
|
|
key_hex = f.read()
|
2025-04-28 10:17:53 +02:00
|
|
|
try:
|
|
|
|
|
key = bytes.fromhex(key_hex)
|
|
|
|
|
version = key[0]
|
|
|
|
|
except Exception:
|
|
|
|
|
self.logger.exception(f'{key_hex=} invalid')
|
|
|
|
|
return None, None
|
2025-04-04 14:23:52 +02:00
|
|
|
if version != PLUGIN_PASSWORD_VERSION:
|
|
|
|
|
self.logger.info(f'unknown plugin password version: {version}')
|
|
|
|
|
return None, None
|
|
|
|
|
# all good
|
|
|
|
|
salt = key[1:1+32]
|
|
|
|
|
pubkey = key[1+32:]
|
|
|
|
|
return pubkey, salt
|
|
|
|
|
|
|
|
|
|
def get_external_plugin_dir(self) -> str:
|
|
|
|
|
pkg_path = os.path.join(self.config.electrum_path(), 'plugins')
|
2025-05-23 15:46:08 +00:00
|
|
|
make_dir(pkg_path)
|
2024-05-09 15:38:57 +02:00
|
|
|
return pkg_path
|
2023-11-29 12:13:34 +01:00
|
|
|
|
2025-04-28 16:55:21 +02:00
|
|
|
async def download_external_plugin(self, url: str) -> str:
|
2025-04-04 14:23:52 +02:00
|
|
|
filename = os.path.basename(urlparse(url).path)
|
|
|
|
|
pkg_path = self.get_external_plugin_dir()
|
|
|
|
|
path = os.path.join(pkg_path, filename)
|
2025-04-28 16:55:21 +02:00
|
|
|
if os.path.exists(path):
|
|
|
|
|
raise FileExistsError(f"Plugin {filename} already exists at {path}")
|
2025-04-04 14:23:52 +02:00
|
|
|
async with aiohttp.ClientSession() as session:
|
|
|
|
|
async with session.get(url) as resp:
|
|
|
|
|
if resp.status == 200:
|
|
|
|
|
with open(path, 'wb') as fd:
|
|
|
|
|
async for chunk in resp.content.iter_chunked(10):
|
|
|
|
|
fd.write(chunk)
|
|
|
|
|
return path
|
|
|
|
|
|
|
|
|
|
def read_manifest(self, path) -> dict:
|
|
|
|
|
""" return json dict """
|
|
|
|
|
with zipfile_lib.ZipFile(path) as file:
|
|
|
|
|
for filename in file.namelist():
|
|
|
|
|
if filename.endswith('manifest.json'):
|
|
|
|
|
break
|
|
|
|
|
else:
|
|
|
|
|
raise Exception('could not find manifest.json in zip archive')
|
|
|
|
|
with file.open(filename, 'r') as f:
|
|
|
|
|
manifest = json.load(f)
|
|
|
|
|
manifest['path'] = path # external, path of the zipfile
|
|
|
|
|
manifest['dirname'] = os.path.dirname(filename) # internal
|
|
|
|
|
manifest['is_zip'] = True
|
|
|
|
|
manifest['zip_hash_sha256'] = get_file_hash256(path).hex()
|
|
|
|
|
return manifest
|
|
|
|
|
|
|
|
|
|
def zip_plugin_path(self, name) -> str:
|
|
|
|
|
path = self.get_metadata(name)['path']
|
|
|
|
|
filename = os.path.basename(path)
|
2025-03-17 14:22:01 +01:00
|
|
|
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
|
2024-05-09 15:38:57 +02:00
|
|
|
try:
|
2025-04-04 14:23:52 +02:00
|
|
|
d = self.read_manifest(path)
|
|
|
|
|
name = d['name']
|
|
|
|
|
except Exception:
|
|
|
|
|
self.logger.info(f"could not load manifest.json from zip plugin {filename}", exc_info=True)
|
2024-05-09 15:38:57 +02:00
|
|
|
continue
|
2025-04-14 12:08:32 +02:00
|
|
|
if name in self.internal_plugin_metadata or name in self.external_plugin_metadata:
|
|
|
|
|
self.logger.info(f"duplicate plugins for {name=}")
|
|
|
|
|
continue
|
2025-04-11 18:24:59 +02:00
|
|
|
if self.cmd_only and not self.config.get(f'plugins.{name}.enabled'):
|
2025-04-04 14:23:52 +02:00
|
|
|
continue
|
|
|
|
|
min_version = d.get('min_electrum_version')
|
|
|
|
|
if min_version and StrictVersion(min_version) > StrictVersion(ELECTRUM_VERSION):
|
|
|
|
|
self.logger.info(f"version mismatch for zip plugin {filename}", exc_info=True)
|
|
|
|
|
continue
|
|
|
|
|
max_version = d.get('max_electrum_version')
|
|
|
|
|
if max_version and StrictVersion(max_version) < StrictVersion(ELECTRUM_VERSION):
|
|
|
|
|
self.logger.info(f"version mismatch for zip plugin {filename}", exc_info=True)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if not self.cmd_only:
|
|
|
|
|
gui_good = self.gui_name in d.get('available_for', [])
|
|
|
|
|
if not gui_good:
|
2025-03-17 17:29:38 +01:00
|
|
|
continue
|
2025-04-04 14:23:52 +02:00
|
|
|
if 'fullname' not in d:
|
2024-05-09 15:38:57 +02:00
|
|
|
continue
|
2025-04-11 09:20:52 +02:00
|
|
|
details = d.get('registers_keystore')
|
|
|
|
|
if details:
|
|
|
|
|
self.register_keystore(name, gui_good, details)
|
2025-04-04 14:23:52 +02:00
|
|
|
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 17:29:38 +01:00
|
|
|
def maybe_load_plugin_init_method(self, name: str) -> None:
|
|
|
|
|
"""Loads the __init__.py module of the plugin if it is not already loaded."""
|
2025-05-17 11:14:13 +02:00
|
|
|
base_name = ('electrum_external_plugins.' if self.is_external(name) else 'electrum.plugins.') + name
|
2025-03-17 17:29:38 +01:00
|
|
|
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:
|
2025-05-17 11:14:13 +02:00
|
|
|
if self.is_external(name):
|
2025-04-04 14:23:52 +02:00
|
|
|
# this branch is deprecated: external plugins are always zip files
|
2025-03-17 17:29:38 +01:00
|
|
|
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'])
|
2025-04-04 14:23:52 +02:00
|
|
|
dirname = metadata['dirname']
|
|
|
|
|
init_spec = zipfile.find_spec(dirname)
|
|
|
|
|
|
2025-03-19 14:52:13 +00:00
|
|
|
self.exec_module_from_spec(init_spec, base_name)
|
2025-03-17 17:29:38 +01:00
|
|
|
|
|
|
|
|
def load_plugin_by_name(self, name: str) -> '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 17:29:38 +01:00
|
|
|
# if the plugin was not enabled on startup the init module hasn't been loaded yet
|
|
|
|
|
self.maybe_load_plugin_init_method(name)
|
2025-05-17 11:14:13 +02:00
|
|
|
is_external = self.is_external(name)
|
2025-04-04 14:23:52 +02:00
|
|
|
if is_external and not self.is_authorized(name):
|
|
|
|
|
self.logger.info(f'plugin not authorized {name}')
|
|
|
|
|
return
|
2025-03-17 14:22:01 +01:00
|
|
|
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 17:29:38 +01:00
|
|
|
module = self.exec_module_from_spec(spec, full_name)
|
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
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
def derive_privkey(self, pw: str, salt:bytes) -> ECPrivkey:
|
|
|
|
|
from hashlib import pbkdf2_hmac
|
|
|
|
|
secret = pbkdf2_hmac('sha256', pw.encode('utf-8'), salt, iterations=10**5)
|
|
|
|
|
return ECPrivkey(secret)
|
|
|
|
|
|
2025-04-14 12:08:32 +02:00
|
|
|
def uninstall(self, name: str):
|
2025-04-28 10:17:53 +02:00
|
|
|
if self.config.get(f'plugins.{name}'):
|
|
|
|
|
self.config.set_key(f'plugins.{name}', None)
|
2025-04-14 12:08:32 +02:00
|
|
|
if name in self.external_plugin_metadata:
|
|
|
|
|
zipfile = self.zip_plugin_path(name)
|
|
|
|
|
os.unlink(zipfile)
|
|
|
|
|
self.external_plugin_metadata.pop(name)
|
|
|
|
|
|
|
|
|
|
def is_internal(self, name) -> bool:
|
|
|
|
|
return name in self.internal_plugin_metadata
|
|
|
|
|
|
2025-05-17 11:14:13 +02:00
|
|
|
def is_external(self, name) -> bool:
|
|
|
|
|
return name in self.external_plugin_metadata
|
|
|
|
|
|
2025-04-14 12:08:32 +02:00
|
|
|
def is_auto_loaded(self, name):
|
|
|
|
|
metadata = self.external_plugin_metadata.get(name) or self.internal_plugin_metadata.get(name)
|
|
|
|
|
return metadata and (metadata.get('registers_keystore') or metadata.get('registers_wallet_type'))
|
|
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
def is_installed(self, name) -> bool:
|
|
|
|
|
"""an external plugin may be installed but not authorized """
|
2025-05-17 11:14:13 +02:00
|
|
|
return (name in self.internal_plugin_metadata or name in self.external_plugin_metadata)
|
2025-04-04 14:23:52 +02:00
|
|
|
|
|
|
|
|
def is_authorized(self, name) -> bool:
|
|
|
|
|
if name in self.internal_plugin_metadata:
|
|
|
|
|
return True
|
|
|
|
|
if name not in self.external_plugin_metadata:
|
|
|
|
|
return False
|
|
|
|
|
pubkey_bytes, salt = self.get_pubkey_bytes()
|
|
|
|
|
if not pubkey_bytes:
|
|
|
|
|
return False
|
|
|
|
|
if not self.is_plugin_zip(name):
|
|
|
|
|
return False
|
|
|
|
|
filename = self.zip_plugin_path(name)
|
|
|
|
|
plugin_hash = get_file_hash256(filename)
|
2025-04-11 18:24:59 +02:00
|
|
|
sig = self.config.get(f'plugins.{name}.authorized')
|
2025-04-04 14:23:52 +02:00
|
|
|
if not sig:
|
|
|
|
|
return False
|
|
|
|
|
pubkey = ECPubkey(pubkey_bytes)
|
|
|
|
|
return pubkey.ecdsa_verify(bytes.fromhex(sig), plugin_hash)
|
|
|
|
|
|
|
|
|
|
def authorize_plugin(self, name: str, filename, privkey: ECPrivkey):
|
|
|
|
|
pubkey_bytes, salt = self.get_pubkey_bytes()
|
|
|
|
|
assert pubkey_bytes == privkey.get_public_key_bytes()
|
|
|
|
|
plugin_hash = get_file_hash256(filename)
|
|
|
|
|
sig = privkey.ecdsa_sign(plugin_hash)
|
|
|
|
|
value = sig.hex()
|
2025-05-17 11:14:13 +02:00
|
|
|
self.config.set_key(f'plugins.{name}.authorized', value)
|
|
|
|
|
self.config.set_key(f'plugins.{name}.enabled', True)
|
2025-04-04 14:23:52 +02:00
|
|
|
|
2020-05-26 00:54:22 +02:00
|
|
|
def enable(self, name: str) -> 'BasePlugin':
|
2025-04-14 12:08:32 +02:00
|
|
|
self.config.enable_plugin(name)
|
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:
|
2025-04-14 12:08:32 +02:00
|
|
|
self.config.disable_plugin(name)
|
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:
|
2025-04-11 18:24:59 +02:00
|
|
|
return key.startswith('plugins.')
|
2023-09-08 14:55:22 +00: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-04-14 12:08:32 +02:00
|
|
|
def read_file(self, name: str, filename: str) -> bytes:
|
|
|
|
|
if self.is_plugin_zip(name):
|
|
|
|
|
plugin_filename = self.zip_plugin_path(name)
|
|
|
|
|
metadata = self.external_plugin_metadata[name]
|
|
|
|
|
dirname = metadata['dirname']
|
|
|
|
|
with zipfile_lib.ZipFile(plugin_filename) as myzip:
|
|
|
|
|
with myzip.open(os.path.join(dirname, filename)) as myfile:
|
|
|
|
|
return myfile.read()
|
2025-05-17 11:14:13 +02:00
|
|
|
elif name in self.internal_plugin_metadata:
|
2025-04-14 12:08:32 +02:00
|
|
|
path = os.path.join(os.path.dirname(__file__), 'plugins', name, filename)
|
|
|
|
|
with open(path, 'rb') as myfile:
|
|
|
|
|
return myfile.read()
|
2025-05-17 11:14:13 +02:00
|
|
|
else:
|
|
|
|
|
# no icon
|
|
|
|
|
return None
|
2025-03-06 11:43:50 +01:00
|
|
|
|
2025-04-04 14:23:52 +02:00
|
|
|
def get_file_hash256(path: str) -> bytes:
|
|
|
|
|
'''Get the sha256 hash of a file, similar to `sha256sum`.'''
|
2025-01-09 18:05:37 +01:00
|
|
|
with open(path, 'rb') as f:
|
2025-04-04 14:23:52 +02:00
|
|
|
return sha256(f.read())
|
|
|
|
|
|
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
|
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):
|
2025-04-14 12:08:32 +02:00
|
|
|
if not self.is_available():
|
|
|
|
|
return False
|
2025-05-17 11:14:13 +02:00
|
|
|
if not self.parent.is_authorized(self.name):
|
|
|
|
|
return False
|
2025-04-14 12:08:32 +02:00
|
|
|
return self.config.is_plugin_enabled(self.name)
|
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:
|
2025-04-14 12:08:32 +02:00
|
|
|
return self.parent.read_file(self.name, filename)
|
2016-01-31 19:36:21 +09:00
|
|
|
|
2025-05-05 18:16:29 +02:00
|
|
|
def get_storage(self, wallet: 'Abstract_Wallet') -> dict:
|
|
|
|
|
"""Returns a dict which is persisted in the per-wallet database."""
|
|
|
|
|
plugin_storage = wallet.db.get_plugin_storage()
|
|
|
|
|
return plugin_storage.setdefault(self.name, {})
|
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
|
|
|
|
2025-05-06 17:47:11 +00:00
|
|
|
def label_for_device_select(self) -> str:
|
|
|
|
|
return (
|
|
|
|
|
"{label} ({maybe_model}{init}, {transport})"
|
|
|
|
|
.format(
|
|
|
|
|
label=self.label or _("An unnamed {}").format(self.plugin_name),
|
|
|
|
|
init=(_("initialized") if self.initialized else _("wiped")),
|
|
|
|
|
transport=self.device.transport_ui_string,
|
|
|
|
|
maybe_model=f"{self.model_name}, " if self.model_name else ""
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
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.") + ")"
|
2025-05-06 17:47:11 +00:00
|
|
|
choices = [ChoiceItem(key=idx, label=info.label_for_device_select())
|
|
|
|
|
for (idx, info) in enumerate(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}")
|
2025-05-06 17:26:41 +00:00
|
|
|
c = handler.query_choice(msg, choices)
|
2016-08-26 12:26:43 +02:00
|
|
|
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:
|
ci: enable more flake8 stuff
```
$ export ELECTRUM_LINTERS=E9,E101,E129,E273,E274,E703,E71,E722,F5,F6,F7,F8,W191,W29,B
$ export ELECTRUM_LINTERS_IGNORE=B007,B009,B010,B019,B036,F541,F841
$ flake8 . --count --select="$ELECTRUM_LINTERS" --ignore="$ELECTRUM_LINTERS_IGNORE" --show-source --statistics --exclude "*_pb2.py,electrum/_vendor/"
./electrum/commands.py:98:1: F811 redefinition of unused 'format_satoshis' from line 48
def format_satoshis(x):
^
./electrum/commands.py:437:9: F811 redefinition of unused 'Mnemonic' from line 62
from .mnemonic import Mnemonic
^
./electrum/gui/qt/wizard/wallet.py:37:5: F811 redefinition of unused 'Daemon' from line 14
from electrum.daemon import Daemon
^
./electrum/lntransport.py:14:1: F811 redefinition of unused 'Optional' from line 12
from typing import NamedTuple, List, Tuple, Mapping, Optional, TYPE_CHECKING, Union, Dict, Set, Sequence
^
./electrum/lntransport.py:14:1: F811 redefinition of unused 'TYPE_CHECKING' from line 12
from typing import NamedTuple, List, Tuple, Mapping, Optional, TYPE_CHECKING, Union, Dict, Set, Sequence
^
./electrum/plugin.py:966:13: F811 redefinition of unused 'hid' from line 593
import hid
^
./electrum/plugin.py:1040:13: F811 redefinition of unused 'hid' from line 593
import hid
^
./electrum/util.py:44:1: F811 redefinition of unused 'json' from line 26
import json
^
./electrum/util.py:46:1: F811 redefinition of unused 'NamedTuple' from line 29
from typing import NamedTuple, Optional
^
./electrum/util.py:46:1: F811 redefinition of unused 'Optional' from line 29
from typing import NamedTuple, Optional
^
./electrum/util.py:1456:56: F811 redefinition of unused 'traceback' from line 34
async def __aexit__(self, exc_type, exc_value, traceback):
^
./electrum/wallet_db.py:536:9: F811 redefinition of unused 'LOCAL' from line 46
LOCAL = 1
^
./electrum/wallet_db.py:537:9: F811 redefinition of unused 'REMOTE' from line 46
REMOTE = -1
^
./tests/test_bitcoin.py:28:1: F811 redefinition of unused 'bitcoin' from line 9
from electrum import crypto, constants, bitcoin
^
./tests/test_txbatcher.py:11:1: F811 redefinition of unused 'Transaction' from line 7
from electrum.transaction import Transaction, PartialTxInput, PartialTxOutput, TxOutpoint
^
./tests/test_wallet_vertical.py:20:1: F811 redefinition of unused 'Transaction' from line 10
from electrum.transaction import Transaction, PartialTxOutput, tx_from_any, Sighash
^
16 F811 redefinition of unused 'format_satoshis' from line 48
16
```
2025-04-02 16:16:05 +00:00
|
|
|
import hid # noqa: F811
|
2018-03-16 00:55:45 +01:00
|
|
|
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:
|
ci: enable more flake8 stuff
```
$ export ELECTRUM_LINTERS=E9,E101,E129,E273,E274,E703,E71,E722,F5,F6,F7,F8,W191,W29,B
$ export ELECTRUM_LINTERS_IGNORE=B007,B009,B010,B019,B036,F541,F841
$ flake8 . --count --select="$ELECTRUM_LINTERS" --ignore="$ELECTRUM_LINTERS_IGNORE" --show-source --statistics --exclude "*_pb2.py,electrum/_vendor/"
./electrum/commands.py:98:1: F811 redefinition of unused 'format_satoshis' from line 48
def format_satoshis(x):
^
./electrum/commands.py:437:9: F811 redefinition of unused 'Mnemonic' from line 62
from .mnemonic import Mnemonic
^
./electrum/gui/qt/wizard/wallet.py:37:5: F811 redefinition of unused 'Daemon' from line 14
from electrum.daemon import Daemon
^
./electrum/lntransport.py:14:1: F811 redefinition of unused 'Optional' from line 12
from typing import NamedTuple, List, Tuple, Mapping, Optional, TYPE_CHECKING, Union, Dict, Set, Sequence
^
./electrum/lntransport.py:14:1: F811 redefinition of unused 'TYPE_CHECKING' from line 12
from typing import NamedTuple, List, Tuple, Mapping, Optional, TYPE_CHECKING, Union, Dict, Set, Sequence
^
./electrum/plugin.py:966:13: F811 redefinition of unused 'hid' from line 593
import hid
^
./electrum/plugin.py:1040:13: F811 redefinition of unused 'hid' from line 593
import hid
^
./electrum/util.py:44:1: F811 redefinition of unused 'json' from line 26
import json
^
./electrum/util.py:46:1: F811 redefinition of unused 'NamedTuple' from line 29
from typing import NamedTuple, Optional
^
./electrum/util.py:46:1: F811 redefinition of unused 'Optional' from line 29
from typing import NamedTuple, Optional
^
./electrum/util.py:1456:56: F811 redefinition of unused 'traceback' from line 34
async def __aexit__(self, exc_type, exc_value, traceback):
^
./electrum/wallet_db.py:536:9: F811 redefinition of unused 'LOCAL' from line 46
LOCAL = 1
^
./electrum/wallet_db.py:537:9: F811 redefinition of unused 'REMOTE' from line 46
REMOTE = -1
^
./tests/test_bitcoin.py:28:1: F811 redefinition of unused 'bitcoin' from line 9
from electrum import crypto, constants, bitcoin
^
./tests/test_txbatcher.py:11:1: F811 redefinition of unused 'Transaction' from line 7
from electrum.transaction import Transaction, PartialTxInput, PartialTxOutput, TxOutpoint
^
./tests/test_wallet_vertical.py:20:1: F811 redefinition of unused 'Transaction' from line 10
from electrum.transaction import Transaction, PartialTxOutput, tx_from_any, Sighash
^
16 F811 redefinition of unused 'format_satoshis' from line 48
16
```
2025-04-02 16:16:05 +00:00
|
|
|
import hid # noqa: F811
|
2023-05-30 22:54:26 +00:00
|
|
|
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
|