Revert "chore: apply black to all .py files"

This reverts commit 83b7779972.
This commit is contained in:
Stefan Stammberger 2021-11-24 14:31:55 +01:00 committed by benarc
parent 83b7779972
commit efec7cb8f0
18 changed files with 90 additions and 139 deletions

View File

@ -1,5 +1,5 @@
## Python script to migrate an LNbits SQLite DB to Postgres
## All credits to @Fritz446 for the awesome work
## All credits to @Fritz446 for the awesome work
## pip install psycopg2 OR psycopg2-binary

View File

@ -278,9 +278,7 @@ async def get_payments(
return [Payment.from_row(row) for row in rows]
async def delete_expired_invoices(
conn: Optional[Connection] = None,
) -> None:
async def delete_expired_invoices(conn: Optional[Connection] = None,) -> None:
# first we delete all invoices older than one month
await (conn or db).execute(
f"""

View File

@ -316,7 +316,8 @@ async def check_invoice_status(
if not payment.pending:
return status
if payment.is_out and status.failed:
print(f" - deleting outgoing failed payment {payment.checking_id}: {status}")
print(
f" - deleting outgoing failed payment {payment.checking_id}: {status}")
await payment.delete()
elif not status.pending:
print(

View File

@ -15,7 +15,6 @@ from ..tasks import api_invoice_listeners
@core_app.get("/.well-known/lnurlp/{username}")
async def lnaddress(username: str, request: Request):
from lnbits.extensions.lnaddress.lnurl import lnurl_response
domain = request.client.host
return await lnurl_response(username, domain)

View File

@ -76,7 +76,7 @@ class Track(BaseModel):
return None
url = request.url_for("livestream.track_redirect_download", track_id=self.id)
url_with_query = f"{url}?p={payment_hash}"
url_with_query = f"{url}?p={payment_hash}"
return UrlAction(
url=url_with_query,

View File

@ -8,8 +8,10 @@ from lnbits.tasks import catch_everything_and_restart
db = Database("ext_lnaddress")
lnaddress_ext: APIRouter = APIRouter(prefix="/lnaddress", tags=["lnaddress"])
lnaddress_ext: APIRouter = APIRouter(
prefix="/lnaddress",
tags=["lnaddress"]
)
def lnaddress_renderer():
return template_renderer(["lnbits/extensions/lnaddress/templates"])

View File

@ -2,7 +2,9 @@ from lnbits.extensions.lnaddress.models import Domains
import httpx, json
async def cloudflare_create_record(domain: Domains, ip: str):
async def cloudflare_create_record(
domain: Domains, ip: str
):
url = (
"https://api.cloudflare.com/client/v4/zones/"
+ domain.cf_zone_id

View File

@ -7,7 +7,9 @@ from . import db
from .models import Addresses, CreateAddress, CreateDomain, Domains
async def create_domain(data: CreateDomain) -> Domains:
async def create_domain(
data: CreateDomain
) -> Domains:
domain_id = urlsafe_short_hash()
await db.execute(
"""
@ -35,20 +37,21 @@ async def update_domain(domain_id: str, **kwargs) -> Domains:
await db.execute(
f"UPDATE lnaddress.domain SET {q} WHERE id = ?", (*kwargs.values(), domain_id)
)
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
row = await db.fetchone(
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
)
assert row, "Newly updated domain couldn't be retrieved"
return Domains(**row)
async def delete_domain(domain_id: str) -> None:
await db.execute("DELETE FROM lnaddress.domain WHERE id = ?", (domain_id,))
async def get_domain(domain_id: str) -> Optional[Domains]:
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
row = await db.fetchone(
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
)
return Domains(**row) if row else None
async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
@ -60,12 +63,12 @@ async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
return [Domains(**row) for row in rows]
## ADRESSES
async def create_address(
payment_hash: str, wallet: str, data: CreateAddress
payment_hash: str,
wallet: str,
data: CreateAddress
) -> Addresses:
await db.execute(
"""
@ -90,7 +93,6 @@ async def create_address(
assert new_address, "Newly created address couldn't be retrieved"
return new_address
async def get_address(address_id: str) -> Optional[Addresses]:
row = await db.fetchone(
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.id = ? AND a.domain = d.id",
@ -98,24 +100,18 @@ async def get_address(address_id: str) -> Optional[Addresses]:
)
return Addresses(**row) if row else None
async def get_address_by_username(username: str, domain: str) -> Optional[Addresses]:
row = await db.fetchone(
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.username = ? AND d.domain = ?",
# "SELECT * FROM lnaddress.address WHERE username = ? AND domain = ?",
(
username,
domain,
),
(username, domain,),
)
print("ADD", row)
return Addresses(**row) if row else None
async def delete_address(address_id: str) -> None:
await db.execute("DELETE FROM lnaddress.address WHERE id = ?", (address_id,))
async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
@ -128,7 +124,6 @@ async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
print([Addresses(**row) for row in rows])
return [Addresses(**row) for row in rows]
async def set_address_paid(payment_hash: str) -> Addresses:
_address = await get_address(payment_hash)
address = _address._asdict()
@ -147,7 +142,6 @@ async def set_address_paid(payment_hash: str) -> Addresses:
assert new_address, "Newly paid address couldn't be retrieved"
return new_address
async def set_address_renewed(address_id: str, duration: int):
_address = await get_address(address_id)
address = _address._asdict()
@ -159,10 +153,7 @@ async def set_address_renewed(address_id: str, duration: int):
SET duration = ?
WHERE id = ?
""",
(
extend_duration,
address_id,
),
(extend_duration, address_id,),
)
updated_address = await get_address(address_id)
assert updated_address, "Renewed address couldn't be retrieved"
@ -170,21 +161,17 @@ async def set_address_renewed(address_id: str, duration: int):
async def check_address_available(username: str, domain: str):
(row,) = await db.fetchone(
row, = await db.fetchone(
"SELECT COUNT(username) FROM lnaddress.address WHERE username = ? AND domain = ?",
(
username,
domain,
),
(username, domain,),
)
return row
async def purge_addresses(domain_id: str):
rows = await db.fetchall(
"SELECT * FROM lnaddress.address WHERE domain = ?",
(domain_id,),
(domain_id, ),
)
now = datetime.now().timestamp()
@ -194,10 +181,8 @@ async def purge_addresses(domain_id: str):
start = datetime.fromtimestamp(r["time"])
paid = r["paid"]
pay_expire = now > start.timestamp() + 86400 # if payment wasn't made in 1 day
expired = (
now > (start + timedelta(days=r["duration"] + 1)).timestamp()
) # give user 1 day to topup is address
pay_expire = now > start.timestamp() + 86400 #if payment wasn't made in 1 day
expired = now > (start + timedelta(days = r["duration"] + 1)).timestamp() #give user 1 day to topup is address
if not paid and pay_expire:
print("DELETE UNP_PAY_EXP", r["username"])

View File

@ -23,15 +23,13 @@ async def lnurl_response(username: str, domain: str, request: Request):
## CHECK IF USER IS STILL VALID/PAYING
now = datetime.now().timestamp()
start = datetime.fromtimestamp(address.time)
expiration = (start + timedelta(days=address.duration)).timestamp()
expiration = (start + timedelta(days = address.duration)).timestamp()
if now > expiration:
return LnurlErrorResponse(reason="Address has expired.").dict()
resp = LnurlPayResponse(
callback=request.url_for(
"lnaddress.lnurl_callback", address_id=address.id, _external=True
),
callback=request.url_for("lnaddress.lnurl_callback", address_id=address.id, _external=True),
min_sendable=1000,
max_sendable=1000000000,
metadata=await address.lnurlpay_metadata(),
@ -39,13 +37,14 @@ async def lnurl_response(username: str, domain: str, request: Request):
return resp.dict()
@lnaddress_ext.get("/lnurl/cb/{address_id}", name="lnaddress.lnurl_callback")
async def lnurl_callback(address_id, amount: int = Query(...)):
address = await get_address(address_id)
if not address:
return LnurlErrorResponse(reason=f"Address not found").dict()
return LnurlErrorResponse(
reason=f"Address not found"
).dict()
amount_received = amount
# min = 1000
@ -65,26 +64,17 @@ async def lnurl_callback(address_id, amount: int = Query(...)):
domain = await get_domain(address.domain)
base_url = (
address.wallet_endpoint[:-1]
if address.wallet_endpoint.endswith("/")
else address.wallet_endpoint
)
base_url = address.wallet_endpoint[:-1] if address.wallet_endpoint.endswith('/') else address.wallet_endpoint
async with httpx.AsyncClient() as client:
try:
call = await client.post(
base_url + "/api/v1/payments",
headers={
"X-Api-Key": address.wallet_key,
"Content-Type": "application/json",
},
headers={"X-Api-Key": address.wallet_key, "Content-Type": "application/json"},
json={
"out": False,
"amount": int(amount_received / 1000),
"description_hash": hashlib.sha256(
(await address.lnurlpay_metadata()).encode("utf-8")
).hexdigest(),
"description_hash": hashlib.sha256((await address.lnurlpay_metadata()).encode("utf-8")).hexdigest(),
"extra": {"tag": f"Payment to {address.username}@{domain.domain}"},
},
timeout=40,

View File

@ -16,7 +16,6 @@ async def m001_initial(db):
"""
)
async def m002_addresses(db):
await db.execute(
"""
@ -38,6 +37,5 @@ async def m002_addresses(db):
"""
)
# async def m003_create_unique_indexes(db):
# await db.execute("CREATE UNIQUE INDEX IF NOT EXISTS address_at_domain ON lnaddress.address (domain, username);")

View File

@ -7,14 +7,13 @@ from pydantic.main import BaseModel # type: ignore
class CreateDomain(BaseModel):
wallet: str = Query(...)
wallet: str = Query(...)
domain: str = Query(...)
cf_token: str = Query(...)
cf_zone_id: str = Query(...)
webhook: str = Query(None)
cost: int = Query(..., ge=0)
class Domains(BaseModel):
id: str
wallet: str
@ -25,7 +24,6 @@ class Domains(BaseModel):
cost: int
time: int
class CreateAddress(BaseModel):
domain: str = Query(...)
username: str = Query(...)
@ -35,7 +33,6 @@ class CreateAddress(BaseModel):
sats: int = Query(..., ge=0)
duration: int = Query(..., ge=1)
class Addresses(BaseModel):
id: str
wallet: str

View File

@ -52,9 +52,7 @@ async def on_invoice_paid(payment: Payment) -> None:
elif "renew lnaddress" == payment.extra.get("tag"):
await payment.set_pending(False)
await set_address_renewed(
address_id=payment.extra["id"], duration=payment.extra["duration"]
)
await set_address_renewed(address_id=payment.extra["id"], duration=payment.extra["duration"])
await call_webhook_on_paid(payment.payment_hash)
else:

View File

@ -18,10 +18,7 @@ templates = Jinja2Templates(directory="templates")
@lnaddress_ext.get("/", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_user_exists)):
return lnaddress_renderer().TemplateResponse(
"lnaddress/index.html", {"request": request, "user": user.dict()}
)
return lnaddress_renderer().TemplateResponse("lnaddress/index.html", {"request": request, "user": user.dict()})
@lnaddress_ext.get("/{domain_id}")
async def display(domain_id, request: Request):
@ -36,12 +33,11 @@ async def display(domain_id, request: Request):
wallet = await get_wallet(domain.wallet)
return lnaddress_renderer().TemplateResponse(
"lnaddress/display.html",
{
"lnaddress/display.html",{
"request": request,
"domain_id": domain.id,
"domain_id":domain.id,
"domain_domain": domain.domain,
"domain_cost": domain.cost,
"domain_wallet_inkey": wallet.inkey,
},
"domain_wallet_inkey": wallet.inkey
}
)

View File

@ -43,12 +43,7 @@ async def api_domains(
@lnaddress_ext.post("/api/v1/domains")
@lnaddress_ext.put("/api/v1/domains/{domain_id}")
async def api_domain_create(
request: Request,
data: CreateDomain,
domain_id=None,
g: WalletTypeInfo = Depends(get_key_type),
):
async def api_domain_create(request: Request,data: CreateDomain, domain_id=None, g: WalletTypeInfo = Depends(get_key_type)):
if domain_id:
domain = await get_domain(domain_id)
@ -69,7 +64,7 @@ async def api_domain_create(
domain = await create_domain(data=data)
root_url = urlparse(request.url.path).netloc
# root_url = request.url_root
#root_url = request.url_root
cf_response = await cloudflare_create_record(
domain=domain,
@ -80,36 +75,32 @@ async def api_domain_create(
await delete_domain(domain.id)
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Problem with cloudflare: "
+ cf_response["errors"][0]["message"],
detail="Problem with cloudflare: " + cf_response["errors"][0]["message"],
)
return domain.dict()
@lnaddress_ext.delete("/api/v1/domains/{domain_id}")
async def api_domain_delete(domain_id, g: WalletTypeInfo = Depends(get_key_type)):
domain = await get_domain(domain_id)
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Domain does not exist.",
)
status_code=HTTPStatus.NOT_FOUND,
detail="Domain does not exist.",
)
if domain.wallet != g.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your domain",
)
status_code=HTTPStatus.FORBIDDEN,
detail="Not your domain",
)
await delete_domain(domain_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# ADDRESSES
@lnaddress_ext.get("/api/v1/addresses")
async def api_addresses(
g: WalletTypeInfo = Depends(get_key_type),
@ -122,7 +113,6 @@ async def api_addresses(
return [address.dict() for address in await get_addresses(wallet_ids)]
@lnaddress_ext.get("/api/v1/address/{domain}/{username}/{wallet_key}")
async def api_get_user_info(username, wallet_key, domain):
address = await get_address_by_username(username, domain)
@ -135,43 +125,39 @@ async def api_get_user_info(username, wallet_key, domain):
if address.wallet_key != wallet_key:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Incorrect user/wallet information.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="Incorrect user/wallet information.",
)
return address.dict()
@lnaddress_ext.get("/api/v1/address/availabity/{domain_id}/{username}")
async def api_check_available_username(domain_id, username):
used_username = await check_address_available(username, domain_id)
return used_username
@lnaddress_ext.post("/api/v1/address/{domain_id}")
@lnaddress_ext.put("/api/v1/address/{domain_id}/{user}/{wallet_key}")
async def api_lnaddress_make_address(
domain_id, data: CreateAddress, user=None, wallet_key=None
):
async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None, wallet_key=None):
domain = await get_domain(domain_id)
# If the request is coming for the non-existant domain
if not domain:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="The domain does not exist.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="The domain does not exist.",
)
domain_cost = domain[6]
sats = data.sats
## FAILSAFE FOR CREATING ADDRESSES BY API
if domain_cost * data.duration != data.sats:
if(domain_cost * data.duration != data.sats):
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
)
if user:
print("USER", user, domain.domain)
@ -197,7 +183,7 @@ async def api_lnaddress_make_address(
extra={
"tag": "renew lnaddress",
"id": address.id,
"duration": data.duration,
"duration": data.duration
},
)
@ -229,7 +215,7 @@ async def api_lnaddress_make_address(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=str(e),
)
address = await create_address(
payment_hash=payment_hash, wallet=domain.wallet, data=data
)
@ -242,7 +228,6 @@ async def api_lnaddress_make_address(
return {"payment_hash": payment_hash, "payment_request": payment_request}
@lnaddress_ext.get("/api/v1/addresses/{payment_hash}")
async def api_address_send_address(payment_hash):
address = await get_address(payment_hash)
@ -251,27 +236,27 @@ async def api_address_send_address(payment_hash):
status = await check_invoice_status(domain.wallet, payment_hash)
is_paid = not status.pending
except Exception as e:
return {"paid": False, "error": str(e)}
return {"paid": False, 'error': str(e)}
if is_paid:
return {"paid": True}
return {"paid": False}
@lnaddress_ext.delete("/api/v1/addresses/{address_id}")
async def api_address_delete(address_id, g: WalletTypeInfo = Depends(get_key_type)):
address = await get_address(address_id)
if not address:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Address does not exist.",
)
status_code=HTTPStatus.NOT_FOUND,
detail="Address does not exist.",
)
if address.wallet != g.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your address.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="Not your address.",
)
await delete_address(address_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)

View File

@ -108,9 +108,7 @@ async def lndhub_payinvoice(
@lndhub_ext.get("/ext/balance")
async def lndhub_balance(
wallet: WalletTypeInfo = Depends(check_wallet),
):
async def lndhub_balance(wallet: WalletTypeInfo = Depends(check_wallet),):
return {"BTC": {"AvailableBalance": wallet.wallet.balance}}

View File

@ -8,9 +8,7 @@ from .models import lnurlposs, lnurlpospayment, createLnurlpos
###############lnurlposS##########################
async def create_lnurlpos(
data: createLnurlpos,
) -> lnurlposs:
async def create_lnurlpos(data: createLnurlpos,) -> lnurlposs:
print(data)
lnurlpos_id = urlsafe_short_hash()
lnurlpos_key = urlsafe_short_hash()
@ -62,7 +60,6 @@ async def get_lnurlposs(wallet_ids: Union[str, List[str]]) -> List[lnurlposs]:
return [lnurlposs(**row) if row else None for row in rows]
async def delete_lnurlpos(lnurlpos_id: str) -> None:
await db.execute("DELETE FROM lnurlpos.lnurlposs WHERE id = ?", (lnurlpos_id,))

View File

@ -51,12 +51,19 @@ async def api_lnurl_response(request: Request, unique_hash):
# CALLBACK
#https://5650-2001-8a0-fa12-2900-4c13-748a-fbb9-a47f.ngrok.io/withdraw/api/v1/lnurl/cb/eJHybS8hqcBWajZM63H3FP?k1=MUaYBGrUPuAs8SLpfizmCk&pr=lnbc100n1pse2tsypp5ju0yn3w9j0n8rr3squg0knddawu2ude2cgrm6zje5f34e9jzpmlsdq8w3jhxaqxqyjw5qcqpjsp5tyhu78pamqg5zfy96kup329zt40ramc8gs2ev6jxgp66zca2348qrzjqwac3nxyg3f5mfa4ke9577c4u8kvkx8pqtdsusqdfww0aymk823x6znwa5qqzyqqqyqqqqlgqqqqppgq9q9qy9qsq66zp6pctnlmk59xwtqjga5lvqrkyccmafmn43enhhc6ugew80sanxymepshpv44m9yyhfgh8r2upvxhgk00d36rpqzfy3fxemeu4jhqp96l8hx
@withdraw_ext.get(
"/api/v1/lnurl/cb/{unique_hash}",
name="withdraw.api_lnurl_callback",
)
async def api_lnurl_callback(
unique_hash, request: Request, k1: str = Query(...), pr: str = Query(...)
unique_hash,
request: Request,
k1: str = Query(...),
pr: str = Query(...)
):
link = await get_withdraw_link_by_hash(unique_hash)
now = int(datetime.now().timestamp())
@ -94,8 +101,8 @@ async def api_lnurl_callback(
"usescsv": usescsv,
}
await update_withdraw_link(link.id, **changes)
payment_request = pr
payment_request=pr
await pay_invoice(
wallet_id=link.wallet,

View File

@ -63,9 +63,7 @@ class LNbitsWallet(Wallet):
async with httpx.AsyncClient() as client:
r = await client.post(
url=f"{self.endpoint}/api/v1/payments",
headers=self.key,
json=data,
url=f"{self.endpoint}/api/v1/payments", headers=self.key, json=data,
)
ok, checking_id, payment_request, error_message = (
not r.is_error,
@ -87,7 +85,7 @@ class LNbitsWallet(Wallet):
r = await client.post(
url=f"{self.endpoint}/api/v1/payments",
headers=self.key,
json={"out": True, "bolt11": bolt11},
json={"out": True, "bolt11": bolt11},
timeout=100,
)
ok, checking_id, fee_msat, error_message = not r.is_error, None, 0, None