Buckets:

download
raw
5.41 kB
import asyncio
import hashlib
from collections.abc import AsyncGenerator
import httpx
from loguru import logger
from lnbits.helpers import normalize_endpoint
from lnbits.settings import settings
from .base import (
InvoiceResponse,
PaymentPendingStatus,
PaymentResponse,
PaymentStatus,
StatusResponse,
Wallet,
payment_request_was_rejected,
)
class LNPayWallet(Wallet):
"""https://docs.lnpay.co/"""
def __init__(self):
if not settings.lnpay_api_endpoint:
raise ValueError(
"cannot initialize LNPayWallet: missing lnpay_api_endpoint"
)
if not settings.lnpay_api_key:
raise ValueError("cannot initialize LNPayWallet: missing lnpay_api_key")
super().__init__()
wallet_key = settings.lnpay_wallet_key or settings.lnpay_admin_key
if not wallet_key:
raise ValueError(
"cannot initialize LNPayWallet: "
"missing lnpay_wallet_key or lnpay_admin_key"
)
self.wallet_key = wallet_key
self.endpoint = normalize_endpoint(settings.lnpay_api_endpoint)
headers = {
"X-Api-Key": settings.lnpay_api_key,
"User-Agent": settings.user_agent,
}
self.client = httpx.AsyncClient(base_url=self.endpoint, headers=headers)
async def cleanup(self):
try:
await self.client.aclose()
except RuntimeError as e:
logger.warning(f"Error closing wallet connection: {e}")
async def status(self) -> StatusResponse:
url = f"/wallet/{self.wallet_key}"
try:
r = await self.client.get(url, timeout=60)
except (httpx.ConnectError, httpx.RequestError):
return StatusResponse(f"Unable to connect to '{url}'", 0)
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"
f" {data['statusType']['name']}",
0,
)
return StatusResponse(None, data["balance"] * 1000)
async def create_invoice(
self,
amount: int,
memo: str | None = None,
description_hash: bytes | None = None,
unhashed_description: bytes | None = None,
**_,
) -> InvoiceResponse:
data: dict = {"num_satoshis": f"{amount}"}
if description_hash:
data["description_hash"] = description_hash.hex()
elif unhashed_description:
data["description_hash"] = hashlib.sha256(unhashed_description).hexdigest()
else:
data["memo"] = memo or ""
r = await self.client.post(
f"/wallet/{self.wallet_key}/invoice",
json=data,
timeout=60,
)
if r.status_code == 201:
data = r.json()
self.pending_invoices.append(data["id"])
return InvoiceResponse(
ok=True,
payment_request=data["payment_request"],
)
return InvoiceResponse(
ok=False,
error_message=r.text,
)
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
try:
r = await self.client.post(
f"/wallet/{self.wallet_key}/withdraw",
json={"payment_request": bolt11},
timeout=None,
)
except Exception as exc:
logger.warning(exc)
return PaymentResponse(error_message="Unable to connect to LNPay.")
try:
data = r.json()
except Exception:
return PaymentResponse(error_message="Got invalid JSON.")
if r.is_error:
return PaymentResponse(
ok=False if payment_request_was_rejected(r.status_code) else None,
error_message=data.get("message", r.text),
)
try:
checking_id = data["lnTx"]["id"]
preimage = data["lnTx"]["payment_preimage"]
except (KeyError, TypeError):
return PaymentResponse(
error_message="LNPay response is missing required payment fields."
)
return PaymentResponse(
ok=True, checking_id=checking_id, fee_msat=0, preimage=preimage
)
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
return await self.get_payment_status(checking_id)
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
try:
r = await self.client.get(
url=f"/lntx/{checking_id}",
)
if r.is_error:
return PaymentPendingStatus()
data = r.json()
paid = {0: None, 1: True, -1: False}.get(data.get("settled"))
return PaymentStatus(
paid, data.get("fee_msat"), data.get("payment_preimage")
)
except Exception as exc:
logger.warning(exc)
return PaymentPendingStatus()
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
self.queue: asyncio.Queue = asyncio.Queue(0)
while settings.lnbits_running:
value = await self.queue.get()
yield value

Xet Storage Details

Size:
5.41 kB
·
Xet hash:
b9a46bcb43b7dfc05af56b9daebebe6b94de01effa8ab8b8be6cd7b3eb497e25

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.