jeffthibault / python-nostr

A Python library for Nostr
MIT License
274 stars 87 forks source link

Issue with npub key signing for DM messages #101

Open proofofjogi opened 1 year ago

proofofjogi commented 1 year ago

Using the current code of this fork, signing DMs does not work for me.

This code:

from nostr.key import PrivateKey

# generate a key
private_key = PrivateKey()
public_key = private_key.public_key

# removed for privacy
npub = 'npub....'

# prepare message
dm = EncryptedDirectMessage(
  recipient_pubkey=npub,
  cleartext_content="DM"
)
# sign message
private_key.sign_event(dm)

Causes this:

    private_key.sign_event(dm)
  File "/home/user/nostr-message/env/lib/python3.10/site-packages/nostr/key.py", line 113, in sign_event
    self.encrypt_dm(event)
  File "/home/user/nostr-message/env/lib/python3.10/site-packages/nostr/key.py", line 84, in encrypt_dm
    dm.content = self.encrypt_message(
  File "/home/user/nostr-message/env/lib/python3.10/site-packages/nostr/key.py", line 75, in encrypt_message
    algorithms.AES(self.compute_shared_secret(public_key_hex)), modes.CBC(iv)
  File "/home/user/nostr-message/env/lib/python3.10/site-packages/nostr/key.py", line 66, in compute_shared_secret
    pk = secp256k1.PublicKey(bytes.fromhex("02" + public_key_hex), True)
ValueError: non-hexadecimal number found in fromhex() arg at position 2

To investigate a little, I printed public_key_hex above line 66, in nostr/key.py and it prints as npub.... The first two characters, np are not hex characters, so the string public_key_hex is not hex compatible.

What I suspect would fix this is that the npub needs to be converted into the hex pubkey before line 66 is happening but that's a little above my skill level to implement