This commit is contained in:
ben
2022-10-03 10:45:13 +01:00
parent b09dbc4b85
commit 77269ad0a7
5 changed files with 19 additions and 26 deletions

View File

@@ -6,12 +6,9 @@ from lnbits.db import Database
from lnbits.helpers import template_renderer from lnbits.helpers import template_renderer
from lnbits.tasks import catch_everything_and_restart from lnbits.tasks import catch_everything_and_restart
from cashu.mint.router import router as cashu_router
db = Database("ext_cashu") db = Database("ext_cashu")
cashu_ext: APIRouter = APIRouter(prefix="/cashu", tags=["cashu"]) cashu_ext: APIRouter = APIRouter(prefix="/cashu", tags=["cashu"])
cashu_ext.include_router(router=cashu_router)
def cashu_renderer(): def cashu_renderer():
return template_renderer(["lnbits/extensions/cashu/templates"]) return template_renderer(["lnbits/extensions/cashu/templates"])

View File

@@ -3,7 +3,7 @@ from typing import List, Optional, Union
from lnbits.helpers import urlsafe_short_hash from lnbits.helpers import urlsafe_short_hash
from . import db from . import db
from .models import Cashu, Pegs from .models import Cashu, Pegs, Proof
from embit import script from embit import script
from embit import ec from embit import ec
@@ -76,9 +76,7 @@ async def delete_cashu(cashu_id: str) -> None:
async def store_promise( async def store_promise(
amount: int, amount: int,
B_: str, B_: str,
C_: str, C_: str
db: Database,
conn: Optional[Connection] = None,
): ):
await (conn or db).execute( await (conn or db).execute(
@@ -95,10 +93,7 @@ async def store_promise(
) )
async def get_proofs_used( async def get_proofs_used():
db: Database,
conn: Optional[Connection] = None,
):
rows = await (conn or db).fetchall( rows = await (conn or db).fetchall(
""" """
@@ -109,9 +104,7 @@ async def get_proofs_used(
async def invalidate_proof( async def invalidate_proof(
proof: Proof, proof: Proof
db: Database,
conn: Optional[Connection] = None,
): ):
# we add the proof and secret to the used list # we add the proof and secret to the used list

View File

@@ -1,22 +1,23 @@
import hashlib import hashlib
from typing import List, Set from typing import List, Set
from models import BlindedMessage, BlindedSignature, Invoice, Proof from .models import BlindedMessage, BlindedSignature, Invoice, Proof
from secp256k1 import PublicKey, PrivateKey from secp256k1 import PublicKey, PrivateKey
from fastapi import Query
from lnbits.core.services import check_transaction_status, create_invoice from lnbits.core.services import check_transaction_status, create_invoice
class Ledger: class Ledger:
def __init__(self, secret_key: str, db: str, MAX_ORDER: int = Query(64)): def __init__(self, secret_key: str, MAX_ORDER: int = Query(64)):
self.proofs_used: Set[str] = set() self.proofs_used: Set[str] = set()
self.master_key: str = secret_key self.master_key: str = secret_key
self.keys: List[PrivateKey] = self._derive_keys(self.master_key) self.keys: List[PrivateKey] = self._derive_keys(self.master_key)
self.pub_keys: List[PublicKey] = self._derive_pubkeys(self.keys) self.pub_keys: List[PublicKey] = self._derive_pubkeys(self.keys)
self.db: Database = Database("mint", db)
async def load_used_proofs(self): async def load_used_proofs(self):
self.proofs_used = set(await get_proofs_used(db=self.db)) self.proofs_used = set(await get_proofs_used)
@staticmethod @staticmethod
def _derive_keys(master_key: str): def _derive_keys(master_key: str):
@@ -48,7 +49,7 @@ class Ledger:
secret_key = self.keys[amount] # Get the correct key secret_key = self.keys[amount] # Get the correct key
C_ = step2_bob(B_, secret_key) C_ = step2_bob(B_, secret_key)
await store_promise( await store_promise(
amount, B_=B_.serialize().hex(), C_=C_.serialize().hex(), db=self.db amount, B_=B_.serialize().hex(), C_=C_.serialize().hex()
) )
return BlindedSignature(amount=amount, C_=C_.serialize().hex()) return BlindedSignature(amount=amount, C_=C_.serialize().hex())
@@ -126,7 +127,7 @@ class Ledger:
self.proofs_used |= proof_msgs self.proofs_used |= proof_msgs
# store in db # store in db
for p in proofs: for p in proofs:
await invalidate_proof(p, db=self.db) await invalidate_proof(p)
# Public methods # Public methods
def get_pubkeys(self): def get_pubkeys(self):
@@ -150,13 +151,13 @@ class Ledger:
) )
if not payment_request or not payment_hash: if not payment_request or not payment_hash:
raise Exception(f"Could not create Lightning invoice.") raise Exception(f"Could not create Lightning invoice.")
await store_lightning_invoice(invoice, db=self.db) await store_lightning_invoice(invoice)
return payment_request, payment_hash return payment_request, payment_hash
async def mint(self, B_s: List[PublicKey], amounts: List[int], payment_hash=None): async def mint(self, B_s: List[PublicKey], amounts: List[int], payment_hash=None):
"""Mints a promise for coins for B_.""" """Mints a promise for coins for B_."""
# check if lightning invoice was paid # check if lightning invoice was paid
if payment_hash and not await check_transaction_status(ayment_hash) if payment_hash and not await check_transaction_status(payment_hash):
raise Exception("Lightning invoice not paid yet.") raise Exception("Lightning invoice not paid yet.")
for amount in amounts: for amount in amounts:
@@ -224,7 +225,7 @@ class Ledger:
return prom_fst, prom_snd return prom_fst, prom_snd
#######FUNCTIONS############### ##############FUNCTIONS###############
def fee_reserve(amount_msat: int) -> int: def fee_reserve(amount_msat: int) -> int:
"""Function for calculating the Lightning fee reserve""" """Function for calculating the Lightning fee reserve"""
return max( return max(

View File

@@ -1,5 +1,5 @@
from sqlite3 import Row from sqlite3 import Row
from typing import Optional from typing import Optional, List
from fastapi import Query from fastapi import Query
from pydantic import BaseModel from pydantic import BaseModel
@@ -31,6 +31,8 @@ class Pegs(BaseModel):
def from_row(cls, row: Row) -> "TPoS": def from_row(cls, row: Row) -> "TPoS":
return cls(**dict(row)) return cls(**dict(row))
class PayLnurlWData(BaseModel):
lnurl: str
class Proof(BaseModel): class Proof(BaseModel):
amount: int amount: int

View File

@@ -16,9 +16,9 @@ from lnbits.decorators import WalletTypeInfo, get_key_type, require_admin_key
from . import cashu_ext from . import cashu_ext
from .crud import create_cashu, delete_cashu, get_cashu, get_cashus, update_cashu_keys from .crud import create_cashu, delete_cashu, get_cashu, get_cashus, update_cashu_keys
from .models import Cashu, Pegs, CheckPayload, MeltPayload, MintPayloads, SplitPayload from .models import Cashu, Pegs, CheckPayload, MeltPayload, MintPayloads, SplitPayload, PayLnurlWData
import .ledger from .ledger import Ledger, fee_reserve, amount_split, hash_to_point, step1_alice, step2_bob, step3_alice, verify
@cashu_ext.get("/api/v1/cashus", status_code=HTTPStatus.OK) @cashu_ext.get("/api/v1/cashus", status_code=HTTPStatus.OK)
async def api_cashus( async def api_cashus(