2022-09-16 13:20:42 +01:00
|
|
|
from http import HTTPStatus
|
2022-09-30 14:23:03 +01:00
|
|
|
from typing import Union
|
2022-09-16 13:20:42 +01:00
|
|
|
|
|
|
|
import httpx
|
|
|
|
from fastapi import Query
|
|
|
|
from fastapi.params import Depends
|
|
|
|
from lnurl import decode as decode_lnurl
|
|
|
|
from loguru import logger
|
2022-10-07 11:17:02 +03:00
|
|
|
from secp256k1 import PublicKey
|
2022-09-16 13:20:42 +01:00
|
|
|
from starlette.exceptions import HTTPException
|
|
|
|
|
|
|
|
from lnbits.core.crud import get_user
|
2022-10-07 11:17:02 +03:00
|
|
|
from lnbits.core.services import check_transaction_status, create_invoice
|
2022-09-16 13:20:42 +01:00
|
|
|
from lnbits.core.views.api import api_payment
|
|
|
|
from lnbits.decorators import WalletTypeInfo, get_key_type, require_admin_key
|
2022-10-07 11:17:02 +03:00
|
|
|
from lnbits.wallets.base import PaymentStatus
|
2022-09-16 13:20:42 +01:00
|
|
|
|
|
|
|
from . import cashu_ext
|
2022-10-07 11:17:02 +03:00
|
|
|
from .core.base import CashuError
|
2022-10-03 14:43:02 +01:00
|
|
|
from .crud import (
|
2022-10-07 11:17:02 +03:00
|
|
|
create_cashu,
|
|
|
|
delete_cashu,
|
|
|
|
get_cashu,
|
2022-10-07 11:08:46 +03:00
|
|
|
get_cashus,
|
2022-10-07 11:17:02 +03:00
|
|
|
get_lightning_invoice,
|
2022-10-07 11:08:46 +03:00
|
|
|
store_lightning_invoice,
|
2022-10-07 13:44:26 +03:00
|
|
|
store_promise,
|
2022-10-07 15:18:09 +03:00
|
|
|
update_lightning_invoice,
|
2022-10-03 14:43:02 +01:00
|
|
|
)
|
2022-10-07 11:17:02 +03:00
|
|
|
from .ledger import mint, request_mint
|
2022-10-07 17:44:02 +03:00
|
|
|
from .mint import generate_promises, get_pubkeys, melt
|
2022-10-03 14:43:02 +01:00
|
|
|
from .models import (
|
2022-10-07 11:08:46 +03:00
|
|
|
Cashu,
|
2022-10-07 11:17:02 +03:00
|
|
|
CheckPayload,
|
|
|
|
Invoice,
|
|
|
|
MeltPayload,
|
|
|
|
MintPayloads,
|
|
|
|
PayLnurlWData,
|
|
|
|
Pegs,
|
|
|
|
SplitPayload,
|
2022-10-03 14:43:02 +01:00
|
|
|
)
|
2022-09-16 13:20:42 +01:00
|
|
|
|
2022-10-07 10:09:16 +03:00
|
|
|
########################################
|
|
|
|
#################MINT CRUD##############
|
|
|
|
########################################
|
|
|
|
|
|
|
|
# todo: use /mints
|
2022-09-16 13:20:42 +01:00
|
|
|
@cashu_ext.get("/api/v1/cashus", status_code=HTTPStatus.OK)
|
|
|
|
async def api_cashus(
|
|
|
|
all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
|
|
|
|
):
|
|
|
|
wallet_ids = [wallet.wallet.id]
|
|
|
|
if all_wallets:
|
|
|
|
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
|
|
|
|
|
|
|
|
return [cashu.dict() for cashu in await get_cashus(wallet_ids)]
|
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.post("/api/v1/cashus", status_code=HTTPStatus.CREATED)
|
2022-10-07 11:17:02 +03:00
|
|
|
async def api_cashu_create(data: Cashu, wallet: WalletTypeInfo = Depends(get_key_type)):
|
2022-09-16 13:20:42 +01:00
|
|
|
cashu = await create_cashu(wallet_id=wallet.wallet.id, data=data)
|
|
|
|
logger.debug(cashu)
|
|
|
|
return cashu.dict()
|
2022-09-21 15:16:38 +01:00
|
|
|
|
2022-10-07 11:17:02 +03:00
|
|
|
|
2022-09-21 15:16:38 +01:00
|
|
|
@cashu_ext.post("/api/v1/cashus/upodatekeys", status_code=HTTPStatus.CREATED)
|
|
|
|
async def api_cashu_update_keys(
|
|
|
|
data: Cashu, wallet: WalletTypeInfo = Depends(get_key_type)
|
|
|
|
):
|
|
|
|
cashu = await get_cashu(data.id)
|
|
|
|
|
|
|
|
cashu = await create_cashu(wallet_id=wallet.wallet.id, data=data)
|
|
|
|
logger.debug(cashu)
|
|
|
|
return cashu.dict()
|
2022-09-16 13:20:42 +01:00
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.delete("/api/v1/cashus/{cashu_id}")
|
|
|
|
async def api_cashu_delete(
|
|
|
|
cashu_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
|
|
|
|
):
|
|
|
|
cashu = await get_cashu(cashu_id)
|
|
|
|
|
|
|
|
if not cashu:
|
|
|
|
raise HTTPException(
|
2022-10-07 19:44:06 +03:00
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Cashu does not exist."
|
2022-09-16 13:20:42 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
if cashu.wallet != wallet.wallet.id:
|
2022-10-07 19:44:06 +03:00
|
|
|
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your Cashu.")
|
2022-09-16 13:20:42 +01:00
|
|
|
|
|
|
|
await delete_cashu(cashu_id)
|
|
|
|
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
|
|
|
|
|
|
|
|
|
2022-10-07 10:09:16 +03:00
|
|
|
########################################
|
|
|
|
#################????###################
|
|
|
|
########################################
|
2022-09-16 13:20:42 +01:00
|
|
|
@cashu_ext.post("/api/v1/cashus/{cashu_id}/invoices", status_code=HTTPStatus.CREATED)
|
|
|
|
async def api_cashu_create_invoice(
|
|
|
|
amount: int = Query(..., ge=1), tipAmount: int = None, cashu_id: str = None
|
|
|
|
):
|
|
|
|
cashu = await get_cashu(cashu_id)
|
|
|
|
|
|
|
|
if not cashu:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
|
|
|
|
)
|
|
|
|
|
|
|
|
if tipAmount:
|
|
|
|
amount += tipAmount
|
|
|
|
|
|
|
|
try:
|
|
|
|
payment_hash, payment_request = await create_invoice(
|
|
|
|
wallet_id=cashu.wallet,
|
|
|
|
amount=amount,
|
|
|
|
memo=f"{cashu.name}",
|
|
|
|
extra={"tag": "cashu", "tipAmount": tipAmount, "cashuId": cashu_id},
|
|
|
|
)
|
|
|
|
except Exception as e:
|
|
|
|
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))
|
|
|
|
|
|
|
|
return {"payment_hash": payment_hash, "payment_request": payment_request}
|
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.post(
|
2022-10-07 11:17:02 +03:00
|
|
|
"/api/v1/cashus/{cashu_id}/invoices/{payment_request}/pay",
|
|
|
|
status_code=HTTPStatus.OK,
|
2022-09-16 13:20:42 +01:00
|
|
|
)
|
|
|
|
async def api_cashu_pay_invoice(
|
|
|
|
lnurl_data: PayLnurlWData, payment_request: str = None, cashu_id: str = None
|
|
|
|
):
|
|
|
|
cashu = await get_cashu(cashu_id)
|
|
|
|
|
|
|
|
if not cashu:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
|
|
|
|
)
|
|
|
|
|
|
|
|
lnurl = (
|
|
|
|
lnurl_data.lnurl.replace("lnurlw://", "")
|
|
|
|
.replace("lightning://", "")
|
|
|
|
.replace("LIGHTNING://", "")
|
|
|
|
.replace("lightning:", "")
|
|
|
|
.replace("LIGHTNING:", "")
|
|
|
|
)
|
|
|
|
|
|
|
|
if lnurl.lower().startswith("lnurl"):
|
|
|
|
lnurl = decode_lnurl(lnurl)
|
|
|
|
else:
|
|
|
|
lnurl = "https://" + lnurl
|
|
|
|
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
try:
|
|
|
|
r = await client.get(lnurl, follow_redirects=True)
|
|
|
|
if r.is_error:
|
|
|
|
lnurl_response = {"success": False, "detail": "Error loading"}
|
|
|
|
else:
|
|
|
|
resp = r.json()
|
|
|
|
if resp["tag"] != "withdrawRequest":
|
|
|
|
lnurl_response = {"success": False, "detail": "Wrong tag type"}
|
|
|
|
else:
|
|
|
|
r2 = await client.get(
|
|
|
|
resp["callback"],
|
|
|
|
follow_redirects=True,
|
|
|
|
params={
|
|
|
|
"k1": resp["k1"],
|
|
|
|
"pr": payment_request,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
resp2 = r2.json()
|
|
|
|
if r2.is_error:
|
|
|
|
lnurl_response = {
|
|
|
|
"success": False,
|
|
|
|
"detail": "Error loading callback",
|
|
|
|
}
|
|
|
|
elif resp2["status"] == "ERROR":
|
|
|
|
lnurl_response = {"success": False, "detail": resp2["reason"]}
|
|
|
|
else:
|
|
|
|
lnurl_response = {"success": True, "detail": resp2}
|
|
|
|
except (httpx.ConnectError, httpx.RequestError):
|
|
|
|
lnurl_response = {"success": False, "detail": "Unexpected error occurred"}
|
|
|
|
|
|
|
|
return lnurl_response
|
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.get(
|
|
|
|
"/api/v1/cashus/{cashu_id}/invoices/{payment_hash}", status_code=HTTPStatus.OK
|
|
|
|
)
|
|
|
|
async def api_cashu_check_invoice(cashu_id: str, payment_hash: str):
|
|
|
|
cashu = await get_cashu(cashu_id)
|
|
|
|
if not cashu:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
status = await api_payment(payment_hash)
|
|
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
logger.error(exc)
|
|
|
|
return {"paid": False}
|
|
|
|
return status
|
2022-09-30 14:23:03 +01:00
|
|
|
|
|
|
|
|
2022-10-03 14:43:02 +01:00
|
|
|
########################################
|
|
|
|
#################MINT###################
|
|
|
|
########################################
|
2022-09-30 14:23:03 +01:00
|
|
|
|
2022-10-07 11:17:02 +03:00
|
|
|
|
2022-10-07 19:44:06 +03:00
|
|
|
@cashu_ext.get("/api/v1/cashu/{cashu_id}/keys", status_code=HTTPStatus.OK)
|
2022-10-07 11:17:02 +03:00
|
|
|
async def keys(
|
|
|
|
cashu_id: str = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
|
|
|
|
):
|
2022-09-30 14:23:03 +01:00
|
|
|
"""Get the public keys of the mint"""
|
2022-10-07 10:09:16 +03:00
|
|
|
mint = await get_cashu(cashu_id)
|
|
|
|
if mint is None:
|
|
|
|
raise HTTPException(
|
2022-10-07 11:17:02 +03:00
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Mint does not exist."
|
|
|
|
)
|
2022-10-07 10:09:16 +03:00
|
|
|
return get_pubkeys(mint.prvkey)
|
2022-09-30 14:23:03 +01:00
|
|
|
|
|
|
|
|
2022-10-07 19:44:06 +03:00
|
|
|
@cashu_ext.get("/api/v1/cashu/{cashu_id}/mint")
|
2022-10-07 11:18:17 +03:00
|
|
|
async def mint_pay_request(
|
|
|
|
amount: int = 0,
|
|
|
|
cashu_id: str = Query(None),
|
|
|
|
wallet: WalletTypeInfo = Depends(get_key_type),
|
|
|
|
):
|
2022-09-30 14:23:03 +01:00
|
|
|
"""Request minting of tokens. Server responds with a Lightning invoice."""
|
2022-10-07 11:17:02 +03:00
|
|
|
|
2022-10-07 10:23:42 +03:00
|
|
|
cashu = await get_cashu(cashu_id)
|
|
|
|
if cashu is None:
|
|
|
|
raise HTTPException(
|
2022-10-07 11:17:02 +03:00
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Mint does not exist."
|
|
|
|
)
|
2022-10-07 10:23:42 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
payment_hash, payment_request = await create_invoice(
|
|
|
|
wallet_id=cashu.wallet,
|
|
|
|
amount=amount,
|
|
|
|
memo=f"{cashu.name}",
|
|
|
|
extra={"tag": "cashu"},
|
|
|
|
)
|
2022-10-07 11:08:46 +03:00
|
|
|
invoice = Invoice(
|
|
|
|
amount=amount, pr=payment_request, hash=payment_hash, issued=False
|
|
|
|
)
|
|
|
|
await store_lightning_invoice(cashu_id, invoice)
|
2022-10-07 10:23:42 +03:00
|
|
|
except Exception as e:
|
2022-10-07 11:08:46 +03:00
|
|
|
logger.error(e)
|
2022-10-07 11:17:02 +03:00
|
|
|
raise HTTPException(
|
2022-10-07 17:44:02 +03:00
|
|
|
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)
|
2022-10-07 11:17:02 +03:00
|
|
|
)
|
2022-10-07 10:23:42 +03:00
|
|
|
|
2022-09-30 14:23:03 +01:00
|
|
|
return {"pr": payment_request, "hash": payment_hash}
|
|
|
|
|
|
|
|
|
2022-10-07 19:44:06 +03:00
|
|
|
@cashu_ext.post("/api/v1/cashu/{cashu_id}/mint")
|
2022-10-07 11:17:02 +03:00
|
|
|
async def mint_coins(
|
2022-10-07 15:09:26 +03:00
|
|
|
data: MintPayloads,
|
2022-10-07 11:17:02 +03:00
|
|
|
cashu_id: str = Query(None),
|
2022-10-07 15:09:26 +03:00
|
|
|
payment_hash: Union[str, None] = None,
|
2022-10-07 11:47:37 +03:00
|
|
|
wallet: WalletTypeInfo = Depends(require_admin_key),
|
2022-10-07 11:17:02 +03:00
|
|
|
):
|
2022-10-07 11:08:46 +03:00
|
|
|
"""
|
|
|
|
Requests the minting of tokens belonging to a paid payment request.
|
|
|
|
Call this endpoint after `GET /mint`.
|
|
|
|
"""
|
2022-10-07 11:17:02 +03:00
|
|
|
cashu: Cashu = await get_cashu(cashu_id)
|
|
|
|
if cashu is None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Mint does not exist."
|
|
|
|
)
|
2022-10-07 11:47:37 +03:00
|
|
|
invoice: Invoice = (
|
|
|
|
None
|
2022-10-07 15:09:26 +03:00
|
|
|
if payment_hash == None
|
|
|
|
else await get_lightning_invoice(cashu_id, payment_hash)
|
2022-10-07 11:47:37 +03:00
|
|
|
)
|
2022-10-07 11:17:02 +03:00
|
|
|
if invoice is None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Mint does not have this invoice."
|
|
|
|
)
|
2022-10-07 15:18:09 +03:00
|
|
|
if invoice.issued == True:
|
|
|
|
raise HTTPException(
|
2022-10-07 17:44:02 +03:00
|
|
|
status_code=HTTPStatus.PAYMENT_REQUIRED,
|
|
|
|
detail="Tokens already issued for this invoice.",
|
2022-10-07 15:18:09 +03:00
|
|
|
)
|
2022-10-07 11:17:02 +03:00
|
|
|
|
2022-10-07 17:44:02 +03:00
|
|
|
status: PaymentStatus = await check_transaction_status(cashu.wallet, payment_hash)
|
2022-10-07 13:44:26 +03:00
|
|
|
# todo: revert to: status.paid != True:
|
2022-10-07 19:44:06 +03:00
|
|
|
if status.paid != True:
|
2022-10-07 11:17:02 +03:00
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.PAYMENT_REQUIRED, detail="Invoice not paid."
|
|
|
|
)
|
2022-10-07 13:44:26 +03:00
|
|
|
try:
|
2022-10-07 15:18:09 +03:00
|
|
|
await update_lightning_invoice(cashu_id, payment_hash, True)
|
|
|
|
|
|
|
|
amounts = []
|
|
|
|
B_s = []
|
|
|
|
for payload in data.blinded_messages:
|
|
|
|
amounts.append(payload.amount)
|
|
|
|
B_s.append(PublicKey(bytes.fromhex(payload.B_), raw=True))
|
|
|
|
|
|
|
|
promises = await generate_promises(cashu.prvkey, amounts, B_s)
|
|
|
|
for amount, B_, p in zip(amounts, B_s, promises):
|
|
|
|
await store_promise(amount, B_.serialize().hex(), p.C_, cashu_id)
|
2022-10-07 17:44:02 +03:00
|
|
|
|
2022-10-07 15:18:09 +03:00
|
|
|
return promises
|
2022-10-07 17:44:02 +03:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(e)
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)
|
|
|
|
)
|
2022-09-30 14:23:03 +01:00
|
|
|
|
|
|
|
|
2022-10-07 19:44:06 +03:00
|
|
|
@cashu_ext.post("/api/v1/cashu/{cashu_id}/melt")
|
2022-10-03 14:43:02 +01:00
|
|
|
async def melt_coins(payload: MeltPayload, cashu_id: str = Query(None)):
|
2022-10-07 17:44:02 +03:00
|
|
|
cashu: Cashu = await get_cashu(cashu_id)
|
|
|
|
if cashu is None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.NOT_FOUND, detail="Mint does not exist."
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
ok, preimage = await melt(cashu, payload.proofs, payload.invoice)
|
|
|
|
return {"paid": ok, "preimage": preimage}
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(e)
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)
|
|
|
|
)
|
2022-09-30 14:23:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.post("/check")
|
2022-10-03 14:43:02 +01:00
|
|
|
async def check_spendable_coins(payload: CheckPayload, cashu_id: str = Query(None)):
|
|
|
|
return await check_spendable(payload.proofs, cashu_id)
|
2022-09-30 14:23:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
@cashu_ext.post("/split")
|
2022-10-03 14:43:02 +01:00
|
|
|
async def spli_coinst(payload: SplitPayload, cashu_id: str = Query(None)):
|
2022-09-30 14:23:03 +01:00
|
|
|
"""
|
|
|
|
Requetst a set of tokens with amount "total" to be split into two
|
|
|
|
newly minted sets with amount "split" and "total-split".
|
|
|
|
"""
|
|
|
|
proofs = payload.proofs
|
|
|
|
amount = payload.amount
|
|
|
|
output_data = payload.output_data.blinded_messages
|
|
|
|
try:
|
2022-10-03 14:43:02 +01:00
|
|
|
split_return = await split(proofs, amount, output_data)
|
2022-09-30 14:23:03 +01:00
|
|
|
except Exception as exc:
|
|
|
|
return {"error": str(exc)}
|
|
|
|
if not split_return:
|
|
|
|
"""There was a problem with the split"""
|
|
|
|
raise Exception("could not split tokens.")
|
|
|
|
fst_promises, snd_promises = split_return
|
2022-10-07 11:17:02 +03:00
|
|
|
return {"fst": fst_promises, "snd": snd_promises}
|