diff --git a/electrum/bitcoin.py b/electrum/bitcoin.py index 3017dd3d4..3917e2d87 100644 --- a/electrum/bitcoin.py +++ b/electrum/bitcoin.py @@ -578,7 +578,13 @@ def deserialize_privkey(key: str) -> Tuple[str, bytes, bool]: if len(vch) not in [33, 34]: raise BitcoinException('invalid vch len for WIF key: {}'.format(len(vch))) - compressed = len(vch) == 34 + compressed = False + if len(vch) == 34: + if vch[33] == 0x01: + compressed = True + else: + raise BitcoinException(f'invalid WIF key. length suggests compressed pubkey, ' + f'but last byte is {vch[33]} != 0x01') if is_segwit_script_type(txin_type) and not compressed: raise BitcoinException('only compressed public keys can be used in segwit scripts') diff --git a/electrum/tests/test_bitcoin.py b/electrum/tests/test_bitcoin.py index 101ec1b62..f6edb51dd 100644 --- a/electrum/tests/test_bitcoin.py +++ b/electrum/tests/test_bitcoin.py @@ -742,6 +742,12 @@ class Test_keyImport(SequentialTestCase): is_private_key("p2wpkh-p2sh:5JKXxT3wAZHcybJ9YNkuHur9vou6uuAnorBV9A8vVxGNFH5wvTW", raise_on_error=True) + @needs_test_with_all_ecc_implementations + def test_wif_with_invalid_magic_byte_for_compressed_pubkey(self): + with self.assertRaises(BitcoinException): + is_private_key("KwFAa6AumokBD2dVqQLPou42jHiVsvThY1n25HJ8Ji8REf1wxAQb", + raise_on_error=True) + class TestBaseEncode(SequentialTestCase):