keystore: Old_KeyStore: allow odd-length hex seeds
What changed, and why it matters
This commit fixes a bug in Electrum where very old wallet seeds containing a rare word combination could no longer be imported or used to sign transactions since version 4.6.1. The fix restores support for these odd-length hex seeds while preventing the wallet from trying to display them as a normal word seed. It is a bug fix for a denial-of-service/access-loss issue, not an exploitable vulnerability that lets an attacker steal funds.
Apply the patch. Users with old Electrum seeds who could not import or sign since 4.6.1 should upgrade. Advise affected users to back up the original seed phrase, because the wallet cannot display these odd-length seeds as words again.
Security signals we found
Bug causes loss of access to existing wallets for users with rare old seeds
Fix restores signing capability for affected old wallets
No new cryptographic primitive or entropy weakness introduced
get_seed now explicitly refuses to re-encode unrepresentable seeds, reducing user confusion
Change is narrowly scoped to Old_KeyStore legacy seed handling
Evidence from the diff
Old_KeyStore previously rejected hex seeds whose length was not even/valid for is_hex_str. Some old Electrum mnemonic triples decode to 9 hex digits (value >= 2**32), so since 4.6.1 those wallets could not be imported or sign. The patch introduces _is_old_hex_seed() which accepts odd-length hex strings, uses it in _get_hex_seed, stretch_key, and mpk_from_seed, and makes get_seed() raise a UserFacingException when the hex length is not a multiple of 8 (because old_mnemonic.mn_encode cannot encode it). Tests are added for both plaintext and encrypted keystores.
Changed components
electrum/keystore.pyOld_KeyStoreold_mnemonic seed import and signing pathInspect captured patch +54 / −4
### electrum/keystore.py
@@ -24,6 +24,7 @@
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
@@ -44,7 +45,7 @@
from .crypto import (pw_decode, pw_encode, sha256, sha256d, PW_HASH_VERSION_LATEST,
SUPPORTED_PW_HASH_VERSIONS, UnsupportedPasswordHashVersion, hash_160,
CiphertextFormatError)
-from .util import (InvalidPassword, WalletFileException,
+from .util import (InvalidPassword, WalletFileException, UserFacingException,
BitcoinException, bfh, inv_dict, is_hex_str)
from .mnemonic import Mnemonic, Wordlist, calc_seed_type, is_seed
from .plugin import run_hook
@@ -747,6 +748,13 @@ def get_lightning_xprv(self, password) -> str:
node = rootnode.subkey_at_private_derivation("m/67'/")
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)
+
+
class Old_KeyStore(MasterPublicKeyMixin, Deterministic_KeyStore):
type = 'old'
@@ -761,10 +769,10 @@ def watching_only_keystore(self):
return Old_KeyStore({'mpk': self.mpk})
def _get_hex_seed(self, password) -> str:
- if not is_hex_str(self.seed) and password is None:
+ if not _is_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_hex_str(hex_str), f"expected hex str, got {type(hex_str)} with {len(hex_str)=}"
+ assert _is_old_hex_seed(hex_str), f"expected hex str, got {type(hex_str)} with {len(hex_str)=}"
return hex_str
def dump(self):
@@ -803,6 +811,9 @@ def format_seed(self, seed):
def get_seed(self, password):
from . import old_mnemonic
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.")
return ' '.join(old_mnemonic.mn_encode(hex_seed))
@classmethod
@@ -813,7 +824,7 @@ def mpk_from_seed(cls, hex_seed: str) -> str:
@classmethod
def stretch_key(cls, hex_seed: str) -> int:
- assert is_hex_str(hex_seed), f"expected hex str, got {type(hex_seed)} with {len(hex_seed)=}"
+ assert _is_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_wallet_vertical.py
@@ -19,6 +19,7 @@
TxSighashRiskLevel, CannotDoubleSpendTx)
from electrum.util import (
bfh, NotEnoughFunds, UnrelatedTransactionException, UserFacingException, TxMinedInfo, InvalidTxSignature,
+ InvalidPassword,
)
from electrum.fee_policy import FixedFeePolicy
from electrum.transaction import Transaction, PartialTxOutput, tx_from_any, Sighash
@@ -196,6 +197,44 @@ async def test_electrum_seed_old(self):
self.assertEqual(w.get_receiving_addresses()[0], '1FJEEB8ihPMbzs2SkLmr37dHyRFzakqUmo')
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.
+ 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')
+
+ ks = keystore.from_seed(seed_words, passphrase='', for_multisig=False)
+
+ WalletIntegrityHelper.check_seeded_keystore_sanity(self, ks)
+ self.assertTrue(isinstance(ks, keystore.Old_KeyStore))
+
+ self.assertEqual(ks.mpk, '8ecdca16d021e997c2d01fc14d95de1ef4baf28ee2425e67646a769f45f2d8174ecf5e930b600b969dec9e0ceecc01e5cd2b7aea7d70bf2b37ee9a849f90254f')
+ self.assertEqual(ks.seed, seed_hex)
+ with self.assertRaises(UserFacingException):
+ ks.get_seed(password=None)
+
+ w = WalletIntegrityHelper.create_standard_wallet(ks, config=self.config)
+ self.assertEqual(w.txin_type, 'p2pkh')
+
+ self.assertEqual(w.get_receiving_addresses()[0], '1BjZwfcsFcS6NKiLTWZrSCb7AQTiNDtzgK')
+ self.assertEqual(w.get_change_addresses()[0], '14dEHoXTPk67jws7FtsVHfnhVpeonDdXRc')
+
+ async def test_electrum_seed_old_odd_length_hex_encrypted_keystore(self):
+ # keystore of the seed above, as stored by Electrum 4.2.1 with password "secret"
+ ks = keystore.Old_KeyStore({
+ 'mpk': '8ecdca16d021e997c2d01fc14d95de1ef4baf28ee2425e67646a769f45f2d8174ecf5e930b600b969dec9e0ceecc01e5cd2b7aea7d70bf2b37ee9a849f90254f',
+ 'pw_hash_version': 1,
+ 'seed': 'oE+29vgAfW2fxsEeZywAp9nZRZ5+eiBTYwRAZwUL6F6wO1rfKRXai4b+83zupmeFqn8jCvBGJO2+WM+IkGvbfg==',
+ 'seed_type': 'old',
+ 'type': 'old',
+ })
+ with self.assertRaises(InvalidPassword):
+ ks.check_password(None)
+ ks.check_password('secret')
+ pk, compressed = ks.get_private_key((0, 0), 'secret')
+ self.assertEqual('p2pkh:5KT6sPpomFjbRtkgTH3p58trKTJ7NJ79mdmWzNoyWswkapLiiLH',
+ bitcoin.serialize_privkey(pk, compressed, 'p2pkh'))
+
async def test_electrum_seed_2fa_legacy_pre27_25words(self):
# pre-version-2.7 2fa seed, containing 25 words
seed_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'Why this scored 42/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.