Skip to content

Commit 3f41cc7

Browse files
committed
Allow instantiation of PublicKey from bech32/npub format
1 parent 67b815b commit 3f41cc7

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

nostr/key.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ class PublicKey:
1010
def __init__(self, raw_bytes: bytes) -> None:
1111
self.raw_bytes = raw_bytes
1212

13+
@classmethod
14+
def from_npub(cls, npub: str):
15+
"""Load a PublicKey from its bech32/npub form"""
16+
hrp, data, spec = bech32.bech32_decode(npub)
17+
raw_public = bech32.convertbits(data, 5, 8)[:-1]
18+
return cls(bytes(raw_public))
19+
1320
def bech32(self) -> str:
1421
converted_bits = bech32.convertbits(self.raw_bytes, 8, 5)
1522
return bech32.bech32_encode("npub", converted_bits, bech32.Encoding.BECH32)
@@ -85,7 +92,7 @@ def sign_message_hash(self, hash: bytes) -> str:
8592
sk = secp256k1.PrivateKey(self.raw_secret)
8693
sig = sk.schnorr_sign(hash, None, raw=True)
8794
return sig.hex()
88-
95+
8996
def __eq__(self, other):
9097
return self.raw_secret == other.raw_secret
9198

@@ -94,4 +101,4 @@ def __eq__(self, other):
94101
@ffi.callback("int (unsigned char *, const unsigned char *, const unsigned char *, void *)")
95102
def copy_x(output, x32, y32, data):
96103
ffi.memmove(output, x32, 32)
97-
return 1
104+
return 1

test/test_key.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from nostr.key import PrivateKey
1+
from nostr.key import PrivateKey, PublicKey
22

33

44
def test_eq_true():
@@ -21,3 +21,9 @@ def test_from_nsec():
2121
pk1 = PrivateKey()
2222
pk2 = PrivateKey.from_nsec(pk1.bech32())
2323
assert pk1.raw_secret == pk2.raw_secret
24+
25+
def test_from_npub():
26+
""" PublicKey.from_npub should yield the source's raw_bytes """
27+
pk1 = PrivateKey()
28+
pk2 = PublicKey.from_npub(pk1.public_key.bech32())
29+
assert pk1.public_key.raw_bytes == pk2.raw_bytes

0 commit comments

Comments
 (0)