Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions electrum/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,26 @@ def has_uncompressed_pubkey(self) -> bool:
return False
return b"\x04" == self.get_pubkey_bytes()[:1]

def validate_pubkey(self, *, permit_uncompressed: bool, is_taproot: bool) -> None:
"""Check that a raw-hex pubkey is a valid public key for its context.

A full compressed or uncompressed point is accepted everywhere; a
32-byte x-only point is additionally accepted inside tr(). An
uncompressed point is rejected where the context forbids it. Keys
derived from an extended key are valid by construction and need no
point check.
"""
if self.extkey is None:
data = unhexlify(self.pubkey)
if len(data) in (33, 65) and data[0] in (2, 3, 4) and ecc.ECPubkey.is_pubkey_bytes(data):
pass # compressed or uncompressed point; hybrid prefixes 0x06/0x07 are rejected, as in Core
elif len(data) == 32 and is_taproot and ecc.ECPubkey.is_pubkey_bytes(b"\x02" + data):
pass # x-only point (even y), BIP340
else:
raise ValueError(f"invalid public key in descriptor: {self.pubkey!r}")
if not permit_uncompressed and self.has_uncompressed_pubkey():
raise ValueError("uncompressed pubkeys are not allowed")


class Descriptor(object):
r"""
Expand Down Expand Up @@ -898,8 +918,8 @@ def parse_pubkey(expr: str, *, ctx: '_ParseDescriptorContext') -> Tuple['PubkeyP
next_expr = expr[end + 1:]
pubkey_provider = PubkeyProvider.parse(expr[:end])
permit_uncompressed = ctx in (_ParseDescriptorContext.TOP, _ParseDescriptorContext.P2SH)
if not permit_uncompressed and pubkey_provider.has_uncompressed_pubkey():
raise ValueError("uncompressed pubkeys are not allowed")
is_taproot = ctx == _ParseDescriptorContext.P2TR
pubkey_provider.validate_pubkey(permit_uncompressed=permit_uncompressed, is_taproot=is_taproot)
return pubkey_provider, next_expr


Expand Down Expand Up @@ -983,7 +1003,7 @@ def _parse_descriptor(desc: str, *, ctx: '_ParseDescriptorContext') -> 'Descript
if func == "tr":
if ctx != _ParseDescriptorContext.TOP:
raise ValueError("Can only have tr at top level")
internal_key, expr = parse_pubkey(expr, ctx=ctx)
internal_key, expr = parse_pubkey(expr, ctx=_ParseDescriptorContext.P2TR)
desc_tree = []
if expr:
def parse_tree(tree_str):
Expand Down
47 changes: 47 additions & 0 deletions tests/test_descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,53 @@ def test_tr_descriptor_bip386(self):
"512017cf18db381d836d8923b1bdb246cfcd818da1a9f0e6e7907f187f0b2f937754",
parse_descriptor("tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,pk(669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))").expand().output_script.hex())

@as_testnet
def test_reject_invalid_raw_pubkey(self):
valid_compressed = "02c97dc3f4420402e01a113984311bf4a1b8de376cac0bdcfaf1b3ac81f13433c7"
valid_xonly = "a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd"
# valid keys still parse in their proper context
self.assertIsInstance(parse_descriptor(f"pkh({valid_compressed})"), PKHDescriptor)
self.assertIsInstance(parse_descriptor(f"wpkh({valid_compressed})"), WPKHDescriptor)
self.assertIsInstance(parse_descriptor(f"tr({valid_xonly})"), TRDescriptor)
self.assertIsInstance(
parse_descriptor(f"tr({valid_xonly},pk({valid_xonly}))"), TRDescriptor)
# off-curve, wrong-length and bad-prefix keys are rejected outside tr()
off_curve = "02" + "ff" * 32
wrong_length = valid_compressed + "ab"
bad_prefix = "05" + valid_compressed[2:]
for bad in (off_curve, wrong_length, bad_prefix):
with self.assertRaises(ValueError):
parse_descriptor(f"pkh({bad})")
with self.assertRaises(ValueError):
parse_descriptor(f"wpkh({bad})")
# off-curve x-only key rejected inside tr(), both as internal key and leaf key
off_curve_xonly = "ff" * 32
with self.assertRaises(ValueError):
parse_descriptor(f"tr({off_curve_xonly})")
with self.assertRaises(ValueError):
parse_descriptor(f"tr({valid_xonly},pk({off_curve_xonly}))")
# a wrong-length key is rejected inside tr() too
with self.assertRaises(ValueError):
parse_descriptor(f"tr({wrong_length})")
# a 32-byte x-only key is not a valid full key outside tr()
with self.assertRaises(ValueError):
parse_descriptor(f"pkh({valid_xonly})")
# inside tr() a valid 33-byte compressed key is accepted (later reduced
# to x-only), matching Bitcoin Core, as internal key and as leaf key
self.assertIsInstance(parse_descriptor(f"tr({valid_compressed})"), TRDescriptor)
self.assertIsInstance(
parse_descriptor(f"tr({valid_xonly},pk({valid_compressed}))"), TRDescriptor)
# a 65-byte uncompressed key is not allowed inside tr()
valid_uncompressed = (
"04a0507c8bb3d96dfd7731bafb0ae30e6ed10bbadd6a9f9f88eaf0602b9cc99adc"
"3ccfc29410b8f23c15d88413a6b88c8cd44b016a7f1dd91a8d64c3107c6bce1a")
with self.assertRaises(ValueError):
parse_descriptor(f"tr({valid_uncompressed})")
# a hybrid-encoded key (a valid point, non-canonical prefix) is rejected
hybrid = "06" + valid_uncompressed[2:]
with self.assertRaises(ValueError):
parse_descriptor(f"pkh({hybrid})")

@as_testnet
def test_parse_descriptor_with_range(self):
d = "wpkh([00000001/84h/1h/0h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/0/*)"
Expand Down