lnurl balanceCheck and balanceNotify.
This commit is contained in:
@@ -3,7 +3,7 @@ import json
|
||||
import lnurl # type: ignore
|
||||
import httpx
|
||||
from urllib.parse import urlparse, urlunparse, urlencode, parse_qs, ParseResult
|
||||
from quart import g, jsonify, make_response
|
||||
from quart import g, jsonify, make_response, url_for
|
||||
from http import HTTPStatus
|
||||
from binascii import unhexlify
|
||||
from typing import Dict, Union
|
||||
@@ -12,6 +12,7 @@ from lnbits import bolt11
|
||||
from lnbits.decorators import api_check_wallet_key, api_validate_post_request
|
||||
|
||||
from .. import core_app, db
|
||||
from ..crud import save_balance_check
|
||||
from ..services import (
|
||||
PaymentFailure,
|
||||
InvoiceFailure,
|
||||
@@ -60,6 +61,7 @@ async def api_payments():
|
||||
"excludes": "memo",
|
||||
},
|
||||
"lnurl_callback": {"type": "string", "nullable": True, "required": False},
|
||||
"lnurl_balance_check": {"type": "string", "required": False},
|
||||
"extra": {"type": "dict", "nullable": True, "required": False},
|
||||
"webhook": {"type": "string", "empty": False, "required": False},
|
||||
}
|
||||
@@ -92,11 +94,22 @@ async def api_payments_create_invoice():
|
||||
|
||||
lnurl_response: Union[None, bool, str] = None
|
||||
if g.data.get("lnurl_callback"):
|
||||
if "lnurl_balance_check" in g.data:
|
||||
save_balance_check(g.wallet.id, g.data["lnurl_balance_check"])
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
r = await client.get(
|
||||
g.data["lnurl_callback"],
|
||||
params={"pr": payment_request},
|
||||
params={
|
||||
"pr": payment_request,
|
||||
"balanceNotify": url_for(
|
||||
"core.lnurl_balance_notify",
|
||||
service=urlparse(g.data["lnurl_callback"]).netloc,
|
||||
wal=g.wallet.id,
|
||||
_external=True,
|
||||
),
|
||||
},
|
||||
timeout=10,
|
||||
)
|
||||
if r.is_error:
|
||||
@@ -387,6 +400,12 @@ async def api_lnurlscan(code: str):
|
||||
parsed_callback: ParseResult = urlparse(data.callback)
|
||||
qs: Dict = parse_qs(parsed_callback.query)
|
||||
qs["k1"] = data.k1
|
||||
|
||||
# balanceCheck/balanceNotify
|
||||
if "balanceCheck" in jdata:
|
||||
params.update(balanceCheck=jdata["balanceCheck"])
|
||||
|
||||
# format callback url and send to client
|
||||
parsed_callback = parsed_callback._replace(query=urlencode(qs, doseq=True))
|
||||
params.update(callback=urlunparse(parsed_callback))
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import trio # type: ignore
|
||||
import httpx
|
||||
from os import path
|
||||
from http import HTTPStatus
|
||||
from quart import (
|
||||
@@ -12,11 +11,10 @@ from quart import (
|
||||
send_from_directory,
|
||||
url_for,
|
||||
)
|
||||
from lnurl import LnurlResponse, LnurlWithdrawResponse, decode as decode_lnurl # type: ignore
|
||||
|
||||
from lnbits.core import core_app, db
|
||||
from lnbits.decorators import check_user_exists, validate_uuids
|
||||
from lnbits.settings import LNBITS_ALLOWED_USERS, SERVICE_FEE
|
||||
from lnbits.settings import LNBITS_ALLOWED_USERS, SERVICE_FEE, LNBITS_SITE_TITLE
|
||||
|
||||
from ..crud import (
|
||||
create_account,
|
||||
@@ -24,8 +22,10 @@ from ..crud import (
|
||||
update_user_extension,
|
||||
create_wallet,
|
||||
delete_wallet,
|
||||
get_balance_check,
|
||||
save_balance_notify,
|
||||
)
|
||||
from ..services import redeem_lnurl_withdraw
|
||||
from ..services import redeem_lnurl_withdraw, pay_invoice
|
||||
|
||||
|
||||
@core_app.route("/favicon.ico")
|
||||
@@ -108,6 +108,62 @@ async def wallet():
|
||||
)
|
||||
|
||||
|
||||
@core_app.route("/withdraw")
|
||||
@validate_uuids(["usr", "wal"], required=True)
|
||||
async def lnurl_full_withdraw():
|
||||
user = await get_user(request.args.get("usr"))
|
||||
if not user:
|
||||
return jsonify({"status": "ERROR", "reason": "User does not exist."})
|
||||
|
||||
wallet = user.get_wallet(request.args.get("wal"))
|
||||
if not wallet:
|
||||
return jsonify({"status": "ERROR", "reason": "Wallet does not exist."})
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"tag": "withdrawRequest",
|
||||
"callback": url_for(
|
||||
"core.lnurl_full_withdraw_callback",
|
||||
usr=user.id,
|
||||
wal=wallet.id,
|
||||
_external=True,
|
||||
),
|
||||
"k1": "0",
|
||||
"minWithdrawable": 1 if wallet.withdrawable_balance else 0,
|
||||
"maxWithdrawable": wallet.withdrawable_balance,
|
||||
"defaultDescription": f"{LNBITS_SITE_TITLE} balance withdraw from {wallet.id[0:5]}",
|
||||
"balanceCheck": url_for(
|
||||
"core.lnurl_full_withdraw", usr=user.id, wal=wallet.id, _external=True
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@core_app.route("/withdraw/cb")
|
||||
@validate_uuids(["usr", "wal"], required=True)
|
||||
async def lnurl_full_withdraw_callback():
|
||||
user = await get_user(request.args.get("usr"))
|
||||
if not user:
|
||||
return jsonify({"status": "ERROR", "reason": "User does not exist."})
|
||||
|
||||
wallet = user.get_wallet(request.args.get("wal"))
|
||||
if not wallet:
|
||||
return jsonify({"status": "ERROR", "reason": "Wallet does not exist."})
|
||||
|
||||
pr = request.args.get("pr")
|
||||
|
||||
async def pay():
|
||||
await pay_invoice(wallet_id=wallet.id, payment_request=pr)
|
||||
|
||||
g.nursery.start_soon(pay)
|
||||
|
||||
balance_notify = request.args.get("balanceNotify")
|
||||
if balance_notify:
|
||||
await save_balance_notify(wallet.id, balance_notify)
|
||||
|
||||
return jsonify({"status": "OK"})
|
||||
|
||||
|
||||
@core_app.route("/deletewallet")
|
||||
@validate_uuids(["usr", "wal"], required=True)
|
||||
@check_user_exists()
|
||||
@@ -127,31 +183,16 @@ async def deletewallet():
|
||||
return redirect(url_for("core.home"))
|
||||
|
||||
|
||||
@core_app.route("/withdraw/notify/<service>")
|
||||
@validate_uuids(["wal"], required=True)
|
||||
async def lnurl_balance_notify(service: str):
|
||||
bc = await get_balance_check(request.args.get("wal"), service)
|
||||
if bc:
|
||||
redeem_lnurl_withdraw(bc.wallet, bc.url)
|
||||
|
||||
|
||||
@core_app.route("/lnurlwallet")
|
||||
async def lnurlwallet():
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
lnurl = decode_lnurl(request.args.get("lightning"))
|
||||
r = await client.get(str(lnurl))
|
||||
withdraw_res = LnurlResponse.from_dict(r.json())
|
||||
|
||||
if not withdraw_res.ok:
|
||||
return (
|
||||
f"Could not process lnurl-withdraw: {withdraw_res.error_msg}",
|
||||
HTTPStatus.BAD_REQUEST,
|
||||
)
|
||||
|
||||
if not isinstance(withdraw_res, LnurlWithdrawResponse):
|
||||
return (
|
||||
f"Expected an lnurl-withdraw code, got {withdraw_res.tag}",
|
||||
HTTPStatus.BAD_REQUEST,
|
||||
)
|
||||
except Exception as exc:
|
||||
return (
|
||||
f"Could not process lnurl-withdraw: {exc}",
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
|
||||
async with db.connect() as conn:
|
||||
account = await create_account(conn=conn)
|
||||
user = await get_user(account.id, conn=conn)
|
||||
@@ -160,7 +201,7 @@ async def lnurlwallet():
|
||||
g.nursery.start_soon(
|
||||
redeem_lnurl_withdraw,
|
||||
wallet.id,
|
||||
withdraw_res,
|
||||
request.args.get("lightning"),
|
||||
"LNbits initial funding: voucher redeem.",
|
||||
)
|
||||
await trio.sleep(3)
|
||||
|
||||
Reference in New Issue
Block a user