2020-05-02 19:00:01 +02:00
|
|
|
try:
|
2022-08-01 16:41:50 +02:00
|
|
|
from pyln.client import LightningRpc, RpcError # type: ignore
|
2020-05-02 19:00:01 +02:00
|
|
|
except ImportError: # pragma: nocover
|
|
|
|
LightningRpc = None
|
|
|
|
|
2021-08-30 19:55:02 +02:00
|
|
|
import asyncio
|
2020-05-02 19:00:01 +02:00
|
|
|
import random
|
2021-11-04 19:49:48 +01:00
|
|
|
from functools import partial, wraps
|
|
|
|
from typing import AsyncGenerator, Optional
|
2022-07-16 14:23:03 +02:00
|
|
|
|
2022-08-01 16:41:50 +02:00
|
|
|
from loguru import logger
|
|
|
|
|
2022-07-16 14:23:03 +02:00
|
|
|
from lnbits import bolt11 as lnbits_bolt11
|
2022-10-05 13:01:41 +02:00
|
|
|
from lnbits.settings import settings
|
2020-10-13 03:25:55 +02:00
|
|
|
|
2021-03-24 04:40:32 +01:00
|
|
|
from .base import (
|
|
|
|
InvoiceResponse,
|
|
|
|
PaymentResponse,
|
|
|
|
PaymentStatus,
|
2021-11-04 19:49:48 +01:00
|
|
|
StatusResponse,
|
2021-03-24 04:40:32 +01:00
|
|
|
Unsupported,
|
2021-11-04 19:49:48 +01:00
|
|
|
Wallet,
|
2021-03-24 04:40:32 +01:00
|
|
|
)
|
2020-05-02 19:00:01 +02:00
|
|
|
|
2020-04-03 12:21:10 +02:00
|
|
|
|
2021-11-04 19:49:48 +01:00
|
|
|
def async_wrap(func):
|
|
|
|
@wraps(func)
|
|
|
|
async def run(*args, loop=None, executor=None, **kwargs):
|
|
|
|
if loop is None:
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
partial_func = partial(func, *args, **kwargs)
|
|
|
|
return await loop.run_in_executor(executor, partial_func)
|
|
|
|
|
|
|
|
return run
|
|
|
|
|
|
|
|
|
2022-03-16 07:20:15 +01:00
|
|
|
def _pay_invoice(ln, payload):
|
|
|
|
return ln.call("pay", payload)
|
2021-11-10 22:14:47 +01:00
|
|
|
|
|
|
|
|
2021-11-04 19:49:48 +01:00
|
|
|
def _paid_invoices_stream(ln, last_pay_index):
|
|
|
|
return ln.waitanyinvoice(last_pay_index)
|
|
|
|
|
|
|
|
|
2022-08-01 16:41:50 +02:00
|
|
|
class CoreLightningWallet(Wallet):
|
2020-04-03 12:21:10 +02:00
|
|
|
def __init__(self):
|
2020-05-02 19:00:01 +02:00
|
|
|
if LightningRpc is None: # pragma: nocover
|
2021-03-24 04:40:32 +01:00
|
|
|
raise ImportError(
|
2022-08-01 16:41:50 +02:00
|
|
|
"The `pyln-client` library must be installed to use `CoreLightningWallet`."
|
2021-03-24 04:40:32 +01:00
|
|
|
)
|
2020-05-02 19:00:01 +02:00
|
|
|
|
2022-10-05 13:01:41 +02:00
|
|
|
self.rpc = settings.corelightning_rpc or settings.clightning_rpc
|
2020-10-03 22:27:55 +02:00
|
|
|
self.ln = LightningRpc(self.rpc)
|
2020-10-02 22:13:33 +02:00
|
|
|
|
2022-08-01 16:41:50 +02:00
|
|
|
# check if description_hash is supported (from CLN>=v0.11.0)
|
|
|
|
self.supports_description_hash = (
|
|
|
|
"deschashonly" in self.ln.help("invoice")["help"][0]["command"]
|
|
|
|
)
|
2020-10-02 22:13:33 +02:00
|
|
|
|
|
|
|
# check last payindex so we can listen from that point on
|
|
|
|
self.last_pay_index = 0
|
|
|
|
invoices = self.ln.listinvoices()
|
2020-10-03 22:27:55 +02:00
|
|
|
for inv in invoices["invoices"][::-1]:
|
|
|
|
if "pay_index" in inv:
|
|
|
|
self.last_pay_index = inv["pay_index"]
|
|
|
|
break
|
2020-04-26 13:28:19 +02:00
|
|
|
|
2021-03-24 05:01:09 +01:00
|
|
|
async def status(self) -> StatusResponse:
|
2020-10-13 03:25:55 +02:00
|
|
|
try:
|
|
|
|
funds = self.ln.listfunds()
|
|
|
|
return StatusResponse(
|
2021-10-17 19:33:29 +02:00
|
|
|
None, sum([ch["channel_sat"] * 1000 for ch in funds["channels"]])
|
2020-10-13 03:25:55 +02:00
|
|
|
)
|
|
|
|
except RpcError as exc:
|
|
|
|
error_message = f"lightningd '{exc.method}' failed with '{exc.error}'."
|
|
|
|
return StatusResponse(error_message, 0)
|
|
|
|
|
2021-03-24 05:01:09 +01:00
|
|
|
async def create_invoice(
|
2021-03-24 04:40:32 +01:00
|
|
|
self,
|
|
|
|
amount: int,
|
|
|
|
memo: Optional[str] = None,
|
|
|
|
description_hash: Optional[bytes] = None,
|
2022-08-13 14:29:04 +02:00
|
|
|
unhashed_description: Optional[bytes] = None,
|
2023-01-26 11:08:40 +01:00
|
|
|
**kwargs,
|
2020-08-31 04:48:46 +02:00
|
|
|
) -> InvoiceResponse:
|
2023-01-21 13:38:17 +01:00
|
|
|
label = f"lbl{random.random()}"
|
2022-08-04 17:40:04 +02:00
|
|
|
msat: int = int(amount * 1000)
|
2020-10-02 22:13:33 +02:00
|
|
|
try:
|
2022-08-14 21:59:36 +02:00
|
|
|
if description_hash and not unhashed_description:
|
|
|
|
raise Unsupported(
|
|
|
|
"'description_hash' unsupported by CLN, provide 'unhashed_description'"
|
|
|
|
)
|
2022-08-13 14:29:04 +02:00
|
|
|
if unhashed_description and not self.supports_description_hash:
|
|
|
|
raise Unsupported("unhashed_description")
|
2022-08-01 16:41:50 +02:00
|
|
|
r = self.ln.invoice(
|
|
|
|
msatoshi=msat,
|
|
|
|
label=label,
|
2022-12-29 16:50:05 +01:00
|
|
|
description=unhashed_description.decode()
|
2022-08-13 14:29:04 +02:00
|
|
|
if unhashed_description
|
2022-08-01 16:41:50 +02:00
|
|
|
else memo,
|
|
|
|
exposeprivatechannels=True,
|
|
|
|
deschashonly=True
|
2022-08-13 14:29:04 +02:00
|
|
|
if unhashed_description
|
2022-08-01 16:41:50 +02:00
|
|
|
else False, # we can't pass None here
|
2023-01-26 11:08:40 +01:00
|
|
|
expiry=kwargs.get("expiry"),
|
2022-08-01 16:41:50 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
if r.get("code") and r.get("code") < 0:
|
|
|
|
raise Exception(r.get("message"))
|
|
|
|
|
|
|
|
return InvoiceResponse(True, r["payment_hash"], r["bolt11"], "")
|
2020-10-02 22:13:33 +02:00
|
|
|
except RpcError as exc:
|
2022-08-30 13:28:58 +02:00
|
|
|
error_message = f"CLN method '{exc.method}' failed with '{exc.error.get('message') or exc.error}'."
|
2022-08-01 16:41:50 +02:00
|
|
|
return InvoiceResponse(False, None, None, error_message)
|
|
|
|
except Exception as e:
|
|
|
|
return InvoiceResponse(False, None, None, str(e))
|
2020-04-03 12:21:10 +02:00
|
|
|
|
2022-03-16 07:20:15 +01:00
|
|
|
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
|
|
|
|
invoice = lnbits_bolt11.decode(bolt11)
|
2022-08-30 13:28:58 +02:00
|
|
|
|
|
|
|
previous_payment = await self.get_payment_status(invoice.payment_hash)
|
|
|
|
if previous_payment.paid:
|
|
|
|
return PaymentResponse(False, None, None, None, "invoice already paid")
|
|
|
|
|
2022-03-16 07:20:15 +01:00
|
|
|
fee_limit_percent = fee_limit_msat / invoice.amount_msat * 100
|
|
|
|
|
|
|
|
payload = {
|
|
|
|
"bolt11": bolt11,
|
2023-01-21 13:38:17 +01:00
|
|
|
"maxfeepercent": f"{fee_limit_percent:.11}",
|
2022-08-30 13:28:58 +02:00
|
|
|
"exemptfee": 0, # so fee_limit_percent is applied even on payments with fee < 5000 millisatoshi (which is default value of exemptfee)
|
2022-03-16 07:20:15 +01:00
|
|
|
}
|
2020-10-13 04:18:37 +02:00
|
|
|
try:
|
2021-11-10 22:14:47 +01:00
|
|
|
wrapped = async_wrap(_pay_invoice)
|
2022-03-16 07:20:15 +01:00
|
|
|
r = await wrapped(self.ln, payload)
|
2022-08-30 13:28:58 +02:00
|
|
|
except RpcError as exc:
|
|
|
|
try:
|
|
|
|
error_message = exc.error["attempts"][-1]["fail_reason"]
|
|
|
|
except:
|
|
|
|
error_message = f"CLN method '{exc.method}' failed with '{exc.error.get('message') or exc.error}'."
|
|
|
|
return PaymentResponse(False, None, None, None, error_message)
|
2022-08-01 16:41:50 +02:00
|
|
|
except Exception as exc:
|
2022-08-30 13:28:58 +02:00
|
|
|
return PaymentResponse(False, None, None, None, str(exc))
|
2020-10-13 04:18:37 +02:00
|
|
|
|
2022-08-30 13:28:58 +02:00
|
|
|
fee_msat = -int(r["msatoshi_sent"] - r["msatoshi"])
|
2022-08-01 16:41:50 +02:00
|
|
|
return PaymentResponse(
|
|
|
|
True, r["payment_hash"], fee_msat, r["payment_preimage"], None
|
|
|
|
)
|
2020-04-03 12:21:10 +02:00
|
|
|
|
2021-03-24 05:01:09 +01:00
|
|
|
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
|
2022-08-01 16:51:19 +02:00
|
|
|
try:
|
|
|
|
r = self.ln.listinvoices(payment_hash=checking_id)
|
|
|
|
except:
|
|
|
|
return PaymentStatus(None)
|
2020-08-29 17:23:01 +02:00
|
|
|
if not r["invoices"]:
|
2022-08-01 16:51:19 +02:00
|
|
|
return PaymentStatus(None)
|
2022-08-30 13:28:58 +02:00
|
|
|
|
|
|
|
invoice_resp = r["invoices"][-1]
|
|
|
|
|
|
|
|
if invoice_resp["payment_hash"] == checking_id:
|
|
|
|
if invoice_resp["status"] == "paid":
|
|
|
|
return PaymentStatus(True)
|
|
|
|
elif invoice_resp["status"] == "unpaid":
|
|
|
|
return PaymentStatus(None)
|
|
|
|
logger.warning(f"supplied an invalid checking_id: {checking_id}")
|
|
|
|
return PaymentStatus(None)
|
2020-04-03 12:21:10 +02:00
|
|
|
|
2021-03-24 05:01:09 +01:00
|
|
|
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
|
2022-08-01 16:51:19 +02:00
|
|
|
try:
|
|
|
|
r = self.ln.call("listpays", {"payment_hash": checking_id})
|
|
|
|
except:
|
|
|
|
return PaymentStatus(None)
|
2020-08-29 17:23:01 +02:00
|
|
|
if not r["pays"]:
|
2022-08-01 16:51:19 +02:00
|
|
|
return PaymentStatus(None)
|
2022-08-30 13:28:58 +02:00
|
|
|
payment_resp = r["pays"][-1]
|
|
|
|
|
|
|
|
if payment_resp["payment_hash"] == checking_id:
|
|
|
|
status = payment_resp["status"]
|
2020-08-29 17:23:01 +02:00
|
|
|
if status == "complete":
|
2022-08-30 13:28:58 +02:00
|
|
|
fee_msat = -int(
|
|
|
|
payment_resp["amount_sent_msat"] - payment_resp["amount_msat"]
|
|
|
|
)
|
|
|
|
|
|
|
|
return PaymentStatus(True, fee_msat, payment_resp["preimage"])
|
2020-08-29 17:23:01 +02:00
|
|
|
elif status == "failed":
|
|
|
|
return PaymentStatus(False)
|
2020-04-26 13:28:19 +02:00
|
|
|
return PaymentStatus(None)
|
2022-08-30 13:28:58 +02:00
|
|
|
logger.warning(f"supplied an invalid checking_id: {checking_id}")
|
|
|
|
return PaymentStatus(None)
|
2020-10-02 22:13:33 +02:00
|
|
|
|
|
|
|
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
|
|
|
while True:
|
2022-08-01 16:41:50 +02:00
|
|
|
try:
|
|
|
|
wrapped = async_wrap(_paid_invoices_stream)
|
|
|
|
paid = await wrapped(self.ln, self.last_pay_index)
|
|
|
|
self.last_pay_index = paid["pay_index"]
|
|
|
|
yield paid["payment_hash"]
|
|
|
|
except Exception as exc:
|
|
|
|
logger.error(
|
|
|
|
f"lost connection to cln invoices stream: '{exc}', retrying in 5 seconds"
|
|
|
|
)
|
|
|
|
await asyncio.sleep(5)
|