Skip to content

Commit

Permalink
revert changes to main
Browse files Browse the repository at this point in the history
  • Loading branch information
callebtc committed Mar 12, 2024
1 parent 85e3fb6 commit 02d090f
Show file tree
Hide file tree
Showing 6 changed files with 10 additions and 112 deletions.
1 change: 0 additions & 1 deletion cashu/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,6 @@ class PostMeltQuoteRequest(BaseModel):
request: str = Field(
..., max_length=settings.mint_max_request_length
) # output payment request
amount: Optional[int] = Field(default=None, gt=0) # input amount


class PostMeltQuoteResponse(BaseModel):
Expand Down
1 change: 0 additions & 1 deletion cashu/lightning/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ def get_payment_status(
async def get_payment_quote(
self,
bolt11: str,
amount: Optional[Amount] = None,
) -> PaymentQuoteResponse:
pass

Expand Down
90 changes: 2 additions & 88 deletions cashu/lightning/lndrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
import json
from typing import AsyncGenerator, Dict, Optional

import bolt11
import httpx
from bolt11 import (
TagChar,
decode,
)
from loguru import logger
Expand Down Expand Up @@ -147,16 +145,6 @@ async def create_invoice(
async def pay_invoice(
self, quote: MeltQuote, fee_limit_msat: int
) -> PaymentResponse:
# if the amount of the melt quote is different from the request
# call pay_partial_invoice instead
invoice = bolt11.decode(quote.request)
if invoice.amount_msat:
amount_msat = int(invoice.amount_msat)
if amount_msat != quote.amount * 1000:
return await self.pay_partial_invoice(
quote, Amount(Unit.sat, quote.amount), fee_limit_msat
)

# set the fee limit for the payment
lnrpcFeeLimit = dict()
lnrpcFeeLimit["fixed_msat"] = f"{fee_limit_msat}"
Expand Down Expand Up @@ -189,71 +177,6 @@ async def pay_invoice(
error_message=None,
)

async def pay_partial_invoice(
self, quote: MeltQuote, amount: Amount, fee_limit_msat: int
) -> PaymentResponse:
# set the fee limit for the payment
lnrpcFeeLimit = dict()
lnrpcFeeLimit["fixed_msat"] = f"{fee_limit_msat}"
invoice = bolt11.decode(quote.request)

invoice_amount = invoice.amount_msat
assert invoice_amount, "invoice has no amount."
total_amount_msat = int(invoice_amount)

payee = invoice.tags.get(TagChar.payee)
assert payee
pubkey = str(payee.data)

payer_addr_tag = invoice.tags.get(bolt11.TagChar("s"))
assert payer_addr_tag
payer_addr = str(payer_addr_tag.data)

# get the route
r = await self.client.post(
url=f"/v1/graph/routes/{pubkey}/{amount.to(Unit.sat).amount}",
timeout=None,
)

data = r.json()

# We need to set the mpp_record for a partial payment
mpp_record = {
"mpp_record": {
"payment_addr": base64.b64encode(bytes.fromhex(payer_addr)).decode(),
"total_amt_msat": total_amount_msat,
}
}

# add the mpp_record to the last hop
rout_nr = 0
data["routes"][rout_nr]["hops"][-1].update(mpp_record)

# send to route
r = await self.client.post(
url="/v2/router/route/send",
json={
"payment_hash": base64.b64encode(
bytes.fromhex(invoice.payment_hash)
).decode(),
"route": data["routes"][rout_nr],
},
timeout=None,
)

data = r.json()
ok = data.get("status") == "SUCCEEDED"
checking_id = invoice.payment_hash
fee_msat = int(data["route"]["total_fees_msat"])
preimage = base64.b64decode(data["preimage"]).hex()
return PaymentResponse(
ok=ok,
checking_id=checking_id,
fee=Amount(unit=Unit.msat, amount=fee_msat) if fee_msat else None,
preimage=preimage,
error_message=None,
)

async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
r = await self.client.get(url=f"/v1/invoice/{checking_id}")

Expand Down Expand Up @@ -338,22 +261,13 @@ async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
)
await asyncio.sleep(5)

async def get_payment_quote(
self, bolt11: str, amount: Optional[Amount] = None
) -> PaymentQuoteResponse:
async def get_payment_quote(self, bolt11: str) -> PaymentQuoteResponse:
invoice_obj = decode(bolt11)
assert invoice_obj.amount_msat, "invoice has no amount."

if amount:
amount_msat = amount.to(Unit.msat).amount
else:
amount_msat = int(invoice_obj.amount_msat)

amount_msat = int(invoice_obj.amount_msat)
fees_msat = fee_reserve(amount_msat)
fees = Amount(unit=Unit.msat, amount=fees_msat)

amount = Amount(unit=Unit.msat, amount=amount_msat)

return PaymentQuoteResponse(
checking_id=invoice_obj.payment_hash, fee=fees, amount=amount
)
8 changes: 1 addition & 7 deletions cashu/mint/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,11 +472,6 @@ async def melt_quote(
if mint_quote:
# internal transaction, validate and return amount from
# associated mint quote and demand zero fees
if (
melt_quote.amount
and Amount(unit, mint_quote.amount).to(unit).amount != melt_quote.amount
):
raise TransactionError("internal amounts do not match")
assert (
Amount(unit, mint_quote.amount).to(Unit.msat).amount
== invoice_obj.amount_msat
Expand All @@ -500,9 +495,8 @@ async def melt_quote(
)
else:
# not internal, get quote by backend
amount = Amount(unit, melt_quote.amount) if melt_quote.amount else None
payment_quote = await self.backends[method][unit].get_payment_quote(
melt_quote.request, amount=amount
melt_quote.request
)
assert payment_quote.checking_id, "quote has no checking id"

Expand Down
6 changes: 2 additions & 4 deletions cashu/wallet/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from operator import itemgetter
from os import listdir
from os.path import isdir, join
from typing import Optional

import click
from click import Context
Expand Down Expand Up @@ -177,17 +176,16 @@ async def cli(ctx: Context, host: str, walletname: str, unit: str, tests: bool):

@cli.command("pay", help="Pay Lightning invoice.")
@click.argument("invoice", type=str)
@click.argument("amount", type=int, required=False)
@click.option(
"--yes", "-y", default=False, is_flag=True, help="Skip confirmation.", type=bool
)
@click.pass_context
@coro
async def pay(ctx: Context, invoice: str, amount: Optional[int], yes: bool):
async def pay(ctx: Context, invoice: str, yes: bool):
wallet: Wallet = ctx.obj["WALLET"]
await wallet.load_mint()
print_balance(ctx)
quote = await wallet.get_pay_amount_with_fees(invoice, amount)
quote = await wallet.get_pay_amount_with_fees(invoice)
logger.debug(f"Quote: {quote}")
total_amount = quote.amount + quote.fee_reserve
if not yes:
Expand Down
16 changes: 5 additions & 11 deletions cashu/wallet/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,15 +527,11 @@ def _mintrequest_include_fields(outputs: List[BlindedMessage]):

@async_set_httpx_client
@async_ensure_mint_loaded
async def melt_quote(
self, payment_request: str, amount: Optional[int] = None
) -> PostMeltQuoteResponse:
async def melt_quote(self, payment_request: str) -> PostMeltQuoteResponse:
"""Checks whether the Lightning payment is internal."""
invoice_obj = bolt11.decode(payment_request)
assert invoice_obj.amount_msat, "invoice must have amount"
payload = PostMeltQuoteRequest(
unit=self.unit.name, request=payment_request, amount=amount
)
payload = PostMeltQuoteRequest(unit=self.unit.name, request=payment_request)
resp = await self.httpx.post(
join(self.url, "/v1/melt/quote/bolt11"),
json=payload.dict(),
Expand All @@ -549,7 +545,7 @@ async def melt_quote(
quote_id = "deprecated_" + str(uuid.uuid4())
return PostMeltQuoteResponse(
quote=quote_id,
amount=amount or invoice_obj.amount_msat // 1000,
amount=invoice_obj.amount_msat // 1000,
fee_reserve=ret.fee or 0,
paid=False,
expiry=invoice_obj.expiry,
Expand Down Expand Up @@ -1524,14 +1520,12 @@ async def invalidate(

# ---------- TRANSACTION HELPERS ----------

async def get_pay_amount_with_fees(
self, invoice: str, amount: Optional[int] = None
) -> PostMeltQuoteResponse:
async def get_pay_amount_with_fees(self, invoice: str):
"""
Decodes the amount from a Lightning invoice and returns the
total amount (amount+fees) to be paid.
"""
melt_quote = await self.melt_quote(invoice, amount)
melt_quote = await self.melt_quote(invoice)
logger.debug(
f"Mint wants {self.unit.str(melt_quote.fee_reserve)} as fee reserve."
)
Expand Down

0 comments on commit 02d090f

Please sign in to comment.