Merge pull request #11051 from accumulator/keystore_enable_disable_fixes
What changed, and why it matters
This commit fixes several bugs in Electrum's feature that lets users temporarily disable or re-enable a wallet's keystore (the part that holds the private signing key). The changes prevent users from accidentally locking themselves out of Lightning funds, stop unrelated seeds from being accepted when re-enabling a keystore, ensure disabled seed material is actually removed from the wallet file, and fix password/encryption handling when only the keystore (not the whole wallet file) was protected. These are reliability and safety fixes rather than a remote-exploitable vulnerability, but mishandling of private key material and Lightning funds has real security consequences.
Users running affected Electrum versions should upgrade to a release containing this commit. Developers should review the new `lightning_needs_keystore()` logic and the encryption state transitions in `enable_keystore`/`disable_keystore` for completeness, and consider whether additional UI warnings are needed before users disable a keystore.
Security signals we found
Prevents loss of access to Lightning funds by blocking keystore disable while channels/swaps need signing
Prevents acceptance of a mismatched seed/device when re-enabling a keystore
Prevents replacing a non-watching-only keystore, which could destroy seed backup state
Ensures disabled seed/xprv material is removed from disk via forced storage consolidation
Corrects keystore encryption flag handling to avoid inconsistent password/encryption state
Adds GUI wiring fix so the correct target keystore is enabled
Evidence from the diff
The patch hardens the enable/disable keystore workflow in Electrum. Key changes: (1) lightning_needs_keystore() now blocks disabling a keystore when there are non-redeemed Lightning channels or pending submarine swaps, replacing the coarser has_channels() check. (2) enable_keystore() now verifies the supplied keystore matches the target watching-only keystore by xpub, refuses to replace a non-watching-only keystore, correctly handles keystore vs storage encryption, and saves the database. (3) disable_keystore() now forces a full storage rewrite to remove seed/xprv remnants, clears stale keystore encryption flags, and locks the wallet when no password remains. (4) The Qt dialog passes the correct target keystore to enable_keystore() and improves user messaging. (5) Tests cover mismatching seeds, disk cleanup, encryption combinations, and Lightning blocking.
Changed components
electrum/wallet.pyelectrum/gui/qt/wallet_info_dialog.pytests/test_wizard.pyInspect captured patch +248 / −17
### electrum/gui/qt/wallet_info_dialog.py
@@ -153,12 +153,12 @@ def __init__(self, parent: QWidget, *, window: 'ElectrumWindow'):
if wallet.can_enable_disable_keystore(ks):
ks_buttons = []
if not ks.is_watching_only():
- rm_keystore_button = QPushButton('Disable keystore')
+ rm_keystore_button = QPushButton(_('Disable keystore'))
rm_keystore_button.clicked.connect(partial(self.disable_keystore, ks))
ks_buttons.insert(0, rm_keystore_button)
else:
- add_keystore_button = QPushButton('Enable Keystore')
- add_keystore_button.clicked.connect(self.enable_keystore)
+ add_keystore_button = QPushButton(_('Enable keystore'))
+ add_keystore_button.clicked.connect(partial(self.enable_keystore, ks))
ks_buttons.insert(0, add_keystore_button)
ks_vbox.addLayout(Buttons(*ks_buttons))
tab_label = _("Cosigner") + f' {idx+1}' if len(keystores) > 1 else _("Keystore")
@@ -180,32 +180,39 @@ def __init__(self, parent: QWidget, *, window: 'ElectrumWindow'):
self.setLayout(vbox)
def disable_keystore(self, keystore):
- if self.wallet.has_channels():
- self.window.show_message(_('Cannot disable keystore: You have active lightning channels'))
+ if self.wallet.lightning_needs_keystore():
+ self.window.show_message(' '.join([
+ _('Cannot disable keystore: you have lightning channels that are not fully closed, or pending submarine swaps.'),
+ _('Lightning needs the keystore to sign transactions, e.g. to sweep funds after a channel was force-closed.'),
+ ]))
return
msg = _('Disable keystore? This will make the keystore watching-only.')
if self.wallet.storage.is_encrypted_with_hw_device():
msg += '\n\n' + _('Note that this will disable wallet file encryption, because it uses your hardware wallet device.')
+ other_keystores = [k for k in self.wallet.get_keystores() if k is not keystore]
+ if (self.wallet.has_keystore_encryption() and not self.wallet.storage.is_encrypted_with_user_pw()
+ and not any(k.may_have_password() for k in other_keystores)):
+ msg += '\n\n' + ' '.join([
+ _('Note that this will remove the wallet password, because it only protects this keystore.'),
+ _('If you enable the keystore again later, set a new password to protect it.'),
+ ])
if not self.window.question(msg):
return
self.accept()
self.wallet.disable_keystore(keystore)
self.window.gui_object.reload_windows()
- def enable_keystore(self, b: bool):
+ def enable_keystore(self, target_keystore):
v = WizardViewState('keystore_type', {'wallet_type': self.window.wallet.wallet_type}, {})
dialog = QEKeystoreWizard(config=self.window.config, app=self.window.gui_object.app,
plugins=self.window.gui_object.plugins, start_viewstate=v)
result = dialog.run()
if not result:
return
keystore, is_hardware = result
- for k in self.wallet.get_keystores():
- if k.get_master_public_key() == keystore.get_master_public_key():
- break
- else:
- self.window.show_error(_('Keystore not found in this wallet'))
+ if keystore.get_master_public_key() != target_keystore.get_master_public_key():
+ self.window.show_error(_('The provided seed or hardware device does not match this keystore.'))
return
self._enable_keystore(keystore, is_hardware)
### electrum/wallet.py
@@ -547,6 +547,23 @@ def has_lightning(self) -> bool:
def has_channels(self):
return self.lnworker is not None and len(self.lnworker._channels) > 0
+ def lightning_needs_keystore(self) -> bool:
+ """Whether lightning needs the keystore to keep functioning, i.e. whether
+ the keystore must not be disabled (made watching-only).
+
+ lnworker itself only needs lightning_xprv (or lightning_privkey2), not the keystore.
+ However, a watching-only wallet does not sign transactions (see sign_transaction),
+ so it could not sweep the outputs of force-closed channels (incl. penalty txs),
+ nor claim or refund submarine swaps. Anchor channels also need wallet coins for fees.
+ """
+ if not self.lnworker:
+ return False
+ if any(not chan.is_redeemed() for chan in self.lnworker.channels.values()):
+ return True
+ if self.lnworker.swap_manager.get_pending_swaps():
+ return True
+ return False
+
def can_have_lightning(self) -> bool:
""" whether this wallet can create new channels """
# we want static_remotekey to be a wallet address
@@ -4346,22 +4363,45 @@ def can_enable_disable_keystore(self, ks: KeyStore) -> bool:
def enable_keystore(self, keystore: KeyStore, is_hardware_keystore: bool, password) -> None:
assert self.can_enable_disable_keystore(keystore)
- if not is_hardware_keystore and self.storage.is_encrypted_with_user_pw():
- keystore.update_password(None, password)
- self.db.put('use_encryption', True)
+ mpk = keystore.get_master_public_key()
+ target = next((k for k in self.get_keystores() if k.get_master_public_key() == mpk), None)
+ if target is None:
+ raise Exception("mismatching xpubs: keystore not found in wallet")
+ if not target.is_watching_only():
+ # e.g. replacing a keystore that has a seed would remove the seed from the wallet file
+ raise Exception("keystore to be replaced is not watching-only")
+ if not is_hardware_keystore:
+ if self.storage.is_encrypted_with_user_pw() or self.has_keystore_encryption():
+ self.check_password(password)
+ keystore.update_password(None, password)
+ self.db.set_keystore_encryption(True)
+ else:
+ # the wallet has no password.
+ self.db.set_keystore_encryption(False)
self._update_keystore(keystore)
+ self.save_db()
def disable_keystore(self, keystore: KeyStore) -> None:
assert self.can_enable_disable_keystore(keystore)
- assert not self.has_channels()
assert keystore in self.get_keystores()
+ if self.lightning_needs_keystore():
+ raise Exception("cannot disable keystore: needed by lightning")
if hasattr(keystore, 'thread') and keystore.thread:
keystore.thread.stop()
if self.storage.is_encrypted_with_hw_device():
password = keystore.get_password_for_storage_encryption()
self.update_password(password, None, encrypt_storage=False)
new = keystore.watching_only_keystore()
self._update_keystore(new)
+ if not self.can_have_keystore_encryption():
+ # no keystore left that can be encrypted. Without storage encryption,
+ # the wallet no longer has a password.
+ self.db.set_keystore_encryption(False)
+ if not self.has_password():
+ self.lock_wallet() # clear in memory password
+ # save changes. force full rewrite to rm remnants of the seed
+ if self.storage and self.storage.file_exists():
+ self.db.write_and_force_consolidation()
class Standard_Wallet(Simple_Wallet, Deterministic_Wallet):
@@ -4465,7 +4505,7 @@ def _update_keystore(self, keystore):
else:
raise Exception('keystore not found')
self.keystores[name] = keystore
- self.keystore = keystore
+ self.keystore = self.keystores['x1']
self.save_keystore()
def can_have_keystore_encryption(self):
### tests/test_wizard.py
@@ -1,4 +1,5 @@
import os
+from unittest import mock
from electrum import SimpleConfig
from electrum.interface import ServerAddr
@@ -7,8 +8,9 @@
from electrum.plugin import Plugins, DeviceInfo, Device
from electrum.wizard import ServerConnectWizard, NewWalletWizard, WizardViewState, KeystoreWizard
from electrum.daemon import Daemon
-from electrum.wallet import Abstract_Wallet, Deterministic_Wallet
+from electrum.wallet import Abstract_Wallet, Deterministic_Wallet, restore_wallet_from_text
from electrum import util
+from electrum.util import InvalidPassword
from electrum import slip39
from electrum.bip32 import KeyOriginInfo
from electrum import keystore
@@ -263,6 +265,131 @@ async def test_haveseed_electrum__mismatching_seed(self):
wallet.enable_keystore(ks, ishww, None)
self.assertTrue("mismatching xpubs" in ctx.exception.args[0])
+ async def test_haveseed_electrum__mismatching_seed__nothing_modified(self):
+ """a failed attempt to add an unrelated seed should not modify the wallet or the keystore"""
+ wallet = self._create_xpub_keystore_wallet(xpub='zpub6nAZodjgiMNf9zzX1pTqd6ZVX61ax8azhUDnWRumKVUr1VYATVoqAuqv3qKsb8WJXjxei4wei2p4vnMG9RnpKnen2kmgdhvZUmug2NnHNsr')
+ wallet.update_password(None, '1234', encrypt_storage=True)
+ self.assertTrue(wallet.storage.is_encrypted_with_user_pw())
+ self.assertFalse(wallet.db.get('use_encryption', False))
+
+ ks = keystore.from_seed('abandon bike', passphrase='', for_multisig=False)
+ with self.assertRaises(Exception) as ctx:
+ wallet.enable_keystore(ks, False, '1234')
+ self.assertTrue("mismatching xpubs" in ctx.exception.args[0])
+ self.assertTrue(wallet.get_keystore().is_watching_only())
+ self.assertFalse(wallet.db.get('use_encryption', False))
+ self.assertEqual('abandon bike', ks.get_seed(None))
+
+ async def test_enable_keystore__written_to_disk(self):
+ myxpub = 'zpub6nAZodjgiMNf9zzX1pTqd6ZVX61ax8azhUDnWRumKVUr1VYATVoqAuqv3qKsb8WJXjxei4wei2p4vnMG9RnpKnen2kmgdhvZUmug2NnHNsr'
+ wallet = self._create_xpub_keystore_wallet(xpub=myxpub)
+ ks = keystore.from_seed('9dk', passphrase='', for_multisig=False)
+ wallet.enable_keystore(ks, False, None)
+
+ wallet2 = Daemon._load_wallet(self.wallet_path, password=None, config=self.config)
+ self.assertFalse(wallet2.get_keystore().is_watching_only())
+ self.assertEqual('9dk', wallet2.get_keystore().get_seed(None))
+
+ async def test_disable_keystore__seed_removed_from_disk(self):
+ myseed = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
+ wallet = restore_wallet_from_text(myseed, path=self.wallet_path, config=self.config)['wallet']
+ xprv = wallet.get_keystore().xprv
+ with open(self.wallet_path, 'r') as f:
+ contents = f.read()
+ self.assertTrue(myseed in contents and xprv in contents)
+
+ wallet.disable_keystore(wallet.get_keystore())
+ with open(self.wallet_path, 'r') as f:
+ contents = f.read()
+ self.assertFalse(myseed in contents, "seed still in wallet file")
+ self.assertFalse(xprv in contents, "xprv still in wallet file")
+
+ wallet2 = Daemon._load_wallet(self.wallet_path, password=None, config=self.config)
+ self.assertTrue(wallet2.get_keystore().is_watching_only())
+
+ async def test_disable_enable_keystore__keystore_encryption_without_storage_encryption(self):
+ myseed = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
+ wallet = restore_wallet_from_text(
+ myseed, path=self.wallet_path, config=self.config, password='1234', encrypt_file=False)['wallet']
+ self.assertTrue(wallet.has_keystore_encryption())
+ self.assertFalse(wallet.has_storage_encryption())
+
+ # the password only protected the keystore, so after disabling it, the wallet has no password
+ wallet.disable_keystore(wallet.get_keystore())
+ self.assertFalse(wallet.has_password())
+ self.assertFalse(wallet.db.get('use_encryption'))
+
+ ks = keystore.from_seed(myseed, passphrase='', for_multisig=False)
+ wallet.enable_keystore(ks, False, None)
+ self.assertFalse(wallet.has_keystore_encryption())
+ wallet.check_password(None)
+ self.assertEqual(myseed, wallet.get_keystore().get_seed(None))
+
+ async def test_disable_enable_keystore__storage_encryption(self):
+ myseed = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
+ wallet = restore_wallet_from_text(
+ myseed, path=self.wallet_path, config=self.config, password='1234', encrypt_file=True)['wallet']
+ self.assertTrue(wallet.has_keystore_encryption())
+
+ wallet.disable_keystore(wallet.get_keystore())
+ self.assertFalse(wallet.has_keystore_encryption())
+ self.assertTrue(wallet.has_password()) # storage encryption
+
+ ks = keystore.from_seed(myseed, passphrase='', for_multisig=False)
+ wallet.enable_keystore(ks, False, '1234')
+ self.assertTrue(wallet.has_keystore_encryption())
+ wallet.check_password('1234')
+ self.assertEqual(myseed, wallet.get_keystore().get_seed('1234'))
+
+ async def test_enable_keystore__stale_use_encryption_flag(self):
+ """older versions left 'use_encryption' set when disabling the only keystore that was encrypted"""
+ myseed = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
+ wallet = restore_wallet_from_text(myseed, path=self.wallet_path, config=self.config)['wallet']
+ wallet.disable_keystore(wallet.get_keystore())
+ wallet.db.put('use_encryption', True)
+ self.assertFalse(wallet.has_password())
+
+ ks = keystore.from_seed(myseed, passphrase='', for_multisig=False)
+ wallet.enable_keystore(ks, False, None)
+ # the seed is not encrypted, so the wallet must not claim keystore encryption
+ self.assertFalse(wallet.has_keystore_encryption())
+ wallet.check_password(None)
+ self.assertEqual(myseed, wallet.get_keystore().get_seed(None))
+
+ async def test_disable_keystore__lightning(self):
+ myseed = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
+ wallet = restore_wallet_from_text(myseed, path=self.wallet_path, config=self.config)['wallet']
+ self.assertTrue(wallet.db.get('lightning_xprv'))
+ lnworker = wallet.lnworker
+
+ class FakeChannel:
+ def __init__(self, *, redeemed: bool):
+ self.redeemed = redeemed
+
+ def is_redeemed(self):
+ return self.redeemed
+
+ # no channels
+ self.assertFalse(wallet.lightning_needs_keystore())
+ # channel not fully closed
+ lnworker._channels[bytes(32)] = FakeChannel(redeemed=False)
+ self.assertTrue(wallet.lightning_needs_keystore())
+ with self.assertRaisesRegex(Exception, "needed by lightning"):
+ wallet.disable_keystore(wallet.get_keystore())
+ self.assertEqual(myseed, wallet.get_keystore().get_seed(None))
+ # channel fully closed
+ lnworker._channels[bytes(32)] = FakeChannel(redeemed=True)
+ self.assertFalse(wallet.lightning_needs_keystore())
+ # pending swap
+ with mock.patch.object(lnworker.swap_manager, 'get_pending_swaps', return_value=[object()]):
+ self.assertTrue(wallet.lightning_needs_keystore())
+ with self.assertRaisesRegex(Exception, "needed by lightning"):
+ wallet.disable_keystore(wallet.get_keystore())
+ self.assertFalse(wallet.get_keystore().is_watching_only())
+
+ wallet.disable_keystore(wallet.get_keystore())
+ self.assertTrue(wallet.get_keystore().is_watching_only())
+
async def test_haveseed_electrum__2fa_seed(self):
"""unlike NewWalletWizard, KeystoreWizard cannot redirect to the 2fa flow, so 2fa seeds are invalid"""
w, v = self._wizard_for()
@@ -434,10 +561,67 @@ async def test_multisig(self):
self.assertFalse(wallet.get_keystores()[1].is_watching_only())
self.assertEqual(seed1, wallet.get_keystores()[0].get_seed(None))
self.assertEqual(seed2, wallet.get_keystores()[1].get_seed(None))
+ # wallet.keystore must keep pointing to x1
+ self.assertIs(wallet.keystore, wallet.keystores['x1'])
+ self.assertEqual(xpub1, wallet.get_master_public_key())
keyorigininfo1 = wallet.get_keystores()[0].get_key_origin_info()
wallet.disable_keystore(wallet.get_keystores()[0])
self._sanity_checks_after_disabling_keystore(ks=wallet.get_keystores()[0], xpub=xpub1, key_origin_info=keyorigininfo1)
+ self.assertIs(wallet.keystore, wallet.keystores['x1'])
+
+ async def test_multisig__refuse_to_replace_keystore_that_is_not_watching_only(self):
+ seed1 = "bitter grass shiver impose acquire brush forget axis eager alone wine silver"
+ xpub2 = "Zpub6xwgqLvc42wXB1wEELTdALD9iXwStMUkGqBgxkJFYumaL2dWgNvUkjEDWyDFZD3fZuDWDzd1KQJ4NwVHS7hs6H6QkpNYSShfNiUZsgMdtNg"
+
+ wallet = WalletIntegrityHelper.create_multisig_wallet(
+ [
+ keystore.from_seed(seed1, passphrase='', for_multisig=True),
+ keystore.from_xpub(xpub2),
+ ],
+ '2of2',
+ config=self.config,
+ storage=WalletStorage(self.wallet_path),
+ )
+ x1 = wallet.keystores['x1']
+ self.assertFalse(x1.is_watching_only())
+
+ ks = keystore.from_seed(seed1, passphrase='', for_multisig=True)
+ with self.assertRaises(Exception) as ctx:
+ wallet.enable_keystore(ks, False, None)
+ self.assertTrue("not watching-only" in ctx.exception.args[0])
+ self.assertIs(x1, wallet.keystores['x1'])
+ self.assertEqual(seed1, wallet.keystores['x1'].get_seed(None))
+
+ async def test_multisig__keystore_encryption_without_storage_encryption(self):
+ seed1 = "bitter grass shiver impose acquire brush forget axis eager alone wine silver"
+ seed2 = "snow nest raise royal more walk demise rotate smooth spirit canyon gun"
+ xpub2 = "Zpub6xwgqLvc42wXB1wEELTdALD9iXwStMUkGqBgxkJFYumaL2dWgNvUkjEDWyDFZD3fZuDWDzd1KQJ4NwVHS7hs6H6QkpNYSShfNiUZsgMdtNg"
+
+ wallet = WalletIntegrityHelper.create_multisig_wallet(
+ [
+ keystore.from_seed(seed1, passphrase='', for_multisig=True),
+ keystore.from_xpub(xpub2),
+ ],
+ '2of2',
+ config=self.config,
+ storage=WalletStorage(self.wallet_path),
+ )
+ wallet.update_password(None, '1234', encrypt_storage=False)
+ self.assertTrue(wallet.has_keystore_encryption())
+ self.assertFalse(wallet.has_storage_encryption())
+
+ ks = keystore.from_seed(seed2, passphrase='', for_multisig=True)
+ with self.assertRaises(InvalidPassword):
+ wallet.enable_keystore(ks, False, 'wrong password')
+ self.assertTrue(wallet.keystores['x2'].is_watching_only())
+
+ ks = keystore.from_seed(seed2, passphrase='', for_multisig=True)
+ wallet.enable_keystore(ks, False, '1234')
+ self.assertFalse(wallet.keystores['x2'].is_watching_only())
+ # the newly added seed must be encrypted with the wallet password
+ wallet.check_password('1234')
+ self.assertEqual(seed2, wallet.keystores['x2'].get_seed('1234'))
class WalletWizardTestCase(WizardTestCase):Why this scored 59/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.