Skip to content

Commit

Permalink
fixup!
Browse files Browse the repository at this point in the history
  • Loading branch information
dni committed Aug 5, 2024
1 parent a1ff3b5 commit 4b5558d
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 21 deletions.
7 changes: 5 additions & 2 deletions nostr/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def bech32_create_checksum(hrp, data, spec):
"""Compute the checksum values given HRP and data."""
values = bech32_hrp_expand(hrp) + data
const = BECH32M_CONST if spec == Encoding.BECH32M else 1
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
polymod = bech32_polymod([*values, 0, 0, 0, 0, 0, 0]) ^ const
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]


Expand Down Expand Up @@ -122,6 +122,7 @@ def convertbits(data, frombits, tobits, pad=True):
def decode(hrp, addr):
"""Decode a segwit address."""
hrpgot, data, spec = bech32_decode(addr)
assert data, "Invalid bech32 string"
if hrpgot != hrp:
return (None, None)
decoded = convertbits(data[1:], 5, 8, False)
Expand All @@ -144,7 +145,9 @@ def decode(hrp, addr):
def encode(hrp, witver, witprog):
"""Encode a segwit address."""
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
bits = convertbits(witprog, 8, 5)
assert bits, "Invalid witness program"
ret = bech32_encode(hrp, [witver, *bits], spec)
if decode(hrp, ret) == (None, None):
return None
return ret
24 changes: 16 additions & 8 deletions nostr/key.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import base64
import secrets
from typing import Optional

import secp256k1
from cffi import FFI
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from typing import Optional

from . import bech32
from .event import EncryptedDirectMessage, Event, EventKind
from cffi import FFI
from .event import EncryptedDirectMessage, EventKind


class PublicKey:
Expand All @@ -33,7 +33,9 @@ def from_npub(cls, npub: str):
"""Load a PublicKey from its bech32/npub form"""
hrp, data, spec = bech32.bech32_decode(npub)
assert data, "Invalid npub"
raw_public_key = bech32.convertbits(data, 5, 8)[:-1]
bits = bech32.convertbits(data, 5, 8)
assert bits, "Invalid npub"
raw_public_key = bits[:-1]
return cls(bytes(raw_public_key))


Expand All @@ -45,13 +47,16 @@ def __init__(self, raw_secret: Optional[bytes] = None) -> None:
self.raw_secret = secrets.token_bytes(32)

sk = secp256k1.PrivateKey(self.raw_secret)
assert sk.pubkey, "Invalid public"
self.public_key = PublicKey(sk.pubkey.serialize()[1:])

@classmethod
def from_nsec(cls, nsec: str):
"""Load a PrivateKey from its bech32/nsec form"""
hrp, data, spec = bech32.bech32_decode(nsec)
raw_secret = bech32.convertbits(data, 5, 8)[:-1]
bits = bech32.convertbits(data, 5, 8)
assert bits, "Invalid nsec"
raw_secret = bits[:-1]
return cls(bytes(raw_secret))

def bech32(self) -> str:
Expand Down Expand Up @@ -81,7 +86,8 @@ def encrypt_message(self, message: str, public_key_hex: str) -> str:
encryptor = cipher.encryptor()
encrypted_message = encryptor.update(padded_data) + encryptor.finalize()

return f"{base64.b64encode(encrypted_message).decode()}?iv={base64.b64encode(iv).decode()}"
msg = base64.b64encode(encrypted_message).decode()
return f"{msg}?iv={base64.b64encode(iv).decode()}"

def encrypt_dm(self, dm: EncryptedDirectMessage) -> None:
assert dm.recipient_pubkey, "Recipient public key must be set"
Expand Down Expand Up @@ -113,7 +119,7 @@ def sign_message_hash(self, message_hash: bytes) -> str:
sig = sk.schnorr_sign(message_hash, None, raw=True)
return sig.hex()

def sign_event(self, event: Event) -> None:
def sign_event(self, event: EncryptedDirectMessage) -> None:
if event.kind == EventKind.ENCRYPTED_DIRECT_MESSAGE and event.content is None:
self.encrypt_dm(event)
if event.public_key is None:
Expand All @@ -124,7 +130,9 @@ def __eq__(self, other):
return self.raw_secret == other.raw_secret


def mine_vanity_key(prefix: str = None, suffix: str = None) -> PrivateKey:
def mine_vanity_key(
prefix: Optional[str] = None, suffix: Optional[str] = None
) -> PrivateKey:
if prefix is None and suffix is None:
raise ValueError("Expected at least one of 'prefix' or 'suffix' arguments")

Expand Down
8 changes: 4 additions & 4 deletions nostr/message_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ class RelayMessageType:
END_OF_STORED_EVENTS = "EOSE"

@staticmethod
def is_valid(type: str) -> bool:
def is_valid(relay_type: str) -> bool:
if (
type == RelayMessageType.EVENT
or type == RelayMessageType.NOTICE
or type == RelayMessageType.END_OF_STORED_EVENTS
relay_type == RelayMessageType.EVENT
or relay_type == RelayMessageType.NOTICE
or relay_type == RelayMessageType.END_OF_STORED_EVENTS
):
return True
return False
27 changes: 26 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ pytest = "^7.3.2"
mypy = "^1.5.1"
pre-commit = "^3.2.2"
ruff = "^0.3.2"
types-cffi = "^1.16.0.20240331"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.mypy]
exclude = "(nostr/*)"
# exclude = "(nostr/*)"
[[tool.mypy.overrides]]
module = [
"lnbits.*",
Expand Down Expand Up @@ -49,9 +50,9 @@ line-length = 88
[tool.ruff]
# Same as Black. + 10% rule of black
line-length = 88
exclude = [
"nostr",
]
# exclude = [
# "nostr",
# ]

[tool.ruff.lint]
# Enable:
Expand Down
4 changes: 2 additions & 2 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from .crud import get_or_create_lnurlp_settings, get_pay_link
from .models import PayLink
from .nostr.event import Event
from .nostr.event import EncryptedDirectMessage


async def wait_for_paid_invoices():
Expand Down Expand Up @@ -125,7 +125,7 @@ def get_tag(event_json, tag):
tags.append([t, tag[0]])
tags.append(["bolt11", payment.bolt11])
tags.append(["description", nostr])
zap_receipt = Event(
zap_receipt = EncryptedDirectMessage(
kind=9735, tags=tags, content=payment.extra.get("comment") or ""
)

Expand Down

0 comments on commit 4b5558d

Please sign in to comment.