What changed, and why it matters
This commit is a small follow-up cleanup in Electrum's keystore code. It renames an internal helper function, makes the code accept certain unusual 'old' seed phrases that some users created by hand, improves an error message shown to users, and adds more tests. There is no direct evidence in the commit that this fixes an active security vulnerability; it appears to be a robustness and maintainability improvement.
No immediate action required. Treat as routine code maintenance. Reviewers may want to verify that relaxing odd-length hex seed acceptance does not introduce unintended behavior in seed restoration or key derivation paths.
Security signals we found
Refactoring of seed validation helper
User-facing error handling improvement in seed display
Grandfathering of non-standard old seed phrases
Addition of regression tests for odd-length hex seeds
Evidence from the diff
The patch refactors _is_old_hex_seed to _is_maybe_old_hex_seed and switches from string.hexdigits to is_hex_str(..., allow_odd_len=True). It updates Old_KeyStore._get_hex_seed, get_seed, and stretch_key to use the renamed helper. A user-facing exception is now raised when an old seed cannot be shown as words, and the GUI’s seed dialog now catches UserFacingException separately from other exceptions to show a friendlier message. Tests are expanded to cover additional hand-constructed old seeds and odd-length hex seeds. The changes reference prior issues #3149 and #11045.
Changed components
electrum/keystore.pyelectrum/gui/qt/main_window.pytests/test_mnemonic.pytests/test_wallet_vertical.pyInspect captured patch +35 / −15
### electrum/gui/qt/main_window.py
@@ -2081,7 +2081,10 @@ def show_seed_dialog(self, password):
try:
seed = keystore.get_seed(password)
passphrase = keystore.get_passphrase(password)
- except BaseException as e:
+ except UserFacingException as e:
+ self.show_error(str(e))
+ return
+ except Exception as e:
self.show_error(repr(e))
return
from .seed_dialog import SeedDialog
### electrum/keystore.py
@@ -24,7 +24,6 @@
from unicodedata import normalize
import hashlib
import re
-import string
import copy
from typing import Tuple, TYPE_CHECKING, Union, Sequence, Optional, Dict, List, NamedTuple, Any, Type
from functools import wraps
@@ -51,6 +50,7 @@
from .plugin import run_hook
from .logging import Logger
from .lrucache import LRUCache
+from .i18n import _
if TYPE_CHECKING:
from .gui.common_qt.util import TaskThread
@@ -749,10 +749,12 @@ def get_lightning_xprv(self, password) -> str:
return node.to_xprv()
-def _is_old_hex_seed(text: Any) -> bool:
- # Unlike is_hex_str, this allows an odd length: mn_decode returns 9 hex digits
- # for a word triple worth 2**32 or more, which mn_encode never produces (#11045).
- return isinstance(text, str) and all(c in string.hexdigits for c in text)
+def _is_maybe_old_hex_seed(text: Any) -> bool:
+ # Accept any hex str, even odd length. (though not in the wizard as a user-input hex-seed!)
+ # We only ever generated "old" seeds whose hex-char-len is a multiple of 8 (see old_mnemonic.mn_encode),
+ # however some users hand-constructed malformed "old" seeds that map to different lengths,
+ # that mn_decode still accepts. We also accept those... (ref #3149)
+ return is_hex_str(text, allow_odd_len=True)
class Old_KeyStore(MasterPublicKeyMixin, Deterministic_KeyStore):
@@ -769,10 +771,10 @@ def watching_only_keystore(self):
return Old_KeyStore({'mpk': self.mpk})
def _get_hex_seed(self, password) -> str:
- if not _is_old_hex_seed(self.seed) and password is None:
+ if not _is_maybe_old_hex_seed(self.seed) and password is None:
raise InvalidPassword()
hex_str = pw_decode(self.seed, password, version=self.pw_hash_version)
- assert _is_old_hex_seed(hex_str), f"expected hex str, got {type(hex_str)} with {len(hex_str)=}"
+ assert _is_maybe_old_hex_seed(hex_str), f"expected hex str, got {type(hex_str)} with {len(hex_str)=}"
return hex_str
def dump(self):
@@ -813,7 +815,7 @@ def get_seed(self, password):
hex_seed = self._get_hex_seed(password)
if len(hex_seed) % 8 != 0:
raise UserFacingException(
- "This seed cannot be shown as words. Keep the seed phrase the wallet was restored from.")
+ _("This seed cannot be shown as words. Keep the seed phrase the wallet was restored from."))
return ' '.join(old_mnemonic.mn_encode(hex_seed))
@classmethod
@@ -824,7 +826,7 @@ def mpk_from_seed(cls, hex_seed: str) -> str:
@classmethod
def stretch_key(cls, hex_seed: str) -> int:
- assert _is_old_hex_seed(hex_seed), f"expected hex str, got {type(hex_seed)} with {len(hex_seed)=}"
+ assert _is_maybe_old_hex_seed(hex_seed), f"expected hex str, got {type(hex_seed)} with {len(hex_seed)=}"
encoded_hex_seed = hex_seed.encode('ascii')
x = encoded_hex_seed
for i in range(100000):
### tests/test_mnemonic.py
@@ -173,26 +173,32 @@ class Test_seeds(ElectrumTestCase):
""" Test old and new seeds. """
mnemonics = {
+ # "old"
('cell dumb heartbeat north boom tease ship baby bright kingdom rare squeeze', 'old'),
('cell dumb heartbeat north boom tease ' * 4, 'old'),
('cell dumb heartbeat north boom tease ship baby bright kingdom rare badword', ''),
('cElL DuMb hEaRtBeAt nOrTh bOoM TeAsE ShIp bAbY BrIgHt kInGdOm rArE SqUeEzE', 'old'),
(' cElL DuMb hEaRtBeAt nOrTh bOoM TeAsE ShIp bAbY BrIgHt kInGdOm rArE SqUeEzE ', 'old'),
- # below seed is actually 'invalid old' as it maps to 33 hex chars
+ # kind-of-invalid "old", as they map to 33-36 hex chars (ref #3149)
('hurry idiot prefer sunset mention mist jaw inhale impossible kingdom rare squeeze', 'old'),
+ ('early given garden bond decay curtain companion random storm chair learn lust', 'old'),
+ ('bond decay curtain bond decay curtain bond decay curtain bond decay curtain', 'old'),
+ # "standard"
('cram swing cover prefer miss modify ritual silly deliver chunk behind inform able', 'standard'),
('cram swing cover prefer miss modify ritual silly deliver chunk behind inform', ''),
('ostrich security deer aunt climb inner alpha arm mutual marble solid task', 'standard'),
('OSTRICH SECURITY DEER AUNT CLIMB INNER ALPHA ARM MUTUAL MARBLE SOLID TASK', 'standard'),
(' oStRiCh sEcUrItY DeEr aUnT ClImB InNeR AlPhA ArM MuTuAl mArBlE SoLiD TaSk ', 'standard'),
+ # "2fa"
('science dawn member doll dutch real can brick knife deny drive list', '2fa'),
('science dawn member doll dutch real ca brick knife deny drive list', ''),
(' sCience dawn member doll Dutch rEAl can brick knife deny drive lisT', '2fa'),
- # pre-version-2.7 2fa seed with 25 words:
+ # pre-version-2.7 "2fa" seed with 25 words:
('bind clever room kidney crucial sausage spy edit canvas soul liquid ribbon slam open alpha suffer gate relax voice carpet law hill woman tonight abstract', '2fa'),
(' bInd cLEveR room kidney crucial sausage spy edit canvas soul liquid ribbon SLAM open alpha suffer gate relax voice carpet law hill woman tonight abstract ', '2fa'),
- # pre-version-2.7 2fa seed with 24 words:
+ # pre-version-2.7 "2fa" seed with 24 words:
('sibling leg cable timber patient foot occur plate travel finger chef scale radio citizen promote immune must chef fluid sea sphere common acid lab', '2fa'),
+ # "segwit"
('frost pig brisk excite novel report camera enlist axis nation novel desert', 'segwit'),
(' fRoSt pig brisk excIte novel rePort CamEra enlist axis nation nOVeL dEsert ', 'segwit'),
# short seed cheat sheet:
### tests/test_wallet_vertical.py
@@ -23,7 +23,7 @@
)
from electrum.fee_policy import FixedFeePolicy
from electrum.transaction import Transaction, PartialTxOutput, tx_from_any, Sighash
-from electrum.mnemonic import calc_seed_type
+from electrum.mnemonic import calc_seed_type, is_old_seed
from electrum.network import Network
from electrum.plugins.trustedcoin import trustedcoin
@@ -180,6 +180,7 @@ async def test_electrum_seed_old(self):
for seed_to_restore_from in (seed_words, seed_hex):
with self.subTest(seed_to_restore_from=seed_to_restore_from):
self.assertEqual(calc_seed_type(seed_to_restore_from), 'old')
+ self.assertTrue(is_old_seed(seed_to_restore_from))
ks = keystore.from_seed(seed_to_restore_from, passphrase='', for_multisig=False)
@@ -198,10 +199,18 @@ async def test_electrum_seed_old(self):
self.assertEqual(w.get_change_addresses()[0], '1KRW8pH6HFHZh889VDq6fEKvmrsmApwNfe')
async def test_electrum_seed_old_odd_length_hex(self):
- # "bond decay curtain" decodes to 9 hex digits, see #11045. Expected values are from Electrum 4.2.1.
+ """
+ "early given" is a technically invalid "old" electrum seed, which maps to 33 hex chars (ref #3149).
+ We never generated such seeds, however "old" seeds do not have a checksum, and some users
+ constructed their seed manually by hand-picking words. Not all selection of words conform to the expected rules,
+ so some hand-constructed old seeds are ~invalid, however we have grandfathered them in...
+ (The "bond decay curtain" word-triple decodes to 9 hex digits, instead of the expected 8)
+ """
seed_words = 'early given garden bond decay curtain companion random storm chair learn lust'
seed_hex = '976741d01001ab4b7a17d6ce83a1bca93'
self.assertEqual(calc_seed_type(seed_words), 'old')
+ self.assertTrue(is_old_seed(seed_words))
+ self.assertFalse(is_old_seed(seed_hex)) # normally the hex-seed we would also accept, but reject 33-len monsters
ks = keystore.from_seed(seed_words, passphrase='', for_multisig=False)
Why this scored 26/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.