From 6d4e9ff9f18e60979cb039c58dd566d37db553b9 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Tue, 21 Nov 2023 13:42:44 -0300 Subject: [PATCH] LightningWallet -> LightningBackend --- cashu/lightning/base.py | 6 +- cashu/lightning/corelightningrest.py | 4 +- cashu/lightning/fake.py | 8 +- cashu/lightning/lnbits.py | 4 +- cashu/lightning/lndrest.py | 4 +- cashu/lightning/strike.py | 4 +- cashu/mint/ledger.py | 33 +----- cashu/mint/lightning.py | 167 --------------------------- cashu/mint/protocols.py | 4 +- 9 files changed, 16 insertions(+), 218 deletions(-) delete mode 100644 cashu/mint/lightning.py diff --git a/cashu/lightning/base.py b/cashu/lightning/base.py index 60d5771e..e757ffe3 100644 --- a/cashu/lightning/base.py +++ b/cashu/lightning/base.py @@ -3,8 +3,6 @@ from pydantic import BaseModel -from ..core.base import Method, Unit - class StatusResponse(BaseModel): error_message: Optional[str] @@ -61,9 +59,7 @@ def __str__(self) -> str: return "unknown (should never happen)" -class LightningWallet(ABC): - unit: Unit - method: Method +class LightningBackend(ABC): @abstractmethod def status(self) -> Coroutine[None, None, StatusResponse]: diff --git a/cashu/lightning/corelightningrest.py b/cashu/lightning/corelightningrest.py index ecd2bfb2..a90e68c8 100644 --- a/cashu/lightning/corelightningrest.py +++ b/cashu/lightning/corelightningrest.py @@ -15,7 +15,7 @@ from ..core.settings import settings from .base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentResponse, PaymentStatus, @@ -25,7 +25,7 @@ from .macaroon import load_macaroon -class CoreLightningRestWallet(LightningWallet): +class CoreLightningRestWallet(LightningBackend): def __init__(self): macaroon = settings.mint_corelightning_rest_macaroon assert macaroon, "missing cln-rest macaroon" diff --git a/cashu/lightning/fake.py b/cashu/lightning/fake.py index 6a19971d..d12e34d0 100644 --- a/cashu/lightning/fake.py +++ b/cashu/lightning/fake.py @@ -15,12 +15,11 @@ encode, ) -from ..core.base import Method, Unit from ..core.helpers import fee_reserve from ..core.settings import settings from .base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentResponse, PaymentStatus, @@ -28,12 +27,9 @@ ) -class FakeWallet(LightningWallet): +class FakeWallet(LightningBackend): """https://github.com/lnbits/lnbits""" - method = Method.bolt11 - unit = Unit.sat - queue: asyncio.Queue[Bolt11] = asyncio.Queue(0) payment_secrets: Dict[str, str] = dict() paid_invoices: Set[str] = set() diff --git a/cashu/lightning/lnbits.py b/cashu/lightning/lnbits.py index 91112a04..20b07e69 100644 --- a/cashu/lightning/lnbits.py +++ b/cashu/lightning/lnbits.py @@ -11,7 +11,7 @@ from ..core.settings import settings from .base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentResponse, PaymentStatus, @@ -19,7 +19,7 @@ ) -class LNbitsWallet(LightningWallet): +class LNbitsWallet(LightningBackend): """https://github.com/lnbits/lnbits""" def __init__(self): diff --git a/cashu/lightning/lndrest.py b/cashu/lightning/lndrest.py index f69d14cf..37c7b96f 100644 --- a/cashu/lightning/lndrest.py +++ b/cashu/lightning/lndrest.py @@ -15,7 +15,7 @@ from ..core.settings import settings from .base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentResponse, PaymentStatus, @@ -24,7 +24,7 @@ from .macaroon import load_macaroon -class LndRestWallet(LightningWallet): +class LndRestWallet(LightningBackend): """https://api.lightning.community/rest/index.html#lnd-rest-api-reference""" def __init__(self): diff --git a/cashu/lightning/strike.py b/cashu/lightning/strike.py index 1aca6803..2707030a 100644 --- a/cashu/lightning/strike.py +++ b/cashu/lightning/strike.py @@ -8,7 +8,7 @@ from ..core.settings import settings from .base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentResponse, PaymentStatus, @@ -16,7 +16,7 @@ ) -class StrikeUSDWallet(LightningWallet): +class StrikeUSDWallet(LightningBackend): """https://github.com/lnbits/lnbits""" method = Method.bolt11 diff --git a/cashu/mint/ledger.py b/cashu/mint/ledger.py index 2c9ae4c2..68226b1b 100644 --- a/cashu/mint/ledger.py +++ b/cashu/mint/ledger.py @@ -36,7 +36,7 @@ from ..core.split import amount_split from ..lightning.base import ( InvoiceResponse, - LightningWallet, + LightningBackend, PaymentQuoteResponse, PaymentStatus, ) @@ -46,7 +46,7 @@ class Ledger(LedgerVerification, LedgerSpendingConditions): - backends: Mapping[Method, Mapping[Unit, LightningWallet]] = {} + backends: Mapping[Method, Mapping[Unit, LightningBackend]] = {} locks: Dict[str, asyncio.Lock] = {} # holds multiprocessing locks proofs_pending_lock: asyncio.Lock = ( asyncio.Lock() @@ -57,7 +57,7 @@ def __init__( self, db: Database, seed: str, - backends: Mapping[Method, Mapping[Unit, LightningWallet]], + backends: Mapping[Method, Mapping[Unit, LightningBackend]], derivation_path="", crud=LedgerCrudSqlite(), ): @@ -430,33 +430,6 @@ async def melt_quote( unit ].get_payment_quote(melt_quote.request) - if unit == Unit.msat: - payment_quote.amount = payment_quote.amount * 1000 - payment_quote.fee = payment_quote.fee * 1000 - - # amount = invoice_amount_sat - # checking_id = invoice_obj.payment_hash - - # if unit == Unit.sat: - # # Lightning - # fee_reserve_sat = await self._get_lightning_fees(melt_quote.request) - # amount = invoice_amount_sat - # checking_id = invoice_obj.payment_hash - # elif unit == Unit.usd: - # fee_reserve_sat = 0 - # amount = int(invoice_amount_sat / 3400) - # checking_id = invoice_obj.payment_hash - # elif unit == Unit.cheese: - # fee_reserve_sat = 2 - # amount = int(invoice_amount_sat / 2) - # checking_id = invoice_obj.payment_hash - # elif unit == Unit.msat: - # fee_reserve_sat = 0 - # amount = invoice_amount_sat * 1000 - # checking_id = invoice_obj.payment_hash - # else: - # raise NotAllowedError(f"Melt quote: {melt_quote.unit} unit not supported.") - # NOTE: We do not store the fee reserve in the database. quote = MeltQuote( quote=random_hash(), diff --git a/cashu/mint/lightning.py b/cashu/mint/lightning.py deleted file mode 100644 index ea4fd9b8..00000000 --- a/cashu/mint/lightning.py +++ /dev/null @@ -1,167 +0,0 @@ -# import math -# from typing import Dict - -# import bolt11 -# from loguru import logger - -# from ..core.base import Unit -# from ..core.db import Database -# from ..core.errors import ( -# LightningError, -# ) -# from ..core.helpers import fee_reserve -# from ..lightning.base import InvoiceResponse, LightningWallet, PaymentResponse -# from ..mint.crud import LedgerCrud -# from .protocols import SupportLightning, SupportsDb - - -# class LedgerLightning(SupportLightning, SupportsDb): -# """Lightning functions for the ledger.""" - -# lightning: Dict[Unit, LightningWallet] -# crud: LedgerCrud -# db: Database - -# async def _request_lightning_invoice(self, amount: int) -> InvoiceResponse: -# """Generate a Lightning invoice using the funding source backend. - -# Args: -# amount (int): Amount of invoice (in Satoshis) - -# Raises: -# Exception: Error with funding source. - -# Returns: -# Tuple[str, str]: Bolt11 invoice and payment id (for lookup) -# """ -# logger.trace( -# "_request_lightning_invoice: Requesting Lightning invoice for" -# f" {amount} satoshis." -# ) -# status = await self.lightning.status() -# logger.trace( -# "_request_lightning_invoice: Lightning wallet balance:" -# f" {status.balance_msat}" -# ) -# if status.error_message: -# raise LightningError( -# f"Lightning wallet not responding: {status.error_message}" -# ) -# payment = await self.lightning.create_invoice(amount, "Cashu deposit") -# logger.trace( -# f"_request_lightning_invoice: Lightning invoice: {payment.payment_request}" -# ) - -# if not payment.ok: -# raise LightningError(f"Lightning wallet error: {payment.error_message}") -# assert payment.payment_request and payment.checking_id, LightningError( -# "could not fetch invoice from Lightning backend" -# ) -# return payment - -# # async def _check_lightning_invoice( -# # self, *, amount: int, id: str, conn: Optional[Connection] = None -# # ) -> PaymentStatus: -# # """Checks with the Lightning backend whether an invoice with `id` was paid. - -# # Args: -# # amount (int): Amount of the outputs the wallet wants in return (in Satoshis). -# # id (str): Id to look up Lightning invoice by. - -# # Raises: -# # Exception: Invoice not found. -# # Exception: Tokens for invoice already issued. -# # Exception: Amount larger than invoice amount. -# # Exception: Invoice not paid yet -# # e: Update database and pass through error. - -# # Returns: -# # bool: True if invoice has been paid, else False -# # """ -# # invoice: Union[Invoice, None] = await self.crud.get_lightning_invoice( -# # id=id, db=self.db, conn=conn -# # ) -# # if invoice is None: -# # raise LightningError("invoice not found.") -# # if invoice.issued: -# # raise LightningError("tokens already issued for this invoice.") -# # if amount > invoice.amount: -# # raise LightningError( -# # f"requested amount too high: {amount}. Invoice amount: {invoice.amount}" -# # ) -# # assert invoice.payment_hash, "invoice has no payment hash." -# # # set this invoice as issued -# # await self.crud.update_lightning_invoice( -# # id=id, issued=True, db=self.db, conn=conn -# # ) - -# # try: -# # status = await self.lightning.get_invoice_status(invoice.payment_hash) -# # if status.paid: -# # return status -# # else: -# # raise InvoiceNotPaidError() -# # except Exception as e: -# # # unset issued -# # await self.crud.update_lightning_invoice( -# # id=id, issued=False, db=self.db, conn=conn -# # ) -# # raise e - -# async def _get_lightning_fees(self, pr: str) -> int: -# """Returns the fee reserve (in sat) that a wallet must add to its proofs -# in order to pay a Lightning invoice. - -# Args: -# pr (str): Bolt11 encoded payment request. Lightning invoice. - -# Returns: -# int: Fee in Satoshis. -# """ - -# amount_msat = 0 -# decoded_invoice = bolt11.decode(pr) -# assert decoded_invoice.amount_msat, "invoice has no amount." -# amount_msat = int(decoded_invoice.amount_msat) -# logger.trace( -# f"get_melt_fees: checking lightning invoice: {decoded_invoice.payment_hash}" -# ) - -# # hack: check if it's internal, if it exists, it will return paid = False, -# # if id does not exist (not internal), it returns paid = None -# # NOTE: This only works with LNbits so we're getting rid of it -# # payment = await self.lightning.get_invoice_status(decoded_invoice.payment_hash) -# # logger.trace(f"get_melt_fees: paid: {payment.paid}") -# # internal = payment.paid is False - -# fees_msat = fee_reserve(amount_msat) -# fee_sat = math.ceil(fees_msat / 1000) -# return fee_sat - -# async def _pay_lightning_invoice( -# self, invoice: str, fee_limit_msat: int -# ) -> PaymentResponse: -# """Pays a Lightning invoice via the funding source backend. - -# Args: -# invoice (str): Bolt11 Lightning invoice -# fee_limit_msat (int): Maximum fee reserve for payment (in Millisatoshi) - -# Raises: -# Exception: Funding source error. - -# Returns: -# Tuple[bool, string, int]: Returns payment status, preimage of invoice, paid fees (in Millisatoshi) -# """ -# status = await self.lightning.status() -# if status.error_message: -# raise LightningError( -# f"Lightning wallet not responding: {status.error_message}" -# ) -# payment = await self.lightning.pay_invoice( -# invoice, fee_limit_msat=fee_limit_msat -# ) -# logger.trace(f"_pay_lightning_invoice: Lightning payment status: {payment.ok}") -# # make sure that fee is positive and not None -# payment.fee_msat = abs(payment.fee_msat) if payment.fee_msat else 0 -# return payment diff --git a/cashu/mint/protocols.py b/cashu/mint/protocols.py index 11a16ac9..47bf618e 100644 --- a/cashu/mint/protocols.py +++ b/cashu/mint/protocols.py @@ -2,7 +2,7 @@ from ..core.base import MintKeyset, Unit from ..core.db import Database -from ..lightning.base import LightningWallet +from ..lightning.base import LightningBackend from ..mint.crud import LedgerCrud @@ -12,7 +12,7 @@ class SupportsKeysets(Protocol): class SupportLightning(Protocol): - lightning: Dict[Unit, LightningWallet] + lightning: Dict[Unit, LightningBackend] class SupportsDb(Protocol):