remove exception to black line-length and reformat.

This commit is contained in:
fiatjaf
2021-03-24 00:40:32 -03:00
parent 3333f1f3f3
commit 42bd5ea989
92 changed files with 1341 additions and 330 deletions
+4 -1
View File
@@ -37,7 +37,10 @@ class Wallet(ABC):
@abstractmethod
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
pass
+15 -3
View File
@@ -10,13 +10,22 @@ import json
from os import getenv
from typing import Optional, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet, Unsupported
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
Unsupported,
)
class CLightningWallet(Wallet):
def __init__(self):
if LightningRpc is None: # pragma: nocover
raise ImportError("The `pylightning` library must be installed to use `CLightningWallet`.")
raise ImportError(
"The `pylightning` library must be installed to use `CLightningWallet`."
)
self.rpc = getenv("CLIGHTNING_RPC")
self.ln = LightningRpc(self.rpc)
@@ -52,7 +61,10 @@ class CLightningWallet(Wallet):
return StatusResponse(error_message, 0)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
label = "lbl{}".format(random.random())
msat = amount * 1000
+36 -8
View File
@@ -3,7 +3,13 @@ import httpx
from os import getenv
from typing import Optional, Dict, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
class LNbitsWallet(Wallet):
@@ -12,7 +18,11 @@ class LNbitsWallet(Wallet):
def __init__(self):
self.endpoint = getenv("LNBITS_ENDPOINT")
key = getenv("LNBITS_KEY") or getenv("LNBITS_ADMIN_KEY") or getenv("LNBITS_INVOICE_KEY")
key = (
getenv("LNBITS_KEY")
or getenv("LNBITS_ADMIN_KEY")
or getenv("LNBITS_INVOICE_KEY")
)
self.key = {"X-Api-Key": key}
def status(self) -> StatusResponse:
@@ -20,7 +30,9 @@ class LNbitsWallet(Wallet):
try:
data = r.json()
except:
return StatusResponse(f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0)
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0
)
if r.is_error:
return StatusResponse(data["message"], 0)
@@ -28,7 +40,10 @@ class LNbitsWallet(Wallet):
return StatusResponse(None, data["balance"])
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
data: Dict = {"out": False, "amount": amount}
if description_hash:
@@ -41,7 +56,12 @@ class LNbitsWallet(Wallet):
headers=self.key,
json=data,
)
ok, checking_id, payment_request, error_message = not r.is_error, None, None, None
ok, checking_id, payment_request, error_message = (
not r.is_error,
None,
None,
None,
)
if r.is_error:
error_message = r.json()["message"]
@@ -52,7 +72,11 @@ class LNbitsWallet(Wallet):
return InvoiceResponse(ok, checking_id, payment_request, error_message)
def pay_invoice(self, bolt11: str) -> PaymentResponse:
r = httpx.post(url=f"{self.endpoint}/api/v1/payments", headers=self.key, json={"out": True, "bolt11": bolt11})
r = httpx.post(
url=f"{self.endpoint}/api/v1/payments",
headers=self.key,
json={"out": True, "bolt11": bolt11},
)
ok, checking_id, fee_msat, error_message = not r.is_error, None, 0, None
if r.is_error:
@@ -64,7 +88,9 @@ class LNbitsWallet(Wallet):
return PaymentResponse(ok, checking_id, fee_msat, error_message)
def get_invoice_status(self, checking_id: str) -> PaymentStatus:
r = httpx.get(url=f"{self.endpoint}/api/v1/payments/{checking_id}", headers=self.key)
r = httpx.get(
url=f"{self.endpoint}/api/v1/payments/{checking_id}", headers=self.key
)
if r.is_error:
return PaymentStatus(None)
@@ -72,7 +98,9 @@ class LNbitsWallet(Wallet):
return PaymentStatus(r.json()["paid"])
def get_payment_status(self, checking_id: str) -> PaymentStatus:
r = httpx.get(url=f"{self.endpoint}/api/v1/payments/{checking_id}", headers=self.key)
r = httpx.get(
url=f"{self.endpoint}/api/v1/payments/{checking_id}", headers=self.key
)
if r.is_error:
return PaymentStatus(None)
+17 -4
View File
@@ -15,7 +15,13 @@ import hashlib
from os import getenv
from typing import Optional, Dict, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
def get_ssl_context(cert_path: str):
@@ -76,10 +82,14 @@ def stringify_checking_id(r_hash: bytes) -> str:
class LndWallet(Wallet):
def __init__(self):
if lndgrpc is None: # pragma: nocover
raise ImportError("The `lndgrpc` library must be installed to use `LndWallet`.")
raise ImportError(
"The `lndgrpc` library must be installed to use `LndWallet`."
)
if purerpc is None: # pragma: nocover
raise ImportError("The `purerpc` library must be installed to use `LndWallet`.")
raise ImportError(
"The `purerpc` library must be installed to use `LndWallet`."
)
endpoint = getenv("LND_GRPC_ENDPOINT")
self.endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
@@ -111,7 +121,10 @@ class LndWallet(Wallet):
return StatusResponse(None, resp.balance * 1000)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
params: Dict = {"value": amount, "expiry": 600, "private": True}
+23 -5
View File
@@ -5,7 +5,13 @@ import base64
from os import getenv
from typing import Optional, Dict, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
class LndRestWallet(Wallet):
@@ -14,7 +20,9 @@ class LndRestWallet(Wallet):
def __init__(self):
endpoint = getenv("LND_REST_ENDPOINT")
endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
endpoint = "https://" + endpoint if not endpoint.startswith("http") else endpoint
endpoint = (
"https://" + endpoint if not endpoint.startswith("http") else endpoint
)
self.endpoint = endpoint
macaroon = (
@@ -47,14 +55,19 @@ class LndRestWallet(Wallet):
return StatusResponse(None, int(data["balance"]) * 1000)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
data: Dict = {
"value": amount,
"private": True,
}
if description_hash:
data["description_hash"] = base64.b64encode(description_hash).decode("ascii")
data["description_hash"] = base64.b64encode(description_hash).decode(
"ascii"
)
else:
data["memo"] = memo or ""
@@ -131,7 +144,12 @@ class LndRestWallet(Wallet):
# check payment.status:
# https://api.lightning.community/rest/index.html?python#peersynctype
statuses = {"UNKNOWN": None, "IN_FLIGHT": None, "SUCCEEDED": True, "FAILED": False}
statuses = {
"UNKNOWN": None,
"IN_FLIGHT": None,
"SUCCEEDED": True,
"FAILED": False,
}
# for some reason our checking_ids are in base64 but the payment hashes
# returned here are in hex, lnd is weird
+17 -4
View File
@@ -6,7 +6,13 @@ from http import HTTPStatus
from typing import Optional, Dict, AsyncGenerator
from quart import request
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
class LNPayWallet(Wallet):
@@ -31,7 +37,8 @@ class LNPayWallet(Wallet):
data = r.json()
if data["statusType"]["name"] != "active":
return StatusResponse(
f"Wallet {data['user_label']} (data['id']) not active, but {data['statusType']['name']}", 0
f"Wallet {data['user_label']} (data['id']) not active, but {data['statusType']['name']}",
0,
)
return StatusResponse(None, data["balance"] * 1000)
@@ -78,7 +85,9 @@ class LNPayWallet(Wallet):
try:
data = r.json()
except:
return PaymentResponse(False, None, 0, None, f"Got invalid JSON: {r.text[:200]}")
return PaymentResponse(
False, None, 0, None, f"Got invalid JSON: {r.text[:200]}"
)
if r.is_error:
return PaymentResponse(False, None, 0, None, data["message"])
@@ -115,7 +124,11 @@ class LNPayWallet(Wallet):
except json.decoder.JSONDecodeError:
print(f"got something wrong on lnpay webhook endpoint: {text[:200]}")
data = None
if type(data) is not dict or "event" not in data or data["event"].get("name") != "wallet_receive":
if (
type(data) is not dict
or "event" not in data
or data["event"].get("name") != "wallet_receive"
):
return "", HTTPStatus.NO_CONTENT
lntx_id = data["data"]["wtx"]["lnTx"]["id"]
+19 -4
View File
@@ -4,7 +4,13 @@ import httpx
from os import getenv
from typing import Optional, Dict, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
class LntxbotWallet(Wallet):
@@ -14,7 +20,11 @@ class LntxbotWallet(Wallet):
endpoint = getenv("LNTXBOT_API_ENDPOINT")
self.endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
key = getenv("LNTXBOT_KEY") or getenv("LNTXBOT_ADMIN_KEY") or getenv("LNTXBOT_INVOICE_KEY")
key = (
getenv("LNTXBOT_KEY")
or getenv("LNTXBOT_ADMIN_KEY")
or getenv("LNTXBOT_INVOICE_KEY")
)
self.auth = {"Authorization": f"Basic {key}"}
def status(self) -> StatusResponse:
@@ -26,7 +36,9 @@ class LntxbotWallet(Wallet):
try:
data = r.json()
except:
return StatusResponse(f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0)
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0
)
if data.get("error"):
return StatusResponse(data["message"], 0)
@@ -34,7 +46,10 @@ class LntxbotWallet(Wallet):
return StatusResponse(None, data["BTC"]["AvailableBalance"] * 1000)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
data: Dict = {"amt": str(amount)}
if description_hash:
+24 -4
View File
@@ -7,7 +7,14 @@ from os import getenv
from typing import Optional, AsyncGenerator
from quart import request, url_for
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet, Unsupported
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
Unsupported,
)
class OpenNodeWallet(Wallet):
@@ -17,7 +24,11 @@ class OpenNodeWallet(Wallet):
endpoint = getenv("OPENNODE_API_ENDPOINT")
self.endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
key = getenv("OPENNODE_KEY") or getenv("OPENNODE_ADMIN_KEY") or getenv("OPENNODE_INVOICE_KEY")
key = (
getenv("OPENNODE_KEY")
or getenv("OPENNODE_ADMIN_KEY")
or getenv("OPENNODE_INVOICE_KEY")
)
self.auth = {"Authorization": key}
def status(self) -> StatusResponse:
@@ -37,7 +48,10 @@ class OpenNodeWallet(Wallet):
return StatusResponse(None, data["balance"]["BTC"] / 100_000_000_000)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
if description_hash:
raise Unsupported("description_hash")
@@ -93,7 +107,13 @@ class OpenNodeWallet(Wallet):
if r.is_error:
return PaymentStatus(None)
statuses = {"initial": None, "pending": None, "confirmed": True, "error": False, "failed": False}
statuses = {
"initial": None,
"pending": None,
"confirmed": True,
"error": False,
"failed": False,
}
return PaymentStatus(statuses[r.json()["data"]["status"]])
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
+18 -4
View File
@@ -5,7 +5,13 @@ import httpx
from os import getenv
from typing import Optional, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
)
class SparkError(Exception):
@@ -24,7 +30,9 @@ class SparkWallet(Wallet):
def __getattr__(self, key):
def call(*args, **kwargs):
if args and kwargs:
raise TypeError(f"must supply either named arguments or a list of arguments, not both: {args} {kwargs}")
raise TypeError(
f"must supply either named arguments or a list of arguments, not both: {args} {kwargs}"
)
elif args:
params = args
elif kwargs:
@@ -67,7 +75,10 @@ class SparkWallet(Wallet):
)
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
label = "lbs{}".format(random.random())
checking_id = label
@@ -81,7 +92,10 @@ class SparkWallet(Wallet):
)
else:
r = self.invoice(
msatoshi=amount * 1000, label=label, description=memo or "", exposeprivatechannels=True
msatoshi=amount * 1000,
label=label,
description=memo or "",
exposeprivatechannels=True,
)
ok, payment_request, error_message = True, r["bolt11"], ""
except (SparkError, UnknownError) as e:
+12 -2
View File
@@ -1,11 +1,21 @@
from typing import Optional, AsyncGenerator
from .base import StatusResponse, InvoiceResponse, PaymentResponse, PaymentStatus, Wallet, Unsupported
from .base import (
StatusResponse,
InvoiceResponse,
PaymentResponse,
PaymentStatus,
Wallet,
Unsupported,
)
class VoidWallet(Wallet):
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
self,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
) -> InvoiceResponse:
raise Unsupported("")