Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add lnaddress #29

Merged
merged 6 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
7 changes: 5 additions & 2 deletions lnurl/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .exceptions import InvalidLnurl, InvalidUrl, LnurlResponseException
from .helpers import _url_encode
from .models import LnurlAuthResponse, LnurlResponse, LnurlResponseModel
from .types import ClearnetUrl, DebugUrl, Lnurl, OnionUrl
from .types import ClearnetUrl, DebugUrl, LnAddress, Lnurl, OnionUrl


def decode(bech32_lnurl: str) -> Union[OnionUrl, ClearnetUrl, DebugUrl]:
Expand Down Expand Up @@ -41,11 +41,14 @@ def handle(
bech32_lnurl: str, *, response_class: Optional[LnurlResponseModel] = None, verify: Union[str, bool] = True
) -> LnurlResponseModel:
try:
if "@" in bech32_lnurl:
lnaddress = LnAddress(bech32_lnurl)
return get(lnaddress.url, response_class=response_class, verify=verify)
lnurl = Lnurl(bech32_lnurl)
except (ValidationError, ValueError):
raise InvalidLnurl

if lnurl.is_login:
return LnurlAuthResponse(callback=lnurl.url, k1=lnurl.url.query_params["k1"])

return get(lnurl.url, response_class=response_class)
return get(lnurl.url, response_class=response_class, verify=verify)
25 changes: 25 additions & 0 deletions lnurl/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
PositiveInt,
ValidationError,
parse_obj_as,
validator,
)
from pydantic.errors import UrlHostTldError, UrlSchemeError
from pydantic.networks import Parts
Expand Down Expand Up @@ -204,6 +205,30 @@ def is_login(self) -> bool:
return "tag" in self.url.query_params and self.url.query_params["tag"] == "login"


class LnAddress(ReprMixin, str):
"""Lightning address of form `user@host`"""

def __new__(cls, address: str, **_) -> "LnAddress":
return str.__new__(cls, address)

def __init__(self, address: str):
str.__init__(address)
self.address = address
self.url = self.__get_url__(address)

@validator("address")
def is_valid_email_address(cls, email: str) -> bool:
email_regex = r"[A-Za-z0-9\._%+-]+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,63}"
return re.fullmatch(email_regex, email) is not None

@classmethod
def __get_url__(cls, address: str) -> Union[OnionUrl, ClearnetUrl, DebugUrl]:
name_domain = address.split("@")
name, domain = name_domain
url = ("http://" if domain.endswith(".onion") else "https://") + domain + "/.well-known/lnurlp/" + name
return parse_obj_as(Union[OnionUrl, ClearnetUrl, DebugUrl], url) # type: ignore


class LnurlPayMetadata(ReprMixin, str):
valid_metadata_mime_types = {"text/plain", "image/png;base64", "image/jpeg;base64"}

Expand Down
22 changes: 22 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
DebugUrl,
LightningInvoice,
LightningNodeUri,
LnAddress,
Lnurl,
LnurlPayMetadata,
OnionUrl,
Expand Down Expand Up @@ -185,3 +186,24 @@ def test_valid(self, metadata, image_type):
def test_invalid_data(self, metadata):
with pytest.raises(ValidationError):
parse_obj_as(LnurlPayMetadata, metadata)

@pytest.mark.parametrize(
"lnaddress",
[
"donate@legend.lnbits.com",
],
)
def test_valid_lnaddress(self, lnaddress):
lnaddress = LnAddress(lnaddress)
assert isinstance(lnaddress.url, (OnionUrl, DebugUrl, ClearnetUrl))

@pytest.mark.parametrize(
"lnaddress",
[
"legend.lnbits.com",
"donate@donate@legend.lnbits.com",
],
)
def test_invalid_lnaddress(self, lnaddress):
with pytest.raises(ValueError):
lnaddress = LnAddress(lnaddress)
Loading