lnbits-legend/lnbits/wallets/eclair.py

228 lines
6.8 KiB
Python
Raw Normal View History

2022-04-29 11:39:27 +01:00
import asyncio
import base64
import hashlib
2021-06-23 16:13:48 +01:00
import json
import urllib.parse
from typing import Any, AsyncGenerator, Dict, Optional
2022-04-29 11:39:27 +01:00
import httpx
2022-07-16 14:23:03 +02:00
from loguru import logger
from websockets.client import connect
2021-06-23 16:13:48 +01:00
2022-12-02 14:52:31 +00:00
from lnbits.settings import settings
2021-06-23 16:13:48 +01:00
from .base import (
InvoiceResponse,
PaymentResponse,
PaymentStatus,
2022-04-29 11:39:27 +01:00
StatusResponse,
2021-06-23 16:13:48 +01:00
Wallet,
)
2022-04-29 11:39:27 +01:00
2021-06-23 16:13:48 +01:00
class EclairError(Exception):
pass
class UnknownError(Exception):
pass
2022-06-01 14:53:05 +02:00
2021-06-23 16:13:48 +01:00
class EclairWallet(Wallet):
def __init__(self):
2022-10-05 13:01:41 +02:00
url = settings.eclair_url
passw = settings.eclair_pass
if not url or not passw:
raise Exception("cannot initialize eclair")
2021-06-23 16:13:48 +01:00
self.url = url[:-1] if url.endswith("/") else url
2022-05-05 15:44:34 +01:00
self.ws_url = f"ws://{urllib.parse.urlsplit(self.url).netloc}/ws"
encodedAuth = base64.b64encode(f":{passw}".encode())
2021-06-23 16:13:48 +01:00
auth = str(encodedAuth, "utf-8")
self.auth = {"Authorization": f"Basic {auth}"}
self.client = httpx.AsyncClient(base_url=self.url, headers=self.auth)
async def cleanup(self):
await self.client.aclose()
2021-06-23 16:13:48 +01:00
async def status(self) -> StatusResponse:
r = await self.client.post("/globalbalance", timeout=5)
2021-06-23 16:13:48 +01:00
try:
2022-05-05 15:44:34 +01:00
data = r.json()
except:
return StatusResponse(
f"Failed to connect to {self.url}, got: '{r.text[:200]}...'", 0
)
2022-06-01 14:53:05 +02:00
2022-05-05 15:44:34 +01:00
if r.is_error:
return StatusResponse(data.get("error") or "undefined error", 0)
if len(data) == 0:
return StatusResponse("no data", 0)
2022-05-05 15:44:34 +01:00
return StatusResponse(None, int(data.get("total") * 100_000_000_000))
2021-06-23 16:13:48 +01:00
async def create_invoice(
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
unhashed_description: Optional[bytes] = None,
**kwargs,
2021-06-23 16:13:48 +01:00
) -> InvoiceResponse:
data: Dict[str, Any] = {
"amountMsat": amount * 1000,
}
if kwargs.get("expiry"):
data["expireIn"] = kwargs["expiry"]
# Either 'description' (string) or 'descriptionHash' must be supplied
2021-06-23 16:13:48 +01:00
if description_hash:
data["descriptionHash"] = description_hash.hex()
elif unhashed_description:
data["descriptionHash"] = hashlib.sha256(unhashed_description).hexdigest()
else:
data["description"] = memo
2022-05-05 15:44:34 +01:00
r = await self.client.post("/createinvoice", data=data, timeout=40)
2022-05-05 15:44:34 +01:00
if r.is_error:
try:
data = r.json()
error_message = data["error"]
except:
error_message = r.text
2021-06-23 16:13:48 +01:00
2022-05-05 15:44:34 +01:00
return InvoiceResponse(False, None, None, error_message)
2021-06-23 16:13:48 +01:00
2022-05-05 15:44:34 +01:00
data = r.json()
return InvoiceResponse(True, data["paymentHash"], data["serialized"], None)
2021-06-23 16:13:48 +01:00
2022-05-05 15:44:34 +01:00
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
r = await self.client.post(
"/payinvoice",
data={"invoice": bolt11, "blocking": True},
timeout=None,
)
2022-05-05 15:44:34 +01:00
if "error" in r.json():
try:
data = r.json()
error_message = data["error"]
except:
error_message = r.text
return PaymentResponse(False, None, None, None, error_message)
2022-06-01 14:53:05 +02:00
2022-05-05 15:44:34 +01:00
data = r.json()
if data["type"] == "payment-failed":
return PaymentResponse(False, None, None, None, "payment failed")
2022-05-05 15:44:34 +01:00
checking_id = data["paymentHash"]
preimage = data["paymentPreimage"]
# We do all this again to get the fee:
r = await self.client.post(
"/getsentinfo",
data={"paymentHash": checking_id},
timeout=40,
)
2022-05-05 15:44:34 +01:00
if "error" in r.json():
try:
data = r.json()
error_message = data["error"]
except:
error_message = r.text
return PaymentResponse(None, checking_id, None, preimage, error_message)
2022-05-05 15:44:34 +01:00
statuses = {
"sent": True,
"failed": False,
"pending": None,
}
data = r.json()[-1]
fee_msat = 0
if data["status"]["type"] == "sent":
fee_msat = -data["status"]["feesPaid"]
preimage = data["status"]["paymentPreimage"]
2022-05-05 15:44:34 +01:00
return PaymentResponse(
statuses[data["status"]["type"]], checking_id, fee_msat, preimage, None
)
2022-05-05 15:44:34 +01:00
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
try:
r = await self.client.post(
"/getreceivedinfo",
data={"paymentHash": checking_id},
)
2022-05-05 15:44:34 +01:00
r.raise_for_status()
data = r.json()
2021-06-23 16:13:48 +01:00
if r.is_error or "error" in data or data.get("status") is None:
raise Exception("error in eclair response")
statuses = {
"received": True,
"expired": False,
"pending": None,
}
return PaymentStatus(statuses.get(data["status"]["type"]))
except:
return PaymentStatus(None)
2021-06-23 16:13:48 +01:00
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
try:
r = await self.client.post(
"/getsentinfo",
data={"paymentHash": checking_id},
timeout=40,
)
2022-05-05 15:44:34 +01:00
r.raise_for_status()
2022-06-01 14:53:05 +02:00
data = r.json()[-1]
2021-06-23 16:13:48 +01:00
if r.is_error or "error" in data or data.get("status") is None:
raise Exception("error in eclair response")
2021-06-23 16:13:48 +01:00
fee_msat, preimage = None, None
if data["status"]["type"] == "sent":
fee_msat = -data["status"]["feesPaid"]
preimage = data["status"]["paymentPreimage"]
2022-06-01 14:53:05 +02:00
statuses = {
"sent": True,
"failed": False,
"pending": None,
}
return PaymentStatus(
statuses.get(data["status"]["type"]), fee_msat, preimage
)
except:
return PaymentStatus(None)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
while True:
try:
async with connect(
self.ws_url,
extra_headers=[("Authorization", self.auth["Authorization"])],
) as ws:
while True:
message = await ws.recv()
message_json = json.loads(message)
if message_json and message_json["type"] == "payment-received":
yield message_json["paymentHash"]
except Exception as exc:
logger.error(
f"lost connection to eclair invoices stream: '{exc}', retrying in 5 seconds"
)
await asyncio.sleep(5)