diff --git a/src/embit/bip39.py b/src/embit/bip39.py index 418f8b3..7ffd4d1 100644 --- a/src/embit/bip39.py +++ b/src/embit/bip39.py @@ -10,7 +10,7 @@ def mnemonic_to_bytes(mnemonic: str, ignore_checksum: bool = False, wordlist=WORDLIST): # this function is copied from Jimmy Song's HDPrivateKey.from_mnemonic() method - words = mnemonic.strip().split() + words = mnemonic.split(" ") if len(words) % 3 != 0 or len(words) < 12: raise ValueError("Invalid recovery phrase") @@ -68,7 +68,7 @@ def mnemonic_is_valid(mnemonic: str, wordlist=WORDLIST): try: mnemonic_to_bytes(mnemonic, wordlist=wordlist) return True - except Exception as e: + except Exception: return False diff --git a/tests/tests/test_bip39.py b/tests/tests/test_bip39.py index 685cb4e..dc527e3 100644 --- a/tests/tests/test_bip39.py +++ b/tests/tests/test_bip39.py @@ -190,6 +190,21 @@ def test_invalid_seed(self): seed = "0000000000000000000000000000000042" self.assertRaises(ValueError, lambda x: mnemonic_from_bytes(unhexlify(x)), seed) + def test_spaces(self): + """Test that mnemonic with leading / trailing / double spaces are invalid.""" + # valid mnemonic + mnemonic = "abandon " * 11 + "about" + self.assertTrue(mnemonic_is_valid(mnemonic)) + # leading / trailing space + self.assertFalse(mnemonic_is_valid(" " + mnemonic)) + self.assertFalse(mnemonic_is_valid(mnemonic + " ")) + # double space + mnemonic = "abandon " * 11 + " about" + self.assertFalse(mnemonic_is_valid(mnemonic)) + # new line instead of space + mnemonic = "abandon\n" * 11 + "about" + self.assertFalse(mnemonic_is_valid(mnemonic)) + def test_find_candidates_happy(self): prefix = "a" exp_candidates = [