Skip to content

Commit 7584ceb

Browse files
committed
bitcoin: stricter check on WIF for compressed pubkeys
fixes #5290
1 parent a6762ff commit 7584ceb

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

electrum/bitcoin.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,13 @@ def deserialize_privkey(key: str) -> Tuple[str, bytes, bool]:
578578

579579
if len(vch) not in [33, 34]:
580580
raise BitcoinException('invalid vch len for WIF key: {}'.format(len(vch)))
581-
compressed = len(vch) == 34
581+
compressed = False
582+
if len(vch) == 34:
583+
if vch[33] == 0x01:
584+
compressed = True
585+
else:
586+
raise BitcoinException(f'invalid WIF key. length suggests compressed pubkey, '
587+
f'but last byte is {vch[33]} != 0x01')
582588

583589
if is_segwit_script_type(txin_type) and not compressed:
584590
raise BitcoinException('only compressed public keys can be used in segwit scripts')

electrum/tests/test_bitcoin.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,12 @@ def test_segwit_uncompressed_pubkey(self):
742742
is_private_key("p2wpkh-p2sh:5JKXxT3wAZHcybJ9YNkuHur9vou6uuAnorBV9A8vVxGNFH5wvTW",
743743
raise_on_error=True)
744744

745+
@needs_test_with_all_ecc_implementations
746+
def test_wif_with_invalid_magic_byte_for_compressed_pubkey(self):
747+
with self.assertRaises(BitcoinException):
748+
is_private_key("KwFAa6AumokBD2dVqQLPou42jHiVsvThY1n25HJ8Ji8REf1wxAQb",
749+
raise_on_error=True)
750+
745751

746752
class TestBaseEncode(SequentialTestCase):
747753

0 commit comments

Comments
 (0)