diff --git a/src/embit/bip39.py b/src/embit/bip39.py index 418f8b3..a6a8f85 100644 --- a/src/embit/bip39.py +++ b/src/embit/bip39.py @@ -11,7 +11,7 @@ def mnemonic_to_bytes(mnemonic: str, ignore_checksum: bool = False, wordlist=WOR # this function is copied from Jimmy Song's HDPrivateKey.from_mnemonic() method words = mnemonic.strip().split() - if len(words) % 3 != 0 or len(words) < 12: + if len(words) % 3 != 0 or not 12 <= len(words) <= 24: raise ValueError("Invalid recovery phrase") binary_seed = bytearray() @@ -97,7 +97,7 @@ def _extract_index(bits, b, n): def mnemonic_from_bytes(entropy, wordlist=WORDLIST): - if len(entropy) % 4 != 0: + if len(entropy) % 4 != 0 or not 16 <= len(entropy) <= 32: raise ValueError("Byte array should be multiple of 4 long (16, 20, ..., 32)") total_bits = len(entropy) * 8 checksum_bits = total_bits // 32 diff --git a/tests/tests/test_bip39.py b/tests/tests/test_bip39.py index 685cb4e..f3b580d 100644 --- a/tests/tests/test_bip39.py +++ b/tests/tests/test_bip39.py @@ -173,8 +173,24 @@ def test_bip39(self): self.assertEqual(act_xkey.to_base58(), xprv) def test_invalid_length(self): - words = "panel trumpet seek bridge income piano history car flower aim loan accident embark canoe" - self.assertFalse(mnemonic_is_valid(words)) + invalid_length = [ + # not divisible by 3, too short, too long + "panel trumpet seek bridge income piano history car flower aim loan accident embark canoe", + "zoo " * 8 + "zebra", + "zoo " * 26 + "valley", + ] + for words in invalid_length: + self.assertFalse(mnemonic_is_valid(words)) + self.assertRaises(ValueError, mnemonic_to_bytes, words) + + invalid_length = [ + # not divisible by 4, too short, too long + b"\x00" * 19, + b"\x00" * 12, + b"\x00" * 36, + ] + for entropy in invalid_length: + self.assertRaises(ValueError, mnemonic_from_bytes, entropy) def test_invalid_word(self): words = "fljsafk minute glow ride mask ceiling old limb rookie discover cotton biology"