What changed, and why it matters
This commit is a straightforward internal cleanup: it moves repeated operating-system checks (Windows, macOS, Linux, Android, AppImage) into a single new helper module called platform.py and updates the rest of the code to use those helpers. There is no change in behavior, no bug fix, and no security-relevant change visible in the diff.
No security action needed. Treat as normal refactoring; standard code-review and regression testing are sufficient.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch introduces electrum/platform.py with small predicates (is_android, is_linux, is_windows, is_mac, is_appimage) and mechanically replaces scattered sys.platform, os.name, os.environ.get(‘APPIMAGE’), and ‘ANDROID_DATA’ in os.environ checks across 19 files. The logic is preserved exactly; for example, is_windows() still matches ‘win32’ and ‘windows’, and is_appimage() still requires both APPIMAGE env var and linux. No functional or security logic was altered.
Changed components
electrum/platform.py (new)electrum/daemon.pyelectrum/dns_hacks.pyelectrum/gui/default_lang.pyelectrum/gui/qml/qeapp.pyelectrum/gui/qml/qebiometrics.pyelectrum/gui/qt/__init__.pyelectrum/gui/qt/main_window.pyelectrum/gui/qt/settings_dialog.pyelectrum/gui/qt/stylesheet_patcher.pyelectrum/gui/qt/util.pyelectrum/gui/qt/wizard/wallet.pyelectrum/logging.pyelectrum/plugin.pyelectrum/plugins/digitalbitbox/digitalbitbox.pyelectrum/qrreader/zxing.pyelectrum/simple_config.pyelectrum/util.pyrun_electrumInspect captured patch +87 / −76
### electrum/daemon.py
@@ -40,8 +40,7 @@
from aiohttp import web, client_exceptions
from aiorpcx import ignore_after
-from . import crandom
-from . import util
+from . import crandom, util, GuiImportError, platform
from .network import Network
from .util import (
json_decode, to_bytes, to_string, profiler, standardize_path, constant_time_compare, InvalidPassword,
@@ -54,7 +53,6 @@
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
from .logging import get_logger, Logger
-from . import GuiImportError
from .plugin import run_hook, Plugins
if TYPE_CHECKING:
@@ -78,7 +76,7 @@ def get_rpcsock_default_type(config: SimpleConfig):
# Use unix domain sockets when available,
# with the extra paranoia that in case windows "implements" them,
# we want to test it before making it the default there.
- if hasattr(socket, 'AF_UNIX') and sys.platform != 'win32':
+ if hasattr(socket, 'AF_UNIX') and not platform.is_windows():
return 'unix'
return 'tcp'
### electrum/dns_hacks.py
@@ -14,7 +14,7 @@
from .logging import get_logger
from .util import get_asyncio_loop
-from . import util
+from . import util, platform
_logger = get_logger(__name__)
@@ -23,7 +23,7 @@ def configure_dns_resolver() -> None:
# Store this somewhere so we can un-monkey-patch:
if not hasattr(socket, "_getaddrinfo"):
socket._getaddrinfo = socket.getaddrinfo
- if sys.platform == 'win32':
+ if platform.is_windows():
# On Windows, socket.getaddrinfo takes a mutex, and might hold it for up to 10 seconds
# when dns-resolving. To speed it up drastically, we resolve dns ourselves, outside that lock.
# See https://github.com/spesmilo/electrum/issues/4421
### electrum/gui/default_lang.py
@@ -6,14 +6,14 @@
# This is to avoid evaluating module-level string-translations before we get
# a chance to set the default language.
-import os
from typing import Optional
+from electrum import platform
from electrum.i18n import languages
jLocale = None
-if "ANDROID_DATA" in os.environ:
+if platform.is_android():
from jnius import autoclass, cast
jLocale = autoclass("java.util.Locale")
### electrum/gui/qml/qeapp.py
@@ -14,7 +14,7 @@
from PyQt6.QtQml import qmlRegisterType, QQmlApplicationEngine
import electrum
-from electrum import version, constants
+from electrum import version, constants, platform
from electrum.i18n import _
from electrum.logging import Logger, get_logger
from electrum.bip21 import BITCOIN_BIP21_URI_SCHEME, LIGHTNING_URI_SCHEME
@@ -54,7 +54,7 @@
from electrum.daemon import Daemon
from electrum.plugin import Plugins
-if 'ANDROID_DATA' in os.environ:
+if platform.is_android():
from jnius import autoclass, cast
from android import activity, permissions
@@ -386,7 +386,7 @@ def isPluginEnabled(self, plugin: str):
@pyqtSlot(result=bool)
def isAndroid(self):
- return 'ANDROID_DATA' in os.environ
+ return platform.is_android()
@pyqtSlot(result='QVariantMap')
def crashData(self):
### electrum/gui/qml/qebiometrics.py
@@ -4,7 +4,7 @@
from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty, QMetaObject, Qt
-from electrum import crandom
+from electrum import crandom, platform
from electrum.i18n import _
from electrum.logging import get_logger
from electrum.base_crash_reporter import send_exception_to_crash_reporter
@@ -25,7 +25,7 @@
jIntent = None
jString = None
-if 'ANDROID_DATA' in os.environ:
+if platform.is_android():
from jnius import autoclass, JavaException
from android import activity
try:
@@ -59,7 +59,7 @@ def __init__(self, *, config: 'SimpleConfig', parent=None):
@pyqtProperty(bool, constant=True)
def isAvailable(self) -> bool:
- if 'ANDROID_DATA' not in os.environ or jBiometricHelper is None:
+ if not platform.is_android() or jBiometricHelper is None:
return False
try:
return jBiometricHelper.isAvailable(jPythonActivity)
### electrum/gui/qt/__init__.py
@@ -44,6 +44,7 @@
import PyQt6.QtCore as QtCore
+from electrum import platform
from electrum.logging import Logger, get_logger
_logger = get_logger(__name__)
@@ -58,7 +59,7 @@
else:
_logger.debug(f"successfully preloaded optional dependency: PyQt6.QtMultimedia")
-if sys.platform == "linux" and os.environ.get("APPIMAGE"):
+if platform.is_appimage():
# For AppImage, we default to xcb qt backend, for better support of older system.
# qt6 normally defaults to QT_QPA_PLATFORM=wayland instead of QT_QPA_PLATFORM=xcb.
# However, the wayland QPA plugin requires libwayland-client0>=1.19, which is too new
@@ -189,7 +190,7 @@ def __init__(self, *, config: 'SimpleConfig', daemon: 'Daemon', plugins: 'Plugin
self.app = QElectrumApplication(sys.argv)
self.app.installEventFilter(self.open_file_efilter)
self.screenshot_protection_efilter = ScreenshotProtectionEventFilter()
- if sys.platform in ['win32', 'windows'] and self.config.GUI_QT_SCREENSHOT_PROTECTION:
+ if platform.is_windows() and self.config.GUI_QT_SCREENSHOT_PROTECTION:
self.app.installEventFilter(self.screenshot_protection_efilter)
self.efilter_no_rich_text = InjectNoRichTextEventFilter()
self.app.installEventFilter(self.efilter_no_rich_text)
### electrum/gui/qt/main_window.py
@@ -49,8 +49,7 @@
import electrum
from electrum.gui import messages
-from electrum import (keystore, constants, util, bitcoin, commands,
- lnutil)
+from electrum import keystore, constants, util, bitcoin, commands, lnutil, platform
from electrum.bitcoin import COIN, is_address, DummyAddress
from electrum.plugin import run_hook
from electrum.i18n import _
@@ -818,7 +817,7 @@ def add_toggle_action(tab):
self.tools_menu = menubar.addMenu(_("&Tools")) # type: QMenu
preferences_action = self.tools_menu.addAction(_("Preferences"), self.settings_dialog) # type: QAction
- if sys.platform == 'darwin':
+ if platform.is_mac():
# "Settings"/"Preferences" are all reserved keywords in macOS.
# preferences_action will get picked up based on name (and put into a standardized location,
# and given a standard reserved hotkey)
@@ -842,7 +841,7 @@ def add_toggle_action(tab):
self.raw_transaction_menu = raw_transaction_menu
self.help_menu = menubar.addMenu(_("&Help"))
- if sys.platform != 'darwin':
+ if not platform.is_mac():
self.help_menu.addAction(_("&About"), self.show_about)
else:
# macOS reserves the "About" menu item name, similarly to "Preferences" (see above).
### electrum/gui/qt/settings_dialog.py
@@ -24,15 +24,14 @@
# SOFTWARE.
import ast
-import sys
from typing import TYPE_CHECKING, Dict
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (QComboBox, QTabWidget, QDialog, QSpinBox, QCheckBox, QLabel,
QVBoxLayout, QGridLayout, QLineEdit, QWidget, QHBoxLayout)
from electrum.i18n import _, get_gui_lang_names
-from electrum import util
+from electrum import util, platform
from electrum.util import base_units_list, event_listener
from electrum.gui.common_qt.util import QtEventListener
@@ -236,7 +235,7 @@ def on_set_filelogging(_x):
self.config.cv.GUI_QT_SCREENSHOT_PROTECTION
)
screenshot_protection_cb.setChecked(self.config.GUI_QT_SCREENSHOT_PROTECTION)
- if sys.platform not in ['windows', 'win32']:
+ if not platform.is_windows():
screenshot_protection_cb.setChecked(False)
screenshot_protection_cb.setDisabled(True)
screenshot_protection_cb.setToolTip(_("This option is only available on Windows"))
### electrum/gui/qt/stylesheet_patcher.py
@@ -2,10 +2,10 @@
It reads the current stylesheet, appends our modifications and sets the new stylesheet.
"""
-import sys
-
from PyQt6 import QtWidgets
+from electrum import platform
+
CUSTOM_PATCH_FOR_DARK_THEME = '''
/* PayToEdit text was being clipped */
@@ -61,7 +61,7 @@ def patch_qt_stylesheet(use_dark_theme: bool) -> None:
if use_dark_theme:
custom_patch = CUSTOM_PATCH_FOR_DARK_THEME
else: # default theme (typically light)
- if sys.platform == 'darwin':
+ if platform.is_mac():
custom_patch = CUSTOM_PATCH_FOR_DEFAULT_THEME_MACOS
app = QtWidgets.QApplication.instance()
### electrum/gui/qt/util.py
@@ -1,8 +1,6 @@
from abc import ABC, ABCMeta
import os.path
import time
-import sys
-import platform
import queue
import os
import webbrowser
@@ -20,6 +18,7 @@
QGraphicsEffect, QGraphicsScene, QGraphicsPixmapItem, QLayoutItem, QLayout, QMenu,
QFrame, QAbstractButton)
+from electrum import platform
from electrum.i18n import _
from electrum.util import (FileImportFailed, FileExportFailed, resource_path, EventListener,
get_logger, UserCancelled, UserFacingException, ChoiceItem)
@@ -38,9 +37,9 @@
from electrum.simple_config import ConfigVarWithConfig
-if platform.system() == 'Windows':
+if platform.is_windows():
MONOSPACE_FONT = 'Lucida Console'
-elif platform.system() == 'Darwin':
+elif platform.is_mac():
MONOSPACE_FONT = 'Monaco'
else:
MONOSPACE_FONT = 'monospace'
@@ -1357,7 +1356,7 @@ def font_height(widget: QWidget = None) -> int:
def webopen(url: str):
- if sys.platform == 'linux' and os.environ.get('APPIMAGE'):
+ if platform.is_appimage():
# When on Linux webbrowser.open can fail in AppImage because it can't find the correct libdbus.
# We just fork the process and unset LD_LIBRARY_PATH before opening the URL.
# See #5425
@@ -1503,7 +1502,7 @@ def set_windows_os_screenshot_protection_drm_flag(window: QWidget) -> None:
screenshots and microsoft recall will not be able to record the window
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowdisplayaffinity
"""
- if sys.platform not in ('win32', 'windows'):
+ if not platform.is_windows():
return
try:
window_id = int(window.winId())
### electrum/gui/qt/wizard/wallet.py
@@ -10,6 +10,7 @@
from PyQt6.QtWidgets import (QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QWidget,
QFileDialog, QSlider, QGridLayout, QDialog, QApplication)
+from electrum import platform
from electrum.bip32 import is_bip32_derivation, BIP32Node, normalize_bip32_derivation, xpub_type
from electrum.daemon import Daemon
from electrum.i18n import _
@@ -1225,11 +1226,11 @@ def failed_getting_device_infos(name, e):
debug_msg = ' {}'.format(_('No exceptions encountered.'))
if not devices:
msg = (_('No hardware device detected.') + '\n\n')
- if sys.platform == 'win32':
+ if platform.is_windows():
msg += _('If your device is not detected on Windows, go to "Settings", "Devices", "Connected devices", '
'and do "Remove device". Then, plug your device again.') + '\n'
msg += _('While this is less than ideal, it might help if you run Electrum as Administrator.') + '\n'
- else:
+ elif platform.is_linux():
msg += _('On Linux, you might have to add a new permission to your udev rules.') + '\n'
msg += '\n\n'
msg += _('Debug message') + '\n' + debug_msg
### electrum/logging.py
@@ -9,12 +9,14 @@
import sys
import pathlib
import os
-import platform
+import platform as py_platform
from typing import Optional, TYPE_CHECKING, Set
import copy
import subprocess
import hashlib
+from electrum import platform
+
if TYPE_CHECKING:
from .simple_config import SimpleConfig
@@ -345,13 +347,13 @@ def get_logfile_path() -> Optional[pathlib.Path]:
def describe_os_version() -> str:
- if 'ANDROID_DATA' in os.environ:
+ if platform.is_android():
import jnius
bv = jnius.autoclass('android.os.Build$VERSION')
b = jnius.autoclass('android.os.Build')
return "Android {} on {} {} ({})".format(bv.RELEASE, b.BRAND, b.DEVICE, b.DISPLAY)
else:
- return platform.platform()
+ return py_platform.platform()
@lru_cache # result unlikely to change while running. though "-dirty" could technically change
### electrum/platform.py
@@ -0,0 +1,23 @@
+import os
+import sys
+
+
+def is_android():
+ return 'ANDROID_DATA' in os.environ
+
+
+def is_linux():
+ # android is linux, but we don't want to match here
+ return sys.platform == 'linux' and not is_android()
+
+
+def is_windows():
+ return sys.platform in ['win32', 'windows'] # not sure if 'windows' can still occur.
+
+
+def is_mac():
+ return sys.platform == 'darwin'
+
+
+def is_appimage():
+ return 'APPIMAGE' in os.environ and is_linux()
### electrum/plugin.py
@@ -48,9 +48,7 @@
from .i18n import _
from .util import (profiler, DaemonThread, UserCancelled, ThreadJob, UserFacingException, ChoiceItem,
make_dir, make_aiohttp_session, make_object_immutable)
-from . import bip32
-from . import plugins
-from . import crandom
+from . import bip32, plugins, crandom, platform
from .simple_config import SimpleConfig
from .logging import get_logger, Logger
from .crypto import sha256
@@ -263,10 +261,10 @@ def _has_root_permissions(self, path):
return os.stat(path).st_uid == 0 and not os.access(path, os.W_OK)
def get_keyfile_path(self, key_hex: Optional[str]) -> Tuple[str, str]:
- if sys.platform in ['windows', 'win32']:
+ if platform.is_windows():
keyfile_path = self.keyfile_windows
keyfile_help = _('This file can be edited with Regedit')
- elif 'ANDROID_DATA' in os.environ:
+ elif platform.is_android():
raise Exception('platform not supported')
else:
# treat unknown platforms and macOS as linux-like
@@ -284,11 +282,11 @@ def get_keyfile_path(self, key_hex: Optional[str]) -> Tuple[str, str]:
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']:
+ if platform.is_windows():
self._write_key_to_regedit_windows(pubkey_hex)
- elif 'ANDROID_DATA' in os.environ:
+ elif platform.is_android():
raise Exception('platform not supported')
- elif sys.platform.startswith('darwin'): # macOS
+ elif platform.is_mac():
self._write_key_to_root_file_macos(pubkey_hex)
else:
self._write_key_to_root_file_linux(pubkey_hex)
@@ -299,11 +297,11 @@ def try_auto_key_setup(self, pubkey_hex: str) -> bool:
def try_auto_key_reset(self) -> bool:
try:
- if sys.platform in ['windows', 'win32']:
+ if platform.is_windows():
self._delete_plugin_key_from_windows_registry()
- elif 'ANDROID_DATA' in os.environ:
+ elif platform.is_android():
raise Exception('platform not supported')
- elif sys.platform.startswith('darwin'): # macOS
+ elif platform.is_mac():
self._delete_macos_plugin_keyfile()
else:
self._delete_linux_plugin_keyfile()
@@ -524,7 +522,7 @@ def get_pubkey_bytes(self) -> Tuple[Optional[bytes], Optional[bytes]]:
returns pubkey, salt
returns None, None if the pubkey has not been set
"""
- if sys.platform in ['windows', 'win32']:
+ if platform.is_windows():
import winreg
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
try:
@@ -533,7 +531,7 @@ def get_pubkey_bytes(self) -> Tuple[Optional[bytes], Optional[bytes]]:
except Exception as e:
self.logger.info(f'winreg error: {e}')
return None, None
- elif 'ANDROID_DATA' in os.environ:
+ elif platform.is_android():
return None, None
else:
# treat unknown platforms as linux-like
### electrum/plugins/digitalbitbox/digitalbitbox.py
@@ -23,17 +23,15 @@
from electrum.bitcoin import public_key_to_p2pkh, usermessage_magic, verify_usermessage_with_address
from electrum.bip32 import BIP32Node, convert_bip32_intpath_to_strpath, is_all_public_derivation
from electrum.bip32 import normalize_bip32_derivation
-from electrum import descriptor
+from electrum import descriptor, constants, crandom, platform
from electrum.wallet import Standard_Wallet
-from electrum import constants
from electrum.transaction import Transaction, PartialTransaction, PartialTxInput, Sighash
from electrum.i18n import _
from electrum.keystore import Hardware_KeyStore
from electrum.util import to_string, UserCancelled, UserFacingException, bfh, ChoiceItem
from electrum.network import Network
from electrum.logging import get_logger
from electrum.plugin import runs_in_hwd_thread, run_in_hwd_thread
-from electrum import crandom
from electrum.hw_wallet import HW_PluginBase, HardwareClientBase, HardwareHandlerBase
from electrum.hw_wallet.plugin import OperationCancelled
@@ -284,9 +282,9 @@ def seed_device_dialog(self):
def mobile_pairing_dialog(self):
dbb_user_dir = None
- if sys.platform == 'darwin':
+ if platform.is_mac():
dbb_user_dir = os.path.join(os.environ.get("HOME", ""), "Library", "Application Support", "DBB")
- elif sys.platform == 'win32':
+ elif platform.is_windows():
dbb_user_dir = os.path.join(os.environ["APPDATA"], "DBB")
else:
dbb_user_dir = os.path.join(os.environ["HOME"], ".dbb")
### electrum/qrreader/zxing.py
@@ -4,13 +4,13 @@
import ctypes
import os
-import sys
from typing import List, Optional, Tuple
from . import MissingLib
from .abstract_base import AbstractQrCodeReader, QrCodeResult
-from ..logging import get_logger
+from electrum.logging import get_logger
+from electrum import platform
_logger = get_logger(__name__)
@@ -23,9 +23,9 @@ class _Position(ctypes.Structure):
_fields_ = [(corner, _Point) for corner in ('topLeft', 'topRight', 'bottomRight', 'bottomLeft')]
-if sys.platform == 'darwin':
+if platform.is_mac():
LIBNAMES = ('libZXing.dylib',)
-elif sys.platform == 'win32':
+elif platform.is_windows():
LIBNAMES = ('ZXing.dll',)
else:
# Distro runtime packages only ship the versioned soname, e.g. libZXing.so.3 of Debian's libzxing3.
### electrum/simple_config.py
@@ -7,9 +7,7 @@
from copy import deepcopy
-from . import constants
-from . import util
-from . import invoices
+from . import constants, util, invoices, platform
from .util import base_units, base_unit_name_to_decimal_point, decimal_point_to_base_unit_name, UnknownBaseUnit, DECIMAL_POINT_DEFAULT
from .util import format_satoshis, format_fee_satoshis, os_chmod
from .util import user_dir, make_dir
@@ -468,7 +466,7 @@ def save_user_config(self):
def get_backup_dir(self) -> Optional[str]:
# this is used to save wallet file backups (without active lightning channels)
# on Android, the export backup button uses android_backup_dir()
- if 'ANDROID_DATA' in os.environ:
+ if platform.is_android():
return None
else:
return self.WALLET_BACKUP_DIRECTORY
### electrum/util.py
@@ -72,7 +72,7 @@
from .i18n import _
from .logging import get_logger, Logger
-from . import crandom
+from . import platform
if TYPE_CHECKING:
from .network import Network, ProxySettings
@@ -423,7 +423,7 @@ def stop(self):
self.wake_up_event.clear()
def on_stop(self):
- if 'ANDROID_DATA' in os.environ:
+ if platform.is_android():
import jnius
jnius.detach()
self.logger.info("jnius detach")
@@ -644,8 +644,7 @@ def is_hidden_wallet_path(wallet_path: Any) -> bool:
def is_android_debug_apk() -> bool:
- is_android = 'ANDROID_DATA' in os.environ
- if not is_android:
+ if not platform.is_android():
return False
from jnius import autoclass
pkgname = get_android_package_name()
@@ -654,8 +653,7 @@ def is_android_debug_apk() -> bool:
def get_android_package_name() -> str:
- is_android = 'ANDROID_DATA' in os.environ
- assert is_android
+ assert platform.is_android()
from jnius import autoclass
from android.config import ACTIVITY_CLASS_NAME
activity = autoclass(ACTIVITY_CLASS_NAME).mActivity
@@ -718,7 +716,7 @@ def xor_bytes(a: bytes, b: bytes) -> bytes:
def user_dir():
if "ELECTRUMDIR" in os.environ:
return os.environ["ELECTRUMDIR"]
- elif 'ANDROID_DATA' in os.environ:
+ elif platform.is_android():
return android_data_dir()
elif os.name == 'posix':
return os.path.join(os.environ["HOME"], ".electrum")
### run_electrum
@@ -39,7 +39,6 @@ import warnings
import asyncio
from typing import TYPE_CHECKING, Optional, Dict
-
script_dir = os.path.dirname(os.path.realpath(__file__))
is_pyinstaller = getattr(sys, 'frozen', False)
is_android = 'ANDROID_DATA' in os.environ
@@ -92,9 +91,7 @@ def check_imports():
if not is_android:
check_imports()
-
-
-if is_android:
+else:
# hack to make pycryptodomex work on Android
# from https://github.com/kivy/python-for-android/issues/1866#issuecomment-927157780
import ctypes
@@ -126,7 +123,7 @@ from electrum.commands import get_parser, get_simple_parser, known_commands, Com
from electrum import daemon
from electrum.util import create_and_start_event_loop, UserFacingException, JsonRPCError
from electrum.i18n import set_language
-from electrum import constants
+from electrum import constants, platform
if TYPE_CHECKING:
import threading
@@ -395,7 +392,7 @@ def main():
sys.argv[i] = prompt_password('Enter argument (will not echo):', confirm=False)
# config is an object passed to the various constructors (wallet, interface, gui)
- if is_android:
+ if platform.is_android():
import importlib.util
config_options = {
'verbosity': '*' if util.is_android_debug_apk() else '',Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.