wallet: disable_keystore: block only while lightning needs the keystore
What changed, and why it matters
This commit tightens a safety check in the Electrum Bitcoin wallet. Previously, Electrum blocked users from making a keystore 'watching-only' if they had any Lightning channels at all. The new logic only blocks this when Lightning actually still needs the keystore to recover funds, such as when a channel is not fully closed or a submarine swap is pending. Making the keystore watching-only at the wrong time could prevent the wallet from signing transactions needed to sweep funds after a force-close or to complete/refund swaps, potentially causing loss of funds. The change is defensive and reduces the window of risk.
No immediate user action required. This is a hardening patch. Users should keep Electrum updated and avoid making a keystore watching-only while Lightning channels are active or swaps are pending. Developers should ensure the new `lightning_needs_keystore()` predicate remains consistent with any future Lightning recovery flows that require on-chain signing.
Security signals we found
Funds-loss prevention: disabling keystore while Lightning still needs on-chain signing could lock user funds
Defense in depth: adds both GUI and backend (`disable_keystore`) enforcement
Lightning channel lifecycle edge case: force-closed channels and anchor close fee-bumping
Submarine swap refund/claim edge case
Test coverage added for the new guard
Evidence from the diff
The patch replaces the coarse-grained has_channels() guard in disable_keystore with a new lightning_needs_keystore() predicate. lnworker itself operates using lightning_xprv/lightning_privkey2, but sweeping force-closed channel outputs, claiming/refunding submarine swaps, and fee-bumping anchor channel closes require the on-chain keystore to sign transactions. The new predicate returns true if any channel is not is_redeemed() or if swap_manager.get_pending_swaps() is non-empty. The GUI message is updated accordingly, and a unit test verifies the behavior with mocked channels and swaps.
Changed components
electrum/wallet.pyelectrum/gui/qt/wallet_info_dialog.pyelectrum/lnworker.py (referenced behavior, not directly modified)electrum/submarine_swaps.py (referenced behavior via swap_manager, not directly modified)Inspect captured patch +59 / −3
### electrum/gui/qt/wallet_info_dialog.py
@@ -180,8 +180,11 @@ 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.')
### 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
@@ -4366,8 +4383,9 @@ def enable_keystore(self, keystore: KeyStore, is_hardware_keystore: bool, passwo
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():
### tests/test_wizard.py
@@ -1,4 +1,5 @@
import os
+from unittest import mock
from electrum import SimpleConfig
from electrum.interface import ServerAddr
@@ -355,6 +356,40 @@ async def test_enable_keystore__stale_use_encryption_flag(self):
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()Why this scored 44/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.