lnbits-legend/lnbits/wallets/clightning.py

46 lines
1.8 KiB
Python
Raw Normal View History

try:
from lightning import LightningRpc # type: ignore
except ImportError: # pragma: nocover
LightningRpc = None
import random
2020-04-03 11:27:36 +01:00
from os import getenv
2020-04-03 11:21:10 +01:00
from .base import InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
2020-04-03 11:21:10 +01:00
class CLightningWallet(Wallet):
def __init__(self):
if LightningRpc is None: # pragma: nocover
raise ImportError("The `pylightning` library must be installed to use `CLightningWallet`.")
2020-04-03 11:48:41 +01:00
self.l1 = LightningRpc(getenv("CLIGHTNING_RPC"))
2020-04-26 13:28:19 +02:00
2020-04-03 11:21:10 +01:00
def create_invoice(self, amount: int, memo: str = "") -> InvoiceResponse:
2020-04-26 13:28:19 +02:00
label = "lbl{}".format(random.random())
2020-04-03 11:48:41 +01:00
r = self.l1.invoice(amount*1000, label, memo, exposeprivatechannels=True)
2020-04-03 11:21:10 +01:00
ok, checking_id, payment_request, error_message = True, r["payment_hash"], r["bolt11"], None
return InvoiceResponse(ok, checking_id, payment_request, error_message)
def pay_invoice(self, bolt11: str) -> PaymentResponse:
2020-04-03 11:48:41 +01:00
r = self.l1.pay(bolt11)
2020-04-26 13:28:19 +02:00
ok, checking_id, fee_msat, error_message = True, None, 0, None
2020-04-03 11:21:10 +01:00
return PaymentResponse(ok, checking_id, fee_msat, error_message)
def get_invoice_status(self, checking_id: str) -> PaymentStatus:
2020-04-03 11:48:41 +01:00
r = self.l1.listinvoices(checking_id)
2020-04-03 11:21:10 +01:00
if r['invoices'][0]['status'] == 'unpaid':
return PaymentStatus(False)
return PaymentStatus(True)
def get_payment_status(self, checking_id: str) -> PaymentStatus:
2020-04-03 11:48:41 +01:00
r = self.l1.listsendpays(checking_id)
2020-04-03 11:21:10 +01:00
if not r.ok:
2020-04-26 13:28:19 +02:00
return PaymentStatus(None)
payments = [p for p in r.json()["payments"] if p["payment_hash"] == checking_id]
2020-04-03 11:21:10 +01:00
payment = payments[0] if payments else None
statuses = {"UNKNOWN": None, "IN_FLIGHT": None, "SUCCEEDED": True, "FAILED": False}
return PaymentStatus(statuses[payment["status"]] if payment else None)