2020-09-29 05:52:27 +02:00
|
|
|
import json
|
2020-10-04 02:57:14 +02:00
|
|
|
import trio # type: ignore
|
2020-09-30 03:04:51 +02:00
|
|
|
import httpx
|
2020-03-31 19:05:25 +02:00
|
|
|
from os import getenv
|
2020-09-29 05:52:27 +02:00
|
|
|
from http import HTTPStatus
|
2020-09-28 04:12:55 +02:00
|
|
|
from typing import Optional, Dict, AsyncGenerator
|
|
|
|
from quart import request
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-10-13 03:25:55 +02:00
|
|
|
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
|
2020-01-18 11:24:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
class LNPayWallet(Wallet):
|
|
|
|
"""https://docs.lnpay.co/"""
|
|
|
|
|
2020-03-31 19:05:25 +02:00
|
|
|
def __init__(self):
|
2020-10-02 22:13:33 +02:00
|
|
|
endpoint = getenv("LNPAY_API_ENDPOINT", "https://lnpay.co/v1")
|
2020-01-18 11:24:22 +01:00
|
|
|
self.endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
|
2020-10-08 21:03:18 +02:00
|
|
|
self.wallet_key = getenv("LNPAY_WALLET_KEY") or getenv("LNPAY_ADMIN_KEY")
|
|
|
|
self.auth = {"X-Api-Key": getenv("LNPAY_API_KEY")}
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-10-13 03:25:55 +02:00
|
|
|
def status(self) -> StatusResponse:
|
|
|
|
url = f"{self.endpoint}/wallet/{self.wallet_key}"
|
|
|
|
try:
|
2020-10-14 01:37:39 +02:00
|
|
|
r = httpx.get(url, headers=self.auth, timeout=60)
|
2020-10-13 03:25:55 +02:00
|
|
|
except (httpx.ConnectError, httpx.RequestError):
|
2020-10-13 19:46:23 +02:00
|
|
|
return StatusResponse(f"Unable to connect to '{url}'", 0)
|
2020-10-13 03:25:55 +02:00
|
|
|
|
|
|
|
if r.is_error:
|
|
|
|
return StatusResponse(r.text[:250], 0)
|
|
|
|
|
|
|
|
data = r.json()
|
|
|
|
if data["statusType"]["name"] != "active":
|
|
|
|
return StatusResponse(
|
|
|
|
f"Wallet {data['user_label']} (data['id']) not active, but {data['statusType']['name']}", 0
|
|
|
|
)
|
|
|
|
|
2020-10-13 18:57:26 +02:00
|
|
|
return StatusResponse(None, data["balance"] * 1000)
|
2020-10-13 03:25:55 +02:00
|
|
|
|
2020-08-31 04:48:46 +02:00
|
|
|
def create_invoice(
|
2020-09-28 04:12:55 +02:00
|
|
|
self,
|
|
|
|
amount: int,
|
|
|
|
memo: Optional[str] = None,
|
|
|
|
description_hash: Optional[bytes] = None,
|
2020-08-31 04:48:46 +02:00
|
|
|
) -> InvoiceResponse:
|
|
|
|
data: Dict = {"num_satoshis": f"{amount}"}
|
|
|
|
if description_hash:
|
|
|
|
data["description_hash"] = description_hash.hex()
|
|
|
|
else:
|
|
|
|
data["memo"] = memo or ""
|
|
|
|
|
2020-10-02 22:13:33 +02:00
|
|
|
r = httpx.post(
|
2020-10-13 03:25:55 +02:00
|
|
|
f"{self.endpoint}/wallet/{self.wallet_key}/invoice",
|
2020-10-08 21:03:18 +02:00
|
|
|
headers=self.auth,
|
2020-09-03 23:02:15 +02:00
|
|
|
json=data,
|
2020-10-14 01:37:39 +02:00
|
|
|
timeout=60,
|
2020-09-03 23:02:15 +02:00
|
|
|
)
|
2020-09-28 04:12:55 +02:00
|
|
|
ok, checking_id, payment_request, error_message = (
|
|
|
|
r.status_code == 201,
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
r.text,
|
|
|
|
)
|
2020-01-31 21:07:05 +01:00
|
|
|
|
2020-03-31 19:05:25 +02:00
|
|
|
if ok:
|
2020-01-18 11:24:22 +01:00
|
|
|
data = r.json()
|
2020-03-31 19:05:25 +02:00
|
|
|
checking_id, payment_request = data["id"], data["payment_request"]
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-03-31 19:05:25 +02:00
|
|
|
return InvoiceResponse(ok, checking_id, payment_request, error_message)
|
2020-01-18 11:24:22 +01:00
|
|
|
|
|
|
|
def pay_invoice(self, bolt11: str) -> PaymentResponse:
|
2020-10-02 22:13:33 +02:00
|
|
|
r = httpx.post(
|
2020-10-14 01:37:39 +02:00
|
|
|
f"{self.endpoint}/wallet/{self.wallet_key}/withdraw",
|
2020-10-08 21:03:18 +02:00
|
|
|
headers=self.auth,
|
2020-01-31 21:07:05 +01:00
|
|
|
json={"payment_request": bolt11},
|
2020-10-14 01:37:39 +02:00
|
|
|
timeout=180,
|
2020-01-31 21:07:05 +01:00
|
|
|
)
|
2020-03-31 19:05:25 +02:00
|
|
|
|
2020-10-13 04:18:37 +02:00
|
|
|
try:
|
|
|
|
data = r.json()
|
|
|
|
except:
|
|
|
|
return PaymentResponse(False, None, 0, None, f"Got invalid JSON: {r.text[:200]}")
|
|
|
|
|
|
|
|
if r.is_error:
|
|
|
|
return PaymentResponse(False, None, 0, None, data["message"])
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-10-13 04:18:37 +02:00
|
|
|
checking_id = data["lnTx"]["id"]
|
|
|
|
fee_msat = 0
|
|
|
|
preimage = data["lnTx"]["payment_preimage"]
|
|
|
|
return PaymentResponse(True, checking_id, fee_msat, preimage, None)
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-03-31 19:05:25 +02:00
|
|
|
def get_invoice_status(self, checking_id: str) -> PaymentStatus:
|
|
|
|
return self.get_payment_status(checking_id)
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-03-31 19:05:25 +02:00
|
|
|
def get_payment_status(self, checking_id: str) -> PaymentStatus:
|
2020-10-02 22:13:33 +02:00
|
|
|
r = httpx.get(
|
2020-10-13 03:25:55 +02:00
|
|
|
url=f"{self.endpoint}/lntx/{checking_id}?fields=settled",
|
2020-10-08 21:03:18 +02:00
|
|
|
headers=self.auth,
|
2020-09-28 04:12:55 +02:00
|
|
|
)
|
2020-01-18 11:24:22 +01:00
|
|
|
|
2020-10-02 22:13:33 +02:00
|
|
|
if r.is_error:
|
2020-03-31 19:05:25 +02:00
|
|
|
return PaymentStatus(None)
|
2020-01-18 11:24:22 +01:00
|
|
|
|
|
|
|
statuses = {0: None, 1: True, -1: False}
|
2020-03-31 19:05:25 +02:00
|
|
|
return PaymentStatus(statuses[r.json()["settled"]])
|
2020-09-28 04:12:55 +02:00
|
|
|
|
|
|
|
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
2020-10-04 02:57:14 +02:00
|
|
|
self.send, receive = trio.open_memory_channel(0)
|
|
|
|
async for value in receive:
|
|
|
|
yield value
|
2020-09-28 04:12:55 +02:00
|
|
|
|
|
|
|
async def webhook_listener(self):
|
2020-09-29 05:52:27 +02:00
|
|
|
text: str = await request.get_data()
|
2020-11-12 19:33:02 +01:00
|
|
|
try:
|
|
|
|
data = json.loads(text)
|
|
|
|
except json.decoder.JSONDecodeError:
|
|
|
|
print(f"got something wrong on lnpay webhook endpoint: {text[:200]}")
|
|
|
|
data = None
|
2020-09-29 05:52:27 +02:00
|
|
|
if type(data) is not dict or "event" not in data or data["event"].get("name") != "wallet_receive":
|
|
|
|
return "", HTTPStatus.NO_CONTENT
|
2020-09-28 04:12:55 +02:00
|
|
|
|
|
|
|
lntx_id = data["data"]["wtx"]["lnTx"]["id"]
|
2020-09-30 03:04:51 +02:00
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
r = await client.get(
|
2020-10-13 03:25:55 +02:00
|
|
|
f"{self.endpoint}/lntx/{lntx_id}?fields=settled",
|
2020-10-08 21:03:18 +02:00
|
|
|
headers=self.auth,
|
2020-09-29 05:52:27 +02:00
|
|
|
)
|
2020-09-30 03:04:51 +02:00
|
|
|
data = r.json()
|
2020-09-29 05:52:27 +02:00
|
|
|
if data["settled"]:
|
2020-10-04 05:22:37 +02:00
|
|
|
await self.send.send(lntx_id)
|
2020-09-29 05:52:27 +02:00
|
|
|
|
|
|
|
return "", HTTPStatus.NO_CONTENT
|