Skip to content

Commit

Permalink
Allow instantiation of PublicKey from bech32/npub format
Browse files Browse the repository at this point in the history
  • Loading branch information
siavashg committed Dec 30, 2022
1 parent 67b815b commit 3f41cc7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
11 changes: 9 additions & 2 deletions nostr/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ class PublicKey:
def __init__(self, raw_bytes: bytes) -> None:
self.raw_bytes = raw_bytes

@classmethod
def from_npub(cls, npub: str):
"""Load a PublicKey from its bech32/npub form"""
hrp, data, spec = bech32.bech32_decode(npub)
raw_public = bech32.convertbits(data, 5, 8)[:-1]
return cls(bytes(raw_public))

def bech32(self) -> str:
converted_bits = bech32.convertbits(self.raw_bytes, 8, 5)
return bech32.bech32_encode("npub", converted_bits, bech32.Encoding.BECH32)
Expand Down Expand Up @@ -85,7 +92,7 @@ def sign_message_hash(self, hash: bytes) -> str:
sk = secp256k1.PrivateKey(self.raw_secret)
sig = sk.schnorr_sign(hash, None, raw=True)
return sig.hex()

def __eq__(self, other):
return self.raw_secret == other.raw_secret

Expand All @@ -94,4 +101,4 @@ def __eq__(self, other):
@ffi.callback("int (unsigned char *, const unsigned char *, const unsigned char *, void *)")
def copy_x(output, x32, y32, data):
ffi.memmove(output, x32, 32)
return 1
return 1
8 changes: 7 additions & 1 deletion test/test_key.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from nostr.key import PrivateKey
from nostr.key import PrivateKey, PublicKey


def test_eq_true():
Expand All @@ -21,3 +21,9 @@ def test_from_nsec():
pk1 = PrivateKey()
pk2 = PrivateKey.from_nsec(pk1.bech32())
assert pk1.raw_secret == pk2.raw_secret

def test_from_npub():
""" PublicKey.from_npub should yield the source's raw_bytes """
pk1 = PrivateKey()
pk2 = PublicKey.from_npub(pk1.public_key.bech32())
assert pk1.public_key.raw_bytes == pk2.raw_bytes

0 comments on commit 3f41cc7

Please sign in to comment.