diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml new file mode 100644 index 000000000..980b9c7b9 --- /dev/null +++ b/.github/workflows/flake8.yml @@ -0,0 +1,27 @@ +name: flake8 + +on: [push, pull_request] + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9"] + poetry-version: ["1.3.1"] + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Set up Poetry ${{ matrix.poetry-version }} + uses: abatilo/actions-poetry@v2 + with: + poetry-version: ${{ matrix.poetry-version }} + - name: Install dependencies + run: | + poetry config virtualenvs.create false + poetry install + - name: Run tests + run: make flake8 diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml new file mode 100644 index 000000000..8a43025b7 --- /dev/null +++ b/.github/workflows/pylint.yml @@ -0,0 +1,27 @@ +name: pylint + +on: [push, pull_request] + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9"] + poetry-version: ["1.3.1"] + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Set up Poetry ${{ matrix.poetry-version }} + uses: abatilo/actions-poetry@v2 + with: + poetry-version: ${{ matrix.poetry-version }} + - name: Install dependencies + run: | + poetry config virtualenvs.create false + poetry install + - name: Run tests + run: make pylint diff --git a/Makefile b/Makefile index 22d79f113..5bdbc9480 100644 --- a/Makefile +++ b/Makefile @@ -15,12 +15,18 @@ pyright: black: poetry run black . +flake8: + poetry run flake8 + mypy: poetry run mypy isort: poetry run isort . +pylint: + poetry run pylint *.py lnbits/ tools/ tests/ + checkprettier: $(shell find lnbits -name "*.js" -o -name ".html") ./node_modules/.bin/prettier --check lnbits/static/js/*.js lnbits/core/static/js/*.js lnbits/extensions/*/templates/*/*.html ./lnbits/core/templates/core/*.html lnbits/templates/*.html lnbits/extensions/*/static/js/*.js lnbits/extensions/*/static/components/*/*.js lnbits/extensions/*/static/components/*/*.html diff --git a/build.py b/build.py index 2bc3e50cb..834067c9e 100644 --- a/build.py +++ b/build.py @@ -1,12 +1,9 @@ import glob import os -import subprocess import warnings -from os import path -from pathlib import Path -from typing import Any, List, NamedTuple, Optional +from typing import List -LNBITS_PATH = path.dirname(path.realpath(__file__)) + "/lnbits" +LNBITS_PATH = os.path.dirname(os.path.realpath(__file__)) + "/lnbits" def get_js_vendored(prefer_minified: bool = False) -> List[str]: diff --git a/lnbits/app.py b/lnbits/app.py index ee3b07367..5167055b2 100644 --- a/lnbits/app.py +++ b/lnbits/app.py @@ -95,7 +95,7 @@ async def check_funding_source() -> None: original_sigint_handler = signal.getsignal(signal.SIGINT) def signal_handler(signal, frame): - logger.debug(f"SIGINT received, terminating LNbits.") + logger.debug("SIGINT received, terminating LNbits.") sys.exit(1) signal.signal(signal.SIGINT, signal_handler) @@ -388,7 +388,7 @@ class Formatter: self.fmt: str = self.minimal_fmt def format(self, record): - function = "{function}".format(**record) + function = "{function}".format(**record) # pylint: disable=C0209 if function == "emit": # uvicorn logs return self.minimal_fmt return self.fmt diff --git a/lnbits/bolt11.py b/lnbits/bolt11.py index 4e20208c9..07bff5a3c 100644 --- a/lnbits/bolt11.py +++ b/lnbits/bolt11.py @@ -5,7 +5,6 @@ from decimal import Decimal from typing import List, NamedTuple, Optional import bitstring -import embit import secp256k1 from bech32 import CHARSET, bech32_decode, bech32_encode from ecdsa import SECP256k1, VerifyingKey @@ -20,7 +19,7 @@ class Route(NamedTuple): cltv: int -class Invoice(object): +class Invoice: payment_hash: str amount_msat: int = 0 description: Optional[str] = None @@ -166,9 +165,7 @@ def lnencode(addr, privkey): amount = Decimal(str(addr.amount)) # We can only send down to millisatoshi. if amount * 10**12 % 10: - raise ValueError( - "Cannot encode {}: too many decimal places".format(addr.amount) - ) + raise ValueError(f"Cannot encode {addr.amount}: too many decimal places") amount = addr.currency + shorten_amount(amount) else: @@ -190,7 +187,7 @@ def lnencode(addr, privkey): # A writer MUST NOT include more than one `d`, `h`, `n` or `x` fields, if k in ("d", "h", "n", "x"): if k in tags_set: - raise ValueError("Duplicate '{}' tag".format(k)) + raise ValueError(f"Duplicate '{k}' tag") if k == "r": route = bitstring.BitArray() @@ -220,7 +217,7 @@ def lnencode(addr, privkey): data += tagged_bytes("n", v) else: # FIXME: Support unknown tags? - raise ValueError("Unknown tag {}".format(k)) + raise ValueError(f"Unknown tag {k}") tags_set.add(k) @@ -230,7 +227,7 @@ def lnencode(addr, privkey): # both. if "d" in tags_set and "h" in tags_set: raise ValueError("Cannot include both 'd' and 'h'") - if not "d" in tags_set and not "h" in tags_set: + if "d" not in tags_set and "h" not in tags_set: raise ValueError("Must include either 'd' or 'h'") # We actually sign the hrp, then data (padded to 8 bits with zeroes). @@ -245,7 +242,7 @@ def lnencode(addr, privkey): return bech32_encode(hrp, bitarray_to_u5(data)) -class LnAddr(object): +class LnAddr: def __init__( self, paymenthash=None, amount=None, currency="bc", tags=None, date=None ): @@ -259,12 +256,9 @@ class LnAddr(object): self.amount = amount def __str__(self): - return "LnAddr[{}, amount={}{} tags=[{}]]".format( - bytes.hex(self.pubkey.serialize()).decode(), - self.amount, - self.currency, - ", ".join([k + "=" + str(v) for k, v in self.tags]), - ) + pubkey = bytes.hex(self.pubkey.serialize()).decode() + tags = ", ".join([k + "=" + str(v) for k, v in self.tags]) + return f"LnAddr[{pubkey}, amount={self.amount}{self.currency} tags=[{tags}]]" def shorten_amount(amount): @@ -296,7 +290,7 @@ def _unshorten_amount(amount: str) -> int: # A reader SHOULD fail if `amount` contains a non-digit, or is followed by # anything except a `multiplier` in the table above. if not re.fullmatch(r"\d+[pnum]?", str(amount)): - raise ValueError("Invalid amount '{}'".format(amount)) + raise ValueError(f"Invalid amount '{amount}'") if unit in units: return int(int(amount[:-1]) * 100_000_000_000 / units[unit]) @@ -347,11 +341,10 @@ def _trim_to_bytes(barr): def _readable_scid(short_channel_id: int) -> str: - return "{blockheight}x{transactionindex}x{outputindex}".format( - blockheight=((short_channel_id >> 40) & 0xFFFFFF), - transactionindex=((short_channel_id >> 16) & 0xFFFFFF), - outputindex=(short_channel_id & 0xFFFF), - ) + blockheight = (short_channel_id >> 40) & 0xFFFFFF + transactionindex = (short_channel_id >> 16) & 0xFFFFFF + outputindex = short_channel_id & 0xFFFF + return f"{blockheight}x{transactionindex}x{outputindex}" def _u5_to_bitarray(arr: List[int]) -> bitstring.BitArray: diff --git a/lnbits/core/__init__.py b/lnbits/core/__init__.py index 75b6d5878..4511a8eb8 100644 --- a/lnbits/core/__init__.py +++ b/lnbits/core/__init__.py @@ -9,7 +9,7 @@ core_app: APIRouter = APIRouter() core_app_extra: CoreAppExtra = CoreAppExtra() -from .views.admin_api import * # noqa -from .views.api import * # noqa -from .views.generic import * # noqa -from .views.public_api import * # noqa +from .views.admin_api import * # noqa: F401,F403 +from .views.api import * # noqa: F401,F403 +from .views.generic import * # noqa: F401,F403 +from .views.public_api import * # noqa: F401,F403 diff --git a/lnbits/core/crud.py b/lnbits/core/crud.py index efb594a14..183f663a0 100644 --- a/lnbits/core/crud.py +++ b/lnbits/core/crud.py @@ -358,7 +358,7 @@ async def get_payments( args: List[Any] = [] clause: List[str] = [] - if since != None: + if since is not None: if db.type == POSTGRES: clause.append("time > to_timestamp(?)") elif db.type == COCKROACH: @@ -702,7 +702,7 @@ async def delete_admin_settings(): async def update_admin_settings(data: EditableSettings): - await db.execute(f"UPDATE settings SET editable_settings = ?", (json.dumps(data),)) + await db.execute("UPDATE settings SET editable_settings = ?", (json.dumps(data),)) async def update_super_user(super_user: str): @@ -711,7 +711,7 @@ async def update_super_user(super_user: str): async def create_admin_settings(super_user: str, new_settings: dict): - sql = f"INSERT INTO settings (super_user, editable_settings) VALUES (?, ?)" + sql = "INSERT INTO settings (super_user, editable_settings) VALUES (?, ?)" await db.execute(sql, (super_user, json.dumps(new_settings))) return await get_super_settings() @@ -740,7 +740,7 @@ async def update_migration_version(conn, db_name, version): async def create_tinyurl(domain: str, endless: bool, wallet: str): tinyurl_id = shortuuid.uuid()[:8] await db.execute( - f"INSERT INTO tiny_url (id, url, endless, wallet) VALUES (?, ?, ?, ?)", + "INSERT INTO tiny_url (id, url, endless, wallet) VALUES (?, ?, ?, ?)", ( tinyurl_id, domain, @@ -753,7 +753,7 @@ async def create_tinyurl(domain: str, endless: bool, wallet: str): async def get_tinyurl(tinyurl_id: str) -> Optional[TinyURL]: row = await db.fetchone( - f"SELECT * FROM tiny_url WHERE id = ?", + "SELECT * FROM tiny_url WHERE id = ?", (tinyurl_id,), ) return TinyURL.from_row(row) if row else None @@ -761,14 +761,14 @@ async def get_tinyurl(tinyurl_id: str) -> Optional[TinyURL]: async def get_tinyurl_by_url(url: str) -> List[TinyURL]: rows = await db.fetchall( - f"SELECT * FROM tiny_url WHERE url = ?", + "SELECT * FROM tiny_url WHERE url = ?", (url,), ) return [TinyURL.from_row(row) for row in rows] async def delete_tinyurl(tinyurl_id: str): - row = await db.execute( - f"DELETE FROM tiny_url WHERE id = ?", + await db.execute( + "DELETE FROM tiny_url WHERE id = ?", (tinyurl_id,), ) diff --git a/lnbits/core/helpers.py b/lnbits/core/helpers.py index 7d5c2920a..214fee2fa 100644 --- a/lnbits/core/helpers.py +++ b/lnbits/core/helpers.py @@ -37,7 +37,7 @@ async def run_migration(db: Connection, migrations_module: Any, current_version: print(f"running migration {db_name}.{version}") await migrate(db) - if db.schema == None: + if db.schema is None: await update_migration_version(db, db_name, version) else: async with core_db.connect() as conn: diff --git a/lnbits/core/models.py b/lnbits/core/models.py index c0643af7b..c3ff6fd9c 100644 --- a/lnbits/core/models.py +++ b/lnbits/core/models.py @@ -6,8 +6,8 @@ import time from sqlite3 import Row from typing import Callable, Dict, List, Optional -from ecdsa import SECP256k1, SigningKey # type: ignore -from lnurl import encode as lnurl_encode # type: ignore +from ecdsa import SECP256k1, SigningKey +from lnurl import encode as lnurl_encode from loguru import logger from pydantic import BaseModel diff --git a/lnbits/core/services.py b/lnbits/core/services.py index af5e6716c..f5bf0b469 100644 --- a/lnbits/core/services.py +++ b/lnbits/core/services.py @@ -14,7 +14,6 @@ from lnbits import bolt11 from lnbits.db import Connection from lnbits.decorators import WalletTypeInfo, require_admin_key from lnbits.helpers import url_for, urlsafe_short_hash -from lnbits.requestvars import g from lnbits.settings import ( FAKE_WALLET, EditableSettings, @@ -22,7 +21,6 @@ from lnbits.settings import ( readonly_variables, send_admin_user_to_saas, settings, - transient_variables, ) from lnbits.wallets.base import PaymentResponse, PaymentStatus @@ -214,22 +212,22 @@ async def pay_invoice( ) logger.debug(f"backend: pay_invoice finished {temp_id}") - if payment.checking_id and payment.ok != False: + if payment.checking_id and payment.ok is not False: # payment.ok can be True (paid) or None (pending)! logger.debug(f"updating payment {temp_id}") async with db.connect() as conn: await update_payment_details( checking_id=temp_id, - pending=payment.ok != True, + pending=payment.ok is not True, fee=payment.fee_msat, preimage=payment.preimage, new_checking_id=payment.checking_id, conn=conn, ) logger.debug(f"payment successful {payment.checking_id}") - elif payment.checking_id is None and payment.ok == False: + elif payment.checking_id is None and payment.ok is False: # payment failed - logger.warning(f"backend sent payment failure") + logger.warning("backend sent payment failure") async with db.connect() as conn: logger.debug(f"deleting temporary payment {temp_id}") await delete_wallet_payment(temp_id, wallet_id, conn=conn) @@ -431,7 +429,7 @@ async def check_admin_settings(): update_cached_settings(settings_db.dict()) # printing settings for debugging - logger.debug(f"Admin settings:") + logger.debug("Admin settings:") for key, value in settings.dict(exclude_none=True).items(): logger.debug(f"{key}: {value}") @@ -449,7 +447,7 @@ async def check_admin_settings(): def update_cached_settings(sets_dict: dict): for key, value in sets_dict.items(): - if not key in readonly_variables + transient_variables: + if key not in readonly_variables: try: setattr(settings, key, value) except: diff --git a/lnbits/core/views/api.py b/lnbits/core/views/api.py index 9341a6038..55fbb7a42 100644 --- a/lnbits/core/views/api.py +++ b/lnbits/core/views/api.py @@ -184,7 +184,7 @@ async def api_payments_create_invoice(data: CreateInvoiceData, wallet: Wallet): async with db.connect() as conn: try: - payment_hash, payment_request = await create_invoice( + _, payment_request = await create_invoice( wallet_id=wallet.id, amount=amount, memo=memo, @@ -560,10 +560,10 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type for [k, v] in metadata: if k == "text/plain": params.update(description=v) - if k == "image/jpeg;base64" or k == "image/png;base64": + if k in ("image/jpeg;base64", "image/png;base64"): data_uri = "data:" + k + "," + v params.update(image=data_uri) - if k == "text/email" or k == "text/identifier": + if k in ("text/email", "text/identifier"): params.update(targetUser=v) params.update(commentAllowed=data.get("commentAllowed", 0)) @@ -702,7 +702,7 @@ async def websocket_connect(websocket: WebSocket, item_id: str): await websocketManager.connect(websocket) try: while True: - data = await websocket.receive_text() + await websocket.receive_text() except WebSocketDisconnect: websocketManager.disconnect(websocket) diff --git a/lnbits/core/views/generic.py b/lnbits/core/views/generic.py index b4ecaf4af..dcd7e8c8b 100644 --- a/lnbits/core/views/generic.py +++ b/lnbits/core/views/generic.py @@ -120,7 +120,7 @@ async def extensions_install( ) ) await update_installed_extension_state( - ext_id=ext_id, active=activate != None + ext_id=ext_id, active=activate is not None ) all_extensions = list(map(lambda e: e.code, get_valid_extensions())) @@ -137,7 +137,7 @@ async def extensions_install( "dependencies": ext.dependencies, "isInstalled": ext.id in installed_exts_ids, "isAvailable": ext.id in all_extensions, - "isActive": not ext.id in inactive_extensions, + "isActive": ext.id not in inactive_extensions, "latestRelease": dict(ext.latest_release) if ext.latest_release else None, diff --git a/lnbits/db.py b/lnbits/db.py index 77f3cf33a..985a658bf 100644 --- a/lnbits/db.py +++ b/lnbits/db.py @@ -135,7 +135,7 @@ class Database(Compat): if value is None: return None f = "%Y-%m-%d %H:%M:%S.%f" - if not "." in value: + if "." not in value: f = "%Y-%m-%d %H:%M:%S" return time.mktime(datetime.datetime.strptime(value, f).timetuple()) diff --git a/lnbits/decorators.py b/lnbits/decorators.py index 42d2b7a30..17134f863 100644 --- a/lnbits/decorators.py +++ b/lnbits/decorators.py @@ -245,7 +245,7 @@ async def check_user_exists(usr: UUID4) -> User: async def check_admin(usr: UUID4) -> User: user = await check_user_exists(usr) - if user.id != settings.super_user and not user.id in settings.lnbits_admin_users: + if user.id != settings.super_user and user.id not in settings.lnbits_admin_users: raise HTTPException( status_code=HTTPStatus.UNAUTHORIZED, detail="User not authorized. No admin privileges.", diff --git a/lnbits/extension_manager.py b/lnbits/extension_manager.py index 7955c791d..7eff9480b 100644 --- a/lnbits/extension_manager.py +++ b/lnbits/extension_manager.py @@ -240,7 +240,7 @@ class InstallableExtension(BaseModel): return False with open(config_file, "r") as json_file: config_json = json.load(json_file) - return config_json.get("is_installed") == True + return config_json.get("is_installed") is True def download_archive(self): ext_zip_file = self.zip_path @@ -467,7 +467,7 @@ class InstalledExtensionMiddleware: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if not "path" in scope: + if "path" not in scope: await self.app(scope, receive, send) return diff --git a/lnbits/extensions/bleskomat/__init__.py b/lnbits/extensions/bleskomat/__init__.py index bef362dc7..df54fc5f5 100644 --- a/lnbits/extensions/bleskomat/__init__.py +++ b/lnbits/extensions/bleskomat/__init__.py @@ -21,6 +21,6 @@ def bleskomat_renderer(): return template_renderer(["lnbits/extensions/bleskomat/templates"]) -from .lnurl_api import * # noqa -from .views import * # noqa -from .views_api import * # noqa +from .lnurl_api import * # noqa: F401,F403 +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/bleskomat/exchange_rates.py b/lnbits/extensions/bleskomat/exchange_rates.py index c6f1d8801..aff9ce657 100644 --- a/lnbits/extensions/bleskomat/exchange_rates.py +++ b/lnbits/extensions/bleskomat/exchange_rates.py @@ -1,6 +1,6 @@ import json import os -from typing import Callable, Dict, Union +from typing import Callable, Union import httpx diff --git a/lnbits/extensions/bleskomat/helpers.py b/lnbits/extensions/bleskomat/helpers.py index 0b2f34710..f61a56403 100644 --- a/lnbits/extensions/bleskomat/helpers.py +++ b/lnbits/extensions/bleskomat/helpers.py @@ -128,7 +128,7 @@ def unshorten_lnurl_query(query: dict) -> Dict[str, str]: long_tag = rules["tags"][tag] new_query["tag"] = long_tag tag = long_tag - if not tag in rules["params"]: + if tag not in rules["params"]: raise LnurlValidationError(f'Unknown tag: "{tag}"') for key in query: if key in rules["params"][str(tag)]: @@ -142,7 +142,7 @@ def unshorten_lnurl_query(query: dict) -> Dict[str, str]: # Unshorten general keys: short_key = key long_key = rules["query"][short_key] - if not long_key in new_query: + if long_key not in new_query: if short_key in query: new_query[long_key] = query[short_key] else: diff --git a/lnbits/extensions/bleskomat/lnurl_api.py b/lnbits/extensions/bleskomat/lnurl_api.py index bdac5fecf..c892cc5ad 100644 --- a/lnbits/extensions/bleskomat/lnurl_api.py +++ b/lnbits/extensions/bleskomat/lnurl_api.py @@ -42,7 +42,7 @@ async def api_bleskomat_lnurl(req: Request): # The API key ID, nonce, and tag should be present in the query string. for field in ["id", "nonce", "tag"]: - if not field in query: + if field not in query: raise LnurlHttpError( f'Failed API key signature check: Missing "{field}"', HTTPStatus.BAD_REQUEST, @@ -105,7 +105,7 @@ async def api_bleskomat_lnurl(req: Request): # No signature provided. # Treat as "action" callback. - if not "k1" in query: + if "k1" not in query: raise LnurlHttpError("Missing secret", HTTPStatus.BAD_REQUEST) secret = query["k1"] diff --git a/lnbits/extensions/bleskomat/models.py b/lnbits/extensions/bleskomat/models.py index 6dc88dc07..5aec7969d 100644 --- a/lnbits/extensions/bleskomat/models.py +++ b/lnbits/extensions/bleskomat/models.py @@ -85,7 +85,7 @@ class BleskomatLnurl(BaseModel): # Perform tag-specific checks. if tag == "withdrawRequest": for field in ["pr"]: - if not field in query: + if field not in query: raise LnurlValidationError(f'Missing required parameter: "{field}"') # Check the bolt11 invoice(s) provided. pr = query["pr"] diff --git a/lnbits/extensions/boltcards/__init__.py b/lnbits/extensions/boltcards/__init__.py index bfdc7492e..5c6b87acf 100644 --- a/lnbits/extensions/boltcards/__init__.py +++ b/lnbits/extensions/boltcards/__init__.py @@ -24,14 +24,14 @@ def boltcards_renderer(): return template_renderer(["lnbits/extensions/boltcards/templates"]) -from .lnurl import * # noqa -from .tasks import * # noqa +from .lnurl import * # noqa: F401,F403 +from .tasks import * # noqa: F401,F403 def boltcards_start(): loop = asyncio.get_event_loop() - loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) + loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) # noqa: F405 -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/boltcards/crud.py b/lnbits/extensions/boltcards/crud.py index 9c7d299d6..0a678e709 100644 --- a/lnbits/extensions/boltcards/crud.py +++ b/lnbits/extensions/boltcards/crud.py @@ -160,7 +160,7 @@ async def update_card_otp(otp: str, id: str): async def get_hit(hit_id: str) -> Optional[Hit]: - row = await db.fetchone(f"SELECT * FROM boltcards.hits WHERE id = ?", (hit_id,)) + row = await db.fetchone("SELECT * FROM boltcards.hits WHERE id = ?", (hit_id,)) if not row: return None @@ -183,7 +183,7 @@ async def get_hits(cards_ids: List[str]) -> List[Hit]: async def get_hits_today(card_id: str) -> List[Hit]: rows = await db.fetchall( - f"SELECT * FROM boltcards.hits WHERE card_id = ?", + "SELECT * FROM boltcards.hits WHERE card_id = ?", (card_id,), ) updatedrow = [] @@ -258,7 +258,7 @@ async def create_refund(hit_id, refund_amount) -> Refund: async def get_refund(refund_id: str) -> Optional[Refund]: row = await db.fetchone( - f"SELECT * FROM boltcards.refunds WHERE id = ?", (refund_id,) + "SELECT * FROM boltcards.refunds WHERE id = ?", (refund_id,) ) if not row: return None diff --git a/lnbits/extensions/boltcards/lnurl.py b/lnbits/extensions/boltcards/lnurl.py index d04303725..3b99fdf22 100644 --- a/lnbits/extensions/boltcards/lnurl.py +++ b/lnbits/extensions/boltcards/lnurl.py @@ -28,6 +28,7 @@ from .nxp424 import decryptSUN, getSunMAC ###############LNURLWITHDRAW################# + # /boltcards/api/v1/scan?p=00000000000000000000000000000000&c=0000000000000000 @boltcards_ext.get("/api/v1/scan/{external_id}") async def api_scan(p, c, request: Request, external_id: str = Query(None)): @@ -123,7 +124,7 @@ async def lnurl_callback( wallet_id=card.wallet, payment_request=pr, max_sat=card.tx_limit, - extra={"tag": "boltcard", "tag": hit.id}, + extra={"tag": "boltcard", "hit": hit.id}, ) return {"status": "OK"} except Exception as exc: @@ -180,7 +181,7 @@ async def lnurlp_response(req: Request, hit_id: str = Query(None)): card = await get_card(hit.card_id) assert card if not hit: - return {"status": "ERROR", "reason": f"LNURL-pay record not found."} + return {"status": "ERROR", "reason": "LNURL-pay record not found."} if not card.enable: return {"status": "ERROR", "reason": "Card is disabled."} payResponse = { @@ -204,7 +205,7 @@ async def lnurlp_callback(hit_id: str = Query(None), amount: str = Query(None)): card = await get_card(hit.card_id) assert card if not hit: - return {"status": "ERROR", "reason": f"LNURL-pay record not found."} + return {"status": "ERROR", "reason": "LNURL-pay record not found."} _, payment_request = await create_invoice( wallet_id=card.wallet, diff --git a/lnbits/extensions/boltcards/migrations.py b/lnbits/extensions/boltcards/migrations.py index 9609e0c37..43d5bb0f7 100644 --- a/lnbits/extensions/boltcards/migrations.py +++ b/lnbits/extensions/boltcards/migrations.py @@ -1,6 +1,3 @@ -from lnbits.helpers import urlsafe_short_hash - - async def m001_initial(db): await db.execute( """ diff --git a/lnbits/extensions/boltz/__init__.py b/lnbits/extensions/boltz/__init__.py index 9a3d5d896..98255e5e5 100644 --- a/lnbits/extensions/boltz/__init__.py +++ b/lnbits/extensions/boltz/__init__.py @@ -25,8 +25,8 @@ boltz_static_files = [ ] from .tasks import check_for_pending_swaps, wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def boltz_start(): diff --git a/lnbits/extensions/boltz/crud.py b/lnbits/extensions/boltz/crud.py index 1c9eb700a..5ad923f6d 100644 --- a/lnbits/extensions/boltz/crud.py +++ b/lnbits/extensions/boltz/crud.py @@ -32,7 +32,7 @@ async def get_submarine_swaps(wallet_ids: Union[str, List[str]]) -> List[Submari async def get_all_pending_submarine_swaps() -> List[SubmarineSwap]: rows = await db.fetchall( - f"SELECT * FROM boltz.submarineswap WHERE status='pending' order by time DESC", + "SELECT * FROM boltz.submarineswap WHERE status='pending' order by time DESC", ) return [SubmarineSwap(**row) for row in rows] @@ -107,7 +107,7 @@ async def get_reverse_submarine_swaps( async def get_all_pending_reverse_submarine_swaps() -> List[ReverseSubmarineSwap]: rows = await db.fetchall( - f"SELECT * FROM boltz.reverse_submarineswap WHERE status='pending' order by time DESC" + "SELECT * FROM boltz.reverse_submarineswap WHERE status='pending' order by time DESC" ) return [ReverseSubmarineSwap(**row) for row in rows] diff --git a/lnbits/extensions/boltz/tasks.py b/lnbits/extensions/boltz/tasks.py index ba394164b..63b981b1c 100644 --- a/lnbits/extensions/boltz/tasks.py +++ b/lnbits/extensions/boltz/tasks.py @@ -101,10 +101,10 @@ async def check_for_pending_swaps(): swaps = await get_all_pending_submarine_swaps() reverse_swaps = await get_all_pending_reverse_submarine_swaps() if len(swaps) > 0 or len(reverse_swaps) > 0: - logger.debug(f"Boltz - startup swap check") + logger.debug("Boltz - startup swap check") except: logger.error( - f"Boltz - startup swap check, database is not created yet, do nothing" + "Boltz - startup swap check, database is not created yet, do nothing" ) return @@ -143,10 +143,10 @@ async def check_swap(swap: SubmarineSwap, client): timeout_block_height=swap.timeout_block_height, ) await update_swap_status(swap.id, "refunded") - except BoltzNotFoundException as exc: + except BoltzNotFoundException: logger.debug(f"Boltz - swap: {swap.boltz_id} does not exist.") await update_swap_status(swap.id, "failed") - except MempoolBlockHeightException as exc: + except MempoolBlockHeightException: logger.debug( f"Boltz - tried to refund swap: {swap.id}, but has not reached the timeout." ) @@ -171,7 +171,7 @@ async def check_reverse_swap(reverse_swap: ReverseSubmarineSwap, client): logger.debug(f"Boltz - swap_status: {str(exc)}") await update_swap_status(reverse_swap.id, "failed") # should only happen while development when regtest is reset - except BoltzNotFoundException as exc: + except BoltzNotFoundException: logger.debug(f"Boltz - reverse swap: {reverse_swap.boltz_id} does not exist.") await update_swap_status(reverse_swap.id, "failed") except Exception as exc: diff --git a/lnbits/extensions/boltz/views_api.py b/lnbits/extensions/boltz/views_api.py index 72f66420d..ffec612c6 100644 --- a/lnbits/extensions/boltz/views_api.py +++ b/lnbits/extensions/boltz/views_api.py @@ -37,7 +37,7 @@ from .utils import check_balance, create_boltz_client, execute_reverse_swap @boltz_ext.get( "/api/v1/swap/mempool", - name=f"boltz.get /swap/mempool", + name="boltz.get /swap/mempool", summary="get a the mempool url", description=""" This endpoint gets the URL from mempool.space @@ -52,7 +52,7 @@ async def api_mempool_url(): # NORMAL SWAP @boltz_ext.get( "/api/v1/swap", - name=f"boltz.get /swap", + name="boltz.get /swap", summary="get a list of swaps a swap", description=""" This endpoint gets a list of normal swaps. @@ -74,7 +74,7 @@ async def api_submarineswap( @boltz_ext.post( "/api/v1/swap/refund", - name=f"boltz.swap_refund", + name="boltz.swap_refund", summary="refund of a swap", description=""" This endpoint attempts to refund a normal swaps, creates onchain tx and sets swap status ro refunded. @@ -122,7 +122,7 @@ async def api_submarineswap_refund(swap_id: str): @boltz_ext.post( "/api/v1/swap", status_code=status.HTTP_201_CREATED, - name=f"boltz.post /swap", + name="boltz.post /swap", summary="create a submarine swap", description=""" This endpoint creates a submarine swap @@ -164,7 +164,7 @@ async def api_submarineswap_create(data: CreateSubmarineSwap): # REVERSE SWAP @boltz_ext.get( "/api/v1/swap/reverse", - name=f"boltz.get /swap/reverse", + name="boltz.get /swap/reverse", summary="get a list of reverse swaps", description=""" This endpoint gets a list of reverse swaps. @@ -187,7 +187,7 @@ async def api_reverse_submarineswap( @boltz_ext.post( "/api/v1/swap/reverse", status_code=status.HTTP_201_CREATED, - name=f"boltz.post /swap/reverse", + name="boltz.post /swap/reverse", summary="create a reverse submarine swap", description=""" This endpoint creates a reverse submarine swap @@ -221,7 +221,7 @@ async def api_reverse_submarineswap_create( @boltz_ext.get( "/api/v1/swap/reverse/auto", - name=f"boltz.get /swap/reverse/auto", + name="boltz.get /swap/reverse/auto", summary="get a list of auto reverse swaps", description=""" This endpoint gets a list of auto reverse swaps. @@ -244,7 +244,7 @@ async def api_auto_reverse_submarineswap( @boltz_ext.post( "/api/v1/swap/reverse/auto", status_code=status.HTTP_201_CREATED, - name=f"boltz.post /swap/reverse/auto", + name="boltz.post /swap/reverse/auto", summary="create a auto reverse submarine swap", description=""" This endpoint creates a auto reverse submarine swap @@ -273,7 +273,7 @@ async def api_auto_reverse_submarineswap_create(data: CreateAutoReverseSubmarine @boltz_ext.delete( "/api/v1/swap/reverse/auto/{swap_id}", - name=f"boltz.delete /swap/reverse/auto", + name="boltz.delete /swap/reverse/auto", summary="delete a auto reverse submarine swap", description=""" This endpoint deletes a auto reverse submarine swap @@ -288,7 +288,7 @@ async def api_auto_reverse_submarineswap_delete(swap_id: str): @boltz_ext.post( "/api/v1/swap/status", - name=f"boltz.swap_status", + name="boltz.swap_status", summary="shows the status of a swap", description=""" This endpoint attempts to get the status of the swap. @@ -315,7 +315,7 @@ async def api_swap_status(swap_id: str): @boltz_ext.get( "/api/v1/swap/boltz", - name=f"boltz.get /swap/boltz", + name="boltz.get /swap/boltz", summary="get a boltz configuration", description=""" This endpoint gets configuration for boltz. (limits, fees...) diff --git a/lnbits/extensions/cashu/__init__.py b/lnbits/extensions/cashu/__init__.py index 83d8ce274..ca831ce0e 100644 --- a/lnbits/extensions/cashu/__init__.py +++ b/lnbits/extensions/cashu/__init__.py @@ -10,7 +10,6 @@ from lnbits.tasks import catch_everything_and_restart db = Database("ext_cashu") -import sys cashu_static_files = [ { @@ -38,8 +37,8 @@ def cashu_renderer(): from .tasks import startup_cashu_mint, wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def cashu_start(): diff --git a/lnbits/extensions/cashu/crud.py b/lnbits/extensions/cashu/crud.py index 23f808c11..e27cc98cc 100644 --- a/lnbits/extensions/cashu/crud.py +++ b/lnbits/extensions/cashu/crud.py @@ -1,18 +1,7 @@ -import os -import random -import time -from typing import Any, List, Optional, Union - -from cashu.core.base import MintKeyset -from embit import bip32, bip39, ec, script -from embit.networks import NETWORKS -from loguru import logger - -from lnbits.db import Connection, Database -from lnbits.helpers import urlsafe_short_hash +from typing import List, Optional, Union from . import db -from .models import Cashu, Pegs, Promises, Proof +from .models import Cashu async def create_cashu( diff --git a/lnbits/extensions/cashu/models.py b/lnbits/extensions/cashu/models.py index c820d12ec..84f28c2bc 100644 --- a/lnbits/extensions/cashu/models.py +++ b/lnbits/extensions/cashu/models.py @@ -1,5 +1,5 @@ from sqlite3 import Row -from typing import List, Union +from typing import List from fastapi import Query from pydantic import BaseModel diff --git a/lnbits/extensions/cashu/tasks.py b/lnbits/extensions/cashu/tasks.py index bf49171c8..982d3ac18 100644 --- a/lnbits/extensions/cashu/tasks.py +++ b/lnbits/extensions/cashu/tasks.py @@ -1,5 +1,4 @@ import asyncio -import json from cashu.core.migrations import migrate_databases from cashu.mint import migrations @@ -8,14 +7,12 @@ from lnbits.core.models import Payment from lnbits.tasks import register_invoice_listener from . import db, ledger -from .crud import get_cashu async def startup_cashu_mint(): await migrate_databases(db, migrations) await ledger.load_used_proofs() await ledger.init_keysets(autosave=False) - pass async def wait_for_paid_invoices(): diff --git a/lnbits/extensions/cashu/views_api.py b/lnbits/extensions/cashu/views_api.py index 69e3d26ae..682412a4e 100644 --- a/lnbits/extensions/cashu/views_api.py +++ b/lnbits/extensions/cashu/views_api.py @@ -1,6 +1,6 @@ import math from http import HTTPStatus -from typing import Dict, List, Union +from typing import Dict, Union # -------- cashu imports from cashu.core.base import ( @@ -322,7 +322,7 @@ async def melt_coins( await pay_invoice( wallet_id=cashu.wallet, payment_request=invoice, - description=f"Pay cashu invoice", + description="Pay cashu invoice", extra={"tag": "cashu", "cashu_name": cashu.name}, ) except Exception as e: @@ -335,7 +335,7 @@ async def melt_coins( status: PaymentStatus = await check_transaction_status( cashu.wallet, invoice_obj.payment_hash ) - if status.paid == True: + if status.paid is True: logger.debug( f"Cashu: Payment successful, invalidating proofs for {invoice_obj.payment_hash}" ) @@ -349,7 +349,7 @@ async def melt_coins( detail=f"Cashu: {str(e)}", ) finally: - logger.debug(f"Cashu: Unset pending") + logger.debug("Cashu: Unset pending") # delete proofs from pending list await ledger._unset_proofs_pending(proofs) diff --git a/lnbits/extensions/deezy/__init__.py b/lnbits/extensions/deezy/__init__.py index 05d1c9a70..60596445c 100644 --- a/lnbits/extensions/deezy/__init__.py +++ b/lnbits/extensions/deezy/__init__.py @@ -21,5 +21,5 @@ def deezy_renderer(): return template_renderer(["lnbits/extensions/deezy/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/deezy/crud.py b/lnbits/extensions/deezy/crud.py index 75549349e..38adc2666 100644 --- a/lnbits/extensions/deezy/crud.py +++ b/lnbits/extensions/deezy/crud.py @@ -1,4 +1,3 @@ -from http import HTTPStatus from typing import List, Optional from . import db @@ -8,7 +7,7 @@ from .models import BtcToLnSwap, LnToBtcSwap, Token, UpdateLnToBtcSwap async def get_ln_to_btc() -> List[LnToBtcSwap]: rows = await db.fetchall( - f"SELECT * FROM deezy.ln_to_btc_swap ORDER BY created_at DESC", + "SELECT * FROM deezy.ln_to_btc_swap ORDER BY created_at DESC", ) return [LnToBtcSwap(**row) for row in rows] @@ -17,7 +16,7 @@ async def get_ln_to_btc() -> List[LnToBtcSwap]: async def get_btc_to_ln() -> List[BtcToLnSwap]: rows = await db.fetchall( - f"SELECT * FROM deezy.btc_to_ln_swap ORDER BY created_at DESC", + "SELECT * FROM deezy.btc_to_ln_swap ORDER BY created_at DESC", ) return [BtcToLnSwap(**row) for row in rows] @@ -26,7 +25,7 @@ async def get_btc_to_ln() -> List[BtcToLnSwap]: async def get_token() -> Optional[Token]: row = await db.fetchone( - f"SELECT * FROM deezy.token ORDER BY created_at DESC", + "SELECT * FROM deezy.token ORDER BY created_at DESC", ) return Token(**row) if row else None diff --git a/lnbits/extensions/deezy/migrations.py b/lnbits/extensions/deezy/migrations.py index 67455d6b5..42c3973e9 100644 --- a/lnbits/extensions/deezy/migrations.py +++ b/lnbits/extensions/deezy/migrations.py @@ -15,7 +15,7 @@ async def m001_initial(db): """ ) await db.execute( - f""" + """ CREATE TABLE deezy.btc_to_ln_swap ( id TEXT PRIMARY KEY, ln_address TEXT NOT NULL, @@ -28,7 +28,7 @@ async def m001_initial(db): """ ) await db.execute( - f""" + """ CREATE TABLE deezy.token ( deezy_token TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP diff --git a/lnbits/extensions/deezy/models.py b/lnbits/extensions/deezy/models.py index e69db355a..ad0c03cba 100644 --- a/lnbits/extensions/deezy/models.py +++ b/lnbits/extensions/deezy/models.py @@ -1,7 +1,4 @@ -from typing import Optional - from pydantic.main import BaseModel -from sqlalchemy.engine import base # type: ignore class Token(BaseModel): diff --git a/lnbits/extensions/deezy/views.py b/lnbits/extensions/deezy/views.py index 131c03b2a..c4cc4b22c 100644 --- a/lnbits/extensions/deezy/views.py +++ b/lnbits/extensions/deezy/views.py @@ -1,4 +1,4 @@ -from fastapi import FastAPI, Request +from fastapi import Request from fastapi.params import Depends from fastapi.templating import Jinja2Templates from starlette.responses import HTMLResponse diff --git a/lnbits/extensions/discordbot/__init__.py b/lnbits/extensions/discordbot/__init__.py index 21989b24a..ad4c76708 100644 --- a/lnbits/extensions/discordbot/__init__.py +++ b/lnbits/extensions/discordbot/__init__.py @@ -21,5 +21,5 @@ def discordbot_renderer(): return template_renderer(["lnbits/extensions/discordbot/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/discordbot/models.py b/lnbits/extensions/discordbot/models.py index 8b9cd822a..85f527a5a 100644 --- a/lnbits/extensions/discordbot/models.py +++ b/lnbits/extensions/discordbot/models.py @@ -1,5 +1,4 @@ from sqlite3 import Row -from typing import Optional from fastapi.param_functions import Query from pydantic import BaseModel diff --git a/lnbits/extensions/events/__init__.py b/lnbits/extensions/events/__init__.py index b2cb75406..b9283368b 100644 --- a/lnbits/extensions/events/__init__.py +++ b/lnbits/extensions/events/__init__.py @@ -26,8 +26,8 @@ def events_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def events_start(): diff --git a/lnbits/extensions/events/views_api.py b/lnbits/extensions/events/views_api.py index 5ec9b916e..f27485d87 100644 --- a/lnbits/extensions/events/views_api.py +++ b/lnbits/extensions/events/views_api.py @@ -50,12 +50,12 @@ async def api_event_create( event = await get_event(event_id) if not event: raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist." + status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist." ) if event.wallet != wallet.wallet.id: raise HTTPException( - status_code=HTTPStatus.FORBIDDEN, detail=f"Not your event." + status_code=HTTPStatus.FORBIDDEN, detail="Not your event." ) event = await update_event(event_id, **data.dict()) else: @@ -69,11 +69,11 @@ async def api_form_delete(event_id, wallet: WalletTypeInfo = Depends(get_key_typ event = await get_event(event_id) if not event: raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist." + status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist." ) if event.wallet != wallet.wallet.id: - raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=f"Not your event.") + raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your event.") await delete_event(event_id) await delete_event_tickets(event_id) @@ -101,7 +101,7 @@ async def api_ticket_make_ticket(event_id, name, email): event = await get_event(event_id) if not event: raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail=f"Event does not exist." + status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist." ) try: payment_hash, payment_request = await create_invoice( @@ -121,7 +121,7 @@ async def api_ticket_send_ticket(event_id, payment_hash, data: CreateTicket): if not event: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, - detail=f"Event could not be fetched.", + detail="Event could not be fetched.", ) status = await api_payment(payment_hash) @@ -141,7 +141,7 @@ async def api_ticket_send_ticket(event_id, payment_hash, data: CreateTicket): if not ticket: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, - detail=f"Event could not be fetched.", + detail="Event could not be fetched.", ) return {"paid": True, "ticket_id": ticket.id} return {"paid": False} @@ -152,13 +152,11 @@ async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_ ticket = await get_ticket(ticket_id) if not ticket: raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail=f"Ticket does not exist." + status_code=HTTPStatus.NOT_FOUND, detail="Ticket does not exist." ) if ticket.wallet != wallet.wallet.id: - raise HTTPException( - status_code=HTTPStatus.FORBIDDEN, detail=f"Not your ticket." - ) + raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your ticket.") await delete_ticket(ticket_id) return "", HTTPStatus.NO_CONTENT @@ -188,7 +186,7 @@ async def api_event_register_ticket(ticket_id): status_code=HTTPStatus.FORBIDDEN, detail="Ticket not paid for." ) - if ticket.registered == True: + if ticket.registered is True: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Ticket already registered" ) diff --git a/lnbits/extensions/example/__init__.py b/lnbits/extensions/example/__init__.py index 8cd9211b3..a78330e9d 100644 --- a/lnbits/extensions/example/__init__.py +++ b/lnbits/extensions/example/__init__.py @@ -25,8 +25,8 @@ def example_renderer(): from .tasks import wait_for_paid_invoices -from .views import * -from .views_api import * +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def tpos_start(): diff --git a/lnbits/extensions/gerty/__init__.py b/lnbits/extensions/gerty/__init__.py index 5b24718ac..8eb76ec1b 100644 --- a/lnbits/extensions/gerty/__init__.py +++ b/lnbits/extensions/gerty/__init__.py @@ -1,5 +1,3 @@ -import asyncio - from fastapi import APIRouter from fastapi.staticfiles import StaticFiles @@ -24,5 +22,5 @@ def gerty_renderer(): return template_renderer(["lnbits/extensions/gerty/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/gerty/crud.py b/lnbits/extensions/gerty/crud.py index 24e8ef25a..6dccf325b 100644 --- a/lnbits/extensions/gerty/crud.py +++ b/lnbits/extensions/gerty/crud.py @@ -8,7 +8,7 @@ from loguru import logger from lnbits.helpers import urlsafe_short_hash from . import db -from .models import Gerty, Mempool, MempoolEndpoint +from .models import Gerty, MempoolEndpoint async def create_gerty(wallet_id: str, data: Gerty) -> Gerty: diff --git a/lnbits/extensions/gerty/helpers.py b/lnbits/extensions/gerty/helpers.py index a3422b794..4700f55b7 100644 --- a/lnbits/extensions/gerty/helpers.py +++ b/lnbits/extensions/gerty/helpers.py @@ -13,7 +13,7 @@ from lnbits.settings import settings from lnbits.utils.exchange_rates import satoshis_amount_as_fiat from .crud import get_mempool_info -from .number_prefixer import * +from .number_prefixer import * # noqa: F403 def get_percent_difference(current, previous, precision=3): @@ -110,7 +110,9 @@ async def get_mining_dashboard(gerty): ) text.append( get_text_item_dict( - text="{0}hash".format(si_format(hashrateNow, 6, True, " ")), + text="{0}hash".format( + si_format(hashrateNow, 6, True, " ") # noqa: F405 + ), font_size=20, gerty_type=gerty.type, ) @@ -320,7 +322,9 @@ async def get_mining_stat(stat_slug: str, gerty): text = [] if stat_slug == "mining_current_hash_rate": stat = await api_get_mining_stat(stat_slug, gerty) - current = "{0}hash".format(si_format(stat["current"], 6, True, " ")) + current = "{0}hash".format( + si_format(stat["current"], 6, True, " ") # noqa: F405 + ) text.append( get_text_item_dict( text="Current Mining Hashrate", font_size=20, gerty_type=gerty.type diff --git a/lnbits/extensions/gerty/migrations.py b/lnbits/extensions/gerty/migrations.py index afef2cfd8..75921a403 100644 --- a/lnbits/extensions/gerty/migrations.py +++ b/lnbits/extensions/gerty/migrations.py @@ -68,7 +68,7 @@ async def m006_add_gerty_model_col(db): """ await db.execute("ALTER TABLE gerty.mempool RENAME TO mempool_old") await db.execute( - f""" + """ CREATE TABLE gerty.mempool ( id TEXT PRIMARY KEY, mempool_endpoint TEXT NOT NULL, diff --git a/lnbits/extensions/gerty/number_prefixer.py b/lnbits/extensions/gerty/number_prefixer.py index eab684e7a..dca001087 100644 --- a/lnbits/extensions/gerty/number_prefixer.py +++ b/lnbits/extensions/gerty/number_prefixer.py @@ -31,7 +31,7 @@ def si_formatter(value): the value cannot be classified. """ classifier = si_classifier(value) - if classifier == None: + if classifier is None: # Don't know how to classify this value return None @@ -48,7 +48,7 @@ def si_format(value, precision=4, long_form=False, separator=""): """ scaled, short_suffix, long_suffix = si_formatter(value) - if scaled == None: + if scaled is None: # Don't know how to format this value return value diff --git a/lnbits/extensions/hivemind/__init__.py b/lnbits/extensions/hivemind/__init__.py index afa677ced..066963f0b 100644 --- a/lnbits/extensions/hivemind/__init__.py +++ b/lnbits/extensions/hivemind/__init__.py @@ -21,4 +21,4 @@ hivemind_static_files = [ } ] -from .views import * # noqa +from .views import * # noqa: F401,F403 diff --git a/lnbits/extensions/invoices/__init__.py b/lnbits/extensions/invoices/__init__.py index 0b60837bb..735e95d81 100644 --- a/lnbits/extensions/invoices/__init__.py +++ b/lnbits/extensions/invoices/__init__.py @@ -32,5 +32,5 @@ def invoices_start(): loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/invoices/crud.py b/lnbits/extensions/invoices/crud.py index 9a05f9c52..396528025 100644 --- a/lnbits/extensions/invoices/crud.py +++ b/lnbits/extensions/invoices/crud.py @@ -23,7 +23,7 @@ async def get_invoice(invoice_id: str) -> Optional[Invoice]: async def get_invoice_items(invoice_id: str) -> List[InvoiceItem]: rows = await db.fetchall( - f"SELECT * FROM invoices.invoice_items WHERE invoice_id = ?", (invoice_id,) + "SELECT * FROM invoices.invoice_items WHERE invoice_id = ?", (invoice_id,) ) return [InvoiceItem.from_row(row) for row in rows] @@ -54,7 +54,7 @@ async def get_invoices(wallet_ids: Union[str, List[str]]) -> List[Invoice]: async def get_invoice_payments(invoice_id: str) -> List[Payment]: rows = await db.fetchall( - f"SELECT * FROM invoices.payments WHERE invoice_id = ?", (invoice_id,) + "SELECT * FROM invoices.payments WHERE invoice_id = ?", (invoice_id,) ) return [Payment.from_row(row) for row in rows] diff --git a/lnbits/extensions/jukebox/__init__.py b/lnbits/extensions/jukebox/__init__.py index 4559dccfd..6307c923a 100644 --- a/lnbits/extensions/jukebox/__init__.py +++ b/lnbits/extensions/jukebox/__init__.py @@ -25,8 +25,8 @@ def jukebox_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def jukebox_start(): diff --git a/lnbits/extensions/jukebox/crud.py b/lnbits/extensions/jukebox/crud.py index fe710f601..f046727b2 100644 --- a/lnbits/extensions/jukebox/crud.py +++ b/lnbits/extensions/jukebox/crud.py @@ -58,7 +58,7 @@ async def get_jukebox_by_user(user: str) -> Optional[Jukebox]: async def get_jukeboxs(user: str) -> List[Jukebox]: rows = await db.fetchall('SELECT * FROM jukebox.jukebox WHERE "user" = ?', (user,)) for row in rows: - if row.sp_playlists == None: + if row.sp_playlists is None: await delete_jukebox(row.id) rows = await db.fetchall('SELECT * FROM jukebox.jukebox WHERE "user" = ?', (user,)) diff --git a/lnbits/extensions/jukebox/views_api.py b/lnbits/extensions/jukebox/views_api.py index 0cca8fc85..8e0bdd27c 100644 --- a/lnbits/extensions/jukebox/views_api.py +++ b/lnbits/extensions/jukebox/views_api.py @@ -123,7 +123,7 @@ async def api_get_jukebox_song( if "items" not in r.json(): if r.status_code == 401: token = await api_get_token(juke_id) - if token == False: + if token is False: return False elif retry: raise HTTPException( @@ -205,7 +205,7 @@ async def api_get_jukebox_device_check( return json.loads(rDevice.text) elif rDevice.status_code == 401 or rDevice.status_code == 403: token = await api_get_token(juke_id) - if token == False: + if token is False: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="No devices connected" ) @@ -309,7 +309,7 @@ async def api_get_jukebox_invoice_paid( if rDevice.status_code == 200: isPlaying = rDevice.json()["is_playing"] - if r.status_code == 204 or isPlaying == False: + if r.status_code == 204 or isPlaying is False: async with httpx.AsyncClient() as client: uri = ["spotify:track:" + song_id] assert jukebox.sp_device @@ -324,7 +324,7 @@ async def api_get_jukebox_invoice_paid( return jukebox_payment elif r.status_code == 401 or r.status_code == 403: token = await api_get_token(juke_id) - if token == False: + if token is False: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid", @@ -359,7 +359,7 @@ async def api_get_jukebox_invoice_paid( elif r.status_code == 401 or r.status_code == 403: token = await api_get_token(juke_id) - if token == False: + if token is False: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid", @@ -379,7 +379,7 @@ async def api_get_jukebox_invoice_paid( ) elif r.status_code == 401 or r.status_code == 403: token = await api_get_token(juke_id) - if token == False: + if token is False: raise HTTPException( status_code=HTTPStatus.OK, detail="Invoice not paid" ) @@ -433,7 +433,7 @@ async def api_get_jukebox_currently( elif r.status_code == 401: token = await api_get_token(juke_id) - if token == False: + if token is False: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid" ) diff --git a/lnbits/extensions/livestream/__init__.py b/lnbits/extensions/livestream/__init__.py index e5f2987c8..accd61de3 100644 --- a/lnbits/extensions/livestream/__init__.py +++ b/lnbits/extensions/livestream/__init__.py @@ -24,10 +24,10 @@ def livestream_renderer(): return template_renderer(["lnbits/extensions/livestream/templates"]) -from .lnurl import * # noqa +from .lnurl import * # noqa: F401,F403 from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def livestream_start(): diff --git a/lnbits/extensions/livestream/tasks.py b/lnbits/extensions/livestream/tasks.py index 9837654ee..4489dad98 100644 --- a/lnbits/extensions/livestream/tasks.py +++ b/lnbits/extensions/livestream/tasks.py @@ -1,9 +1,7 @@ import asyncio -import json from loguru import logger -from lnbits.core import db as core_db from lnbits.core.models import Payment from lnbits.core.services import create_invoice, pay_invoice from lnbits.helpers import get_current_extension_name diff --git a/lnbits/extensions/lnaddress/__init__.py b/lnbits/extensions/lnaddress/__init__.py index a507a1dc7..dcc4a9516 100644 --- a/lnbits/extensions/lnaddress/__init__.py +++ b/lnbits/extensions/lnaddress/__init__.py @@ -24,10 +24,10 @@ def lnaddress_renderer(): return template_renderer(["lnbits/extensions/lnaddress/templates"]) -from .lnurl import * # noqa +from .lnurl import * # noqa: F401,F403 from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def lnaddress_start(): diff --git a/lnbits/extensions/lnaddress/cloudflare.py b/lnbits/extensions/lnaddress/cloudflare.py index cf8feaf02..558bca7d0 100644 --- a/lnbits/extensions/lnaddress/cloudflare.py +++ b/lnbits/extensions/lnaddress/cloudflare.py @@ -1,5 +1,3 @@ -import json - import httpx from .models import Domains diff --git a/lnbits/extensions/lnaddress/crud.py b/lnbits/extensions/lnaddress/crud.py index 0e590ec8d..a0201ee64 100644 --- a/lnbits/extensions/lnaddress/crud.py +++ b/lnbits/extensions/lnaddress/crud.py @@ -130,7 +130,7 @@ async def set_address_paid(payment_hash: str) -> Addresses: address = await get_address(payment_hash) assert address - if address.paid == False: + if address.paid is False: await db.execute( """ UPDATE lnaddress.address diff --git a/lnbits/extensions/lnaddress/lnurl.py b/lnbits/extensions/lnaddress/lnurl.py index c4c3cea55..b38da954b 100644 --- a/lnbits/extensions/lnaddress/lnurl.py +++ b/lnbits/extensions/lnaddress/lnurl.py @@ -39,7 +39,7 @@ async def lnurl_response(username: str, domain: str, request: Request): 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="Address not found").dict() amount_received = amount diff --git a/lnbits/extensions/lndhub/__init__.py b/lnbits/extensions/lndhub/__init__.py index 1d1effcf0..344e91c66 100644 --- a/lnbits/extensions/lndhub/__init__.py +++ b/lnbits/extensions/lndhub/__init__.py @@ -21,7 +21,7 @@ def lndhub_renderer(): return template_renderer(["lnbits/extensions/lndhub/templates"]) -from .decorators import * # noqa -from .utils import * # noqa -from .views import * # noqa -from .views_api import * # noqa +from .decorators import * # noqa: F401,F403 +from .utils import * # noqa: F401,F403 +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/lndhub/views_api.py b/lnbits/extensions/lndhub/views_api.py index 1dff52351..059604f28 100644 --- a/lnbits/extensions/lndhub/views_api.py +++ b/lnbits/extensions/lndhub/views_api.py @@ -228,4 +228,3 @@ async def lndhub_decodeinvoice(invoice: str = Query(None)): @lndhub_ext.get("/ext/checkrouteinvoice") async def lndhub_checkrouteinvoice(): "not implemented on canonical lndhub" - pass diff --git a/lnbits/extensions/lnurldevice/__init__.py b/lnbits/extensions/lnurldevice/__init__.py index 8ef391451..56e9d8f7d 100644 --- a/lnbits/extensions/lnurldevice/__init__.py +++ b/lnbits/extensions/lnurldevice/__init__.py @@ -24,10 +24,10 @@ def lnurldevice_renderer(): return template_renderer(["lnbits/extensions/lnurldevice/templates"]) -from .lnurl import * # noqa +from .lnurl import * # noqa: F401,F403 from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def lnurldevice_start(): diff --git a/lnbits/extensions/lnurldevice/crud.py b/lnbits/extensions/lnurldevice/crud.py index 0ab520da7..8e15d4ec6 100644 --- a/lnbits/extensions/lnurldevice/crud.py +++ b/lnbits/extensions/lnurldevice/crud.py @@ -1,4 +1,4 @@ -from typing import List, Optional, Union +from typing import List, Optional import shortuuid diff --git a/lnbits/extensions/lnurldevice/lnurl.py b/lnbits/extensions/lnurldevice/lnurl.py index eba2a6930..20e113d54 100644 --- a/lnbits/extensions/lnurldevice/lnurl.py +++ b/lnbits/extensions/lnurldevice/lnurl.py @@ -3,7 +3,6 @@ import hmac from http import HTTPStatus from io import BytesIO -import shortuuid from embit import bech32, compact from fastapi import HTTPException, Query, Request @@ -17,7 +16,6 @@ from .crud import ( create_lnurldevicepayment, get_lnurldevice, get_lnurldevicepayment, - get_lnurlpayload, update_lnurldevicepayment, ) @@ -116,7 +114,7 @@ async def lnurl_v1_params( if switch[0] == gpio and switch[1] == profit and switch[2] == amount: check = True if not check: - return {"status": "ERROR", "reason": f"Switch params wrong"} + return {"status": "ERROR", "reason": "Switch params wrong"} lnurldevicepayment = await create_lnurldevicepayment( deviceid=device.id, @@ -226,7 +224,7 @@ async def lnurl_callback( ) if device.device == "atm": if lnurldevicepayment.payload == lnurldevicepayment.payhash: - return {"status": "ERROR", "reason": f"Payment already claimed"} + return {"status": "ERROR", "reason": "Payment already claimed"} if not pr: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="No payment request" @@ -240,7 +238,7 @@ async def lnurl_callback( if lnurldevicepayment.payload != k1: return {"status": "ERROR", "reason": "Bad K1"} if lnurldevicepayment.payhash != "payment_hash": - return {"status": "ERROR", "reason": f"Payment already claimed"} + return {"status": "ERROR", "reason": "Payment already claimed"} lnurldevicepayment_updated = await update_lnurldevicepayment( lnurldevicepayment_id=paymentid, payhash=lnurldevicepayment.payload diff --git a/lnbits/extensions/lnurldevice/migrations.py b/lnbits/extensions/lnurldevice/migrations.py index 1df04075d..7fd7d6c40 100644 --- a/lnbits/extensions/lnurldevice/migrations.py +++ b/lnbits/extensions/lnurldevice/migrations.py @@ -29,7 +29,7 @@ async def m001_initial(db): payhash TEXT, payload TEXT NOT NULL, pin INT, - sats {db.big_int}, + sats {db.big_int}, timestamp TIMESTAMP NOT NULL DEFAULT {db.timestamp_now} ); """ diff --git a/lnbits/extensions/lnurlp/__init__.py b/lnbits/extensions/lnurlp/__init__.py index e2486df05..f5ea0cd29 100644 --- a/lnbits/extensions/lnurlp/__init__.py +++ b/lnbits/extensions/lnurlp/__init__.py @@ -24,10 +24,10 @@ def lnurlp_renderer(): return template_renderer(["lnbits/extensions/lnurlp/templates"]) -from .lnurl import * # noqa +from .lnurl import * # noqa: F401,F403 from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def lnurlp_start(): diff --git a/lnbits/extensions/lnurlp/crud.py b/lnbits/extensions/lnurlp/crud.py index d5963b958..4acb4a41e 100644 --- a/lnbits/extensions/lnurlp/crud.py +++ b/lnbits/extensions/lnurlp/crud.py @@ -10,7 +10,7 @@ async def create_pay_link(data: CreatePayLinkData, wallet_id: str) -> PayLink: link_id = urlsafe_short_hash()[:6] result = await db.execute( - f""" + """ INSERT INTO lnurlp.pay_links ( id, wallet, @@ -46,6 +46,7 @@ async def create_pay_link(data: CreatePayLinkData, wallet_id: str) -> PayLink: data.fiat_base_multiplier, ), ) + assert result link = await get_pay_link(link_id) assert link, "Newly created link couldn't be retrieved" diff --git a/lnbits/extensions/lnurlp/lnurl.py b/lnbits/extensions/lnurlp/lnurl.py index 99de459cf..918a5bd39 100644 --- a/lnbits/extensions/lnurlp/lnurl.py +++ b/lnbits/extensions/lnurlp/lnurl.py @@ -1,5 +1,3 @@ -import hashlib -import math from http import HTTPStatus from fastapi import Request diff --git a/lnbits/extensions/lnurlp/views_api.py b/lnbits/extensions/lnurlp/views_api.py index a7bf0761a..badaaebfa 100644 --- a/lnbits/extensions/lnurlp/views_api.py +++ b/lnbits/extensions/lnurlp/views_api.py @@ -83,7 +83,7 @@ async def api_link_create_or_update( detail="Min is greater than max.", status_code=HTTPStatus.BAD_REQUEST ) - if data.currency == None and ( + if data.currency is None and ( round(data.min) != data.min or round(data.max) != data.max or data.min < 1 ): raise HTTPException( diff --git a/lnbits/extensions/market/__init__.py b/lnbits/extensions/market/__init__.py index 3795ec73f..a14fe6afc 100644 --- a/lnbits/extensions/market/__init__.py +++ b/lnbits/extensions/market/__init__.py @@ -34,8 +34,8 @@ def market_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def market_start(): diff --git a/lnbits/extensions/market/crud.py b/lnbits/extensions/market/crud.py index 1d9c28be6..c2a6ace12 100644 --- a/lnbits/extensions/market/crud.py +++ b/lnbits/extensions/market/crud.py @@ -1,18 +1,14 @@ -from base64 import urlsafe_b64encode from typing import List, Optional, Union -from uuid import uuid4 # from lnbits.db import open_ext_db from lnbits.db import SQLITE from lnbits.helpers import urlsafe_short_hash -from lnbits.settings import WALLET from . import db from .models import ( ChatMessage, CreateChatMessage, CreateMarket, - CreateMarketStalls, Market, MarketSettings, OrderDetail, @@ -33,7 +29,7 @@ from .models import ( async def create_market_product(data: createProduct) -> Products: product_id = urlsafe_short_hash() await db.execute( - f""" + """ INSERT INTO market.products (id, stall, product, categories, description, image, price, quantity) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, @@ -95,7 +91,7 @@ async def delete_market_product(product_id: str) -> None: async def create_market_zone(user, data: createZones) -> Zones: zone_id = urlsafe_short_hash() await db.execute( - f""" + """ INSERT INTO market.zones ( id, "user", @@ -143,7 +139,7 @@ async def delete_market_zone(zone_id: str) -> None: async def create_market_stall(data: createStalls) -> Stalls: stall_id = urlsafe_short_hash() await db.execute( - f""" + """ INSERT INTO market.stalls ( id, wallet, @@ -257,7 +253,7 @@ async def create_market_order_details(order_id: str, data: List[createOrderDetai async def get_market_order_details(order_id: str) -> List[OrderDetail]: rows = await db.fetchall( - f"SELECT * FROM market.order_details WHERE order_id = ?", (order_id,) + "SELECT * FROM market.order_details WHERE order_id = ?", (order_id,) ) return [OrderDetail(**row) for row in rows] diff --git a/lnbits/extensions/market/migrations.py b/lnbits/extensions/market/migrations.py index 72b584f96..81c3e14f9 100644 --- a/lnbits/extensions/market/migrations.py +++ b/lnbits/extensions/market/migrations.py @@ -139,7 +139,7 @@ async def m001_initial(db): id_conversation TEXT NOT NULL, timestamp TIMESTAMP NOT NULL DEFAULT """ + db.timestamp_now - + """ + + """ ); """ ) diff --git a/lnbits/extensions/market/views.py b/lnbits/extensions/market/views.py index e6c8eeff1..0bcfac459 100644 --- a/lnbits/extensions/market/views.py +++ b/lnbits/extensions/market/views.py @@ -1,6 +1,5 @@ import json from http import HTTPStatus -from typing import List from fastapi import ( BackgroundTasks, @@ -11,7 +10,6 @@ from fastapi import ( WebSocketDisconnect, ) from fastapi.templating import Jinja2Templates -from loguru import logger from starlette.exceptions import HTTPException from starlette.responses import HTMLResponse @@ -20,7 +18,6 @@ from lnbits.decorators import check_user_exists from . import market_ext, market_renderer from .crud import ( - create_chat_message, create_market_settings, get_market_market, get_market_market_stalls, @@ -30,10 +27,8 @@ from .crud import ( get_market_settings, get_market_stall, get_market_zone, - get_market_zones, - update_market_product_stock, ) -from .models import CreateChatMessage, SetSettings +from .models import SetSettings from .notifier import Notifier templates = Jinja2Templates(directory="templates") diff --git a/lnbits/extensions/market/views_api.py b/lnbits/extensions/market/views_api.py index 31703e8d7..ad0cbb463 100644 --- a/lnbits/extensions/market/views_api.py +++ b/lnbits/extensions/market/views_api.py @@ -1,9 +1,6 @@ -from base64 import urlsafe_b64encode from http import HTTPStatus -from typing import List, Union -from uuid import uuid4 -from fastapi import Body, Depends, Query, Request +from fastapi import Depends, Query from loguru import logger from starlette.exceptions import HTTPException @@ -17,7 +14,7 @@ from lnbits.decorators import ( require_invoice_key, ) from lnbits.helpers import urlsafe_short_hash -from lnbits.utils.exchange_rates import currencies, get_fiat_rate_satoshis +from lnbits.utils.exchange_rates import currencies from . import db, market_ext from .crud import ( @@ -48,7 +45,6 @@ from .crud import ( get_market_settings, get_market_stall, get_market_stalls, - get_market_stalls_by_ids, get_market_zone, get_market_zones, set_market_order_pubkey, @@ -60,12 +56,7 @@ from .crud import ( ) from .models import ( CreateMarket, - CreateMarketStalls, - Orders, - Products, SetSettings, - Stalls, - Zones, createOrder, createProduct, createStalls, @@ -312,7 +303,7 @@ async def api_market_order_create(data: createOrder): payment_hash, payment_request = await create_invoice( wallet_id=data.wallet, amount=data.total, - memo=f"New order on Market", + memo="New order on Market", extra={ "tag": "market", "reference": ref, diff --git a/lnbits/extensions/ngrok/__init__.py b/lnbits/extensions/ngrok/__init__.py index 0ef256d13..16ac46507 100644 --- a/lnbits/extensions/ngrok/__init__.py +++ b/lnbits/extensions/ngrok/__init__.py @@ -12,4 +12,4 @@ def ngrok_renderer(): return template_renderer(["lnbits/extensions/ngrok/templates"]) -from .views import * +from .views import * # noqa: F401,F403 diff --git a/lnbits/extensions/nostrnip5/__init__.py b/lnbits/extensions/nostrnip5/__init__.py index a9a2ea1ce..a9cb526d5 100644 --- a/lnbits/extensions/nostrnip5/__init__.py +++ b/lnbits/extensions/nostrnip5/__init__.py @@ -32,5 +32,5 @@ def nostrnip5_start(): loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/nostrnip5/crud.py b/lnbits/extensions/nostrnip5/crud.py index 66b9840b3..f7ec929c7 100644 --- a/lnbits/extensions/nostrnip5/crud.py +++ b/lnbits/extensions/nostrnip5/crud.py @@ -58,7 +58,7 @@ async def get_address_by_local_part( async def get_addresses(domain_id: str) -> List[Address]: rows = await db.fetchall( - f"SELECT * FROM nostrnip5.addresses WHERE domain_id = ?", (domain_id,) + "SELECT * FROM nostrnip5.addresses WHERE domain_id = ?", (domain_id,) ) return [Address.from_row(row) for row in rows] diff --git a/lnbits/extensions/nostrnip5/migrations.py b/lnbits/extensions/nostrnip5/migrations.py index 8e81a1a4e..7c5a49dd4 100644 --- a/lnbits/extensions/nostrnip5/migrations.py +++ b/lnbits/extensions/nostrnip5/migrations.py @@ -24,7 +24,7 @@ async def m001_initial_invoices(db): local_part TEXT NOT NULL, pubkey TEXT NOT NULL, - + active BOOLEAN NOT NULL DEFAULT false, time TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}, diff --git a/lnbits/extensions/nostrnip5/models.py b/lnbits/extensions/nostrnip5/models.py index 5abbf1281..7e7bf2546 100644 --- a/lnbits/extensions/nostrnip5/models.py +++ b/lnbits/extensions/nostrnip5/models.py @@ -1,6 +1,4 @@ -from enum import Enum from sqlite3 import Row -from typing import List, Optional from fastapi.param_functions import Query from pydantic import BaseModel diff --git a/lnbits/extensions/nostrnip5/views.py b/lnbits/extensions/nostrnip5/views.py index fc897d5da..40f498c1d 100644 --- a/lnbits/extensions/nostrnip5/views.py +++ b/lnbits/extensions/nostrnip5/views.py @@ -1,4 +1,3 @@ -from datetime import datetime from http import HTTPStatus from fastapi import Depends, Request diff --git a/lnbits/extensions/nostrnip5/views_api.py b/lnbits/extensions/nostrnip5/views_api.py index 99a0fe011..aa5dc887b 100644 --- a/lnbits/extensions/nostrnip5/views_api.py +++ b/lnbits/extensions/nostrnip5/views_api.py @@ -270,7 +270,7 @@ async def api_get_nostr_json( if not local_part: continue - if address.get("active") == False: + if address.get("active") is False: continue if name and name.lower() != local_part.lower(): diff --git a/lnbits/extensions/offlineshop/__init__.py b/lnbits/extensions/offlineshop/__init__.py index 0b776a8ce..72d1ae6b3 100644 --- a/lnbits/extensions/offlineshop/__init__.py +++ b/lnbits/extensions/offlineshop/__init__.py @@ -21,6 +21,6 @@ def offlineshop_renderer(): return template_renderer(["lnbits/extensions/offlineshop/templates"]) -from .lnurl import * # noqa -from .views import * # noqa -from .views_api import * # noqa +from .lnurl import * # noqa: F401,F403 +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/offlineshop/views.py b/lnbits/extensions/offlineshop/views.py index 3c2aaf5a9..ebde17629 100644 --- a/lnbits/extensions/offlineshop/views.py +++ b/lnbits/extensions/offlineshop/views.py @@ -1,19 +1,17 @@ import time from datetime import datetime from http import HTTPStatus -from typing import List from fastapi import Depends, HTTPException, Query, Request from starlette.responses import HTMLResponse from lnbits.core.crud import get_standalone_payment -from lnbits.core.models import Payment, User +from lnbits.core.models import User from lnbits.core.views.api import api_payment from lnbits.decorators import check_user_exists from . import offlineshop_ext, offlineshop_renderer from .crud import get_item, get_shop -from .models import Item @offlineshop_ext.get("/", response_class=HTMLResponse) diff --git a/lnbits/extensions/offlineshop/views_api.py b/lnbits/extensions/offlineshop/views_api.py index 1b8abb495..22dca69b1 100644 --- a/lnbits/extensions/offlineshop/views_api.py +++ b/lnbits/extensions/offlineshop/views_api.py @@ -78,7 +78,7 @@ async def api_add_or_update_item( ) if data.unit != "sat": data.price = data.price * 100 - if item_id == None: + if item_id is None: await add_item( shop.id, diff --git a/lnbits/extensions/paywall/__init__.py b/lnbits/extensions/paywall/__init__.py index d7adcdeda..5565a9349 100644 --- a/lnbits/extensions/paywall/__init__.py +++ b/lnbits/extensions/paywall/__init__.py @@ -21,5 +21,5 @@ def paywall_renderer(): return template_renderer(["lnbits/extensions/paywall/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/satsdice/__init__.py b/lnbits/extensions/satsdice/__init__.py index aaa56af2a..a13653bf3 100644 --- a/lnbits/extensions/satsdice/__init__.py +++ b/lnbits/extensions/satsdice/__init__.py @@ -21,6 +21,6 @@ def satsdice_renderer(): return template_renderer(["lnbits/extensions/satsdice/templates"]) -from .lnurl import * # noqa -from .views import * # noqa -from .views_api import * # noqa +from .lnurl import * # noqa: F401,F403 +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/satsdice/models.py b/lnbits/extensions/satsdice/models.py index b0a9a4cda..510b7bde0 100644 --- a/lnbits/extensions/satsdice/models.py +++ b/lnbits/extensions/satsdice/models.py @@ -8,7 +8,6 @@ from lnurl import Lnurl from lnurl import encode as lnurl_encode from lnurl.types import LnurlPayMetadata from pydantic import BaseModel -from pydantic.main import BaseModel class satsdiceLink(BaseModel): diff --git a/lnbits/extensions/satspay/__init__.py b/lnbits/extensions/satspay/__init__.py index 37245c21d..8f115a3cf 100644 --- a/lnbits/extensions/satspay/__init__.py +++ b/lnbits/extensions/satspay/__init__.py @@ -26,8 +26,8 @@ def satspay_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def satspay_start(): diff --git a/lnbits/extensions/satspay/helpers.py b/lnbits/extensions/satspay/helpers.py index 8596d3684..1967c79d9 100644 --- a/lnbits/extensions/satspay/helpers.py +++ b/lnbits/extensions/satspay/helpers.py @@ -18,7 +18,6 @@ def public_charge(charge: Charges): "timestamp": charge.timestamp, "time_elapsed": charge.time_elapsed, "time_left": charge.time_left, - "paid": charge.paid, "custom_css": charge.custom_css, } diff --git a/lnbits/extensions/satspay/migrations.py b/lnbits/extensions/satspay/migrations.py index e23bd413b..488754699 100644 --- a/lnbits/extensions/satspay/migrations.py +++ b/lnbits/extensions/satspay/migrations.py @@ -33,7 +33,7 @@ async def m002_add_charge_extra_data(db): Add 'extra' column for storing various config about the charge (JSON format) """ await db.execute( - """ALTER TABLE satspay.charges + """ALTER TABLE satspay.charges ADD COLUMN extra TEXT DEFAULT '{"mempool_endpoint": "https://mempool.space", "network": "Mainnet"}'; """ ) diff --git a/lnbits/extensions/satspay/models.py b/lnbits/extensions/satspay/models.py index 0b2b14739..c9da401a2 100644 --- a/lnbits/extensions/satspay/models.py +++ b/lnbits/extensions/satspay/models.py @@ -77,7 +77,7 @@ class Charges(BaseModel): return ChargeConfig(**charge_config) def must_call_webhook(self): - return self.webhook and self.paid and self.config.webhook_success == False + return self.webhook and self.paid and self.config.webhook_success is False class SatsPayThemes(BaseModel): diff --git a/lnbits/extensions/scrub/__init__.py b/lnbits/extensions/scrub/__init__.py index 777a7c3f9..29428af96 100644 --- a/lnbits/extensions/scrub/__init__.py +++ b/lnbits/extensions/scrub/__init__.py @@ -25,8 +25,8 @@ def scrub_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def scrub_start(): diff --git a/lnbits/extensions/scrub/migrations.py b/lnbits/extensions/scrub/migrations.py index f8f2ba43c..f1f4badef 100644 --- a/lnbits/extensions/scrub/migrations.py +++ b/lnbits/extensions/scrub/migrations.py @@ -3,7 +3,7 @@ async def m001_initial(db): Initial scrub table. """ await db.execute( - f""" + """ CREATE TABLE scrub.scrub_links ( id TEXT PRIMARY KEY, wallet TEXT NOT NULL, diff --git a/lnbits/extensions/smtp/__init__.py b/lnbits/extensions/smtp/__init__.py index e7419852a..9b89a0c46 100644 --- a/lnbits/extensions/smtp/__init__.py +++ b/lnbits/extensions/smtp/__init__.py @@ -25,8 +25,8 @@ def smtp_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def smtp_start(): diff --git a/lnbits/extensions/smtp/crud.py b/lnbits/extensions/smtp/crud.py index c7b96df59..bc8d9e1a4 100644 --- a/lnbits/extensions/smtp/crud.py +++ b/lnbits/extensions/smtp/crud.py @@ -121,9 +121,9 @@ async def create_email(wallet: str, data: CreateEmail, payment_hash: str = "") - async def set_email_paid(payment_hash: str) -> bool: email = await get_email_by_payment_hash(payment_hash) - if email and email.paid == False: + if email and email.paid is False: await db.execute( - f"UPDATE smtp.email SET paid = true WHERE payment_hash = ?", (payment_hash,) + "UPDATE smtp.email SET paid = true WHERE payment_hash = ?", (payment_hash,) ) return True return False @@ -131,13 +131,13 @@ async def set_email_paid(payment_hash: str) -> bool: async def get_email_by_payment_hash(payment_hash: str) -> Optional[Email]: row = await db.fetchone( - f"SELECT * FROM smtp.email WHERE payment_hash = ?", (payment_hash,) + "SELECT * FROM smtp.email WHERE payment_hash = ?", (payment_hash,) ) return Email(**row) if row else None async def get_email(id: str) -> Optional[Email]: - row = await db.fetchone(f"SELECT * FROM smtp.email WHERE id = ?", (id,)) + row = await db.fetchone("SELECT * FROM smtp.email WHERE id = ?", (id,)) return Email(**row) if row else None diff --git a/lnbits/extensions/smtp/migrations.py b/lnbits/extensions/smtp/migrations.py index fbe77d73f..22500e106 100644 --- a/lnbits/extensions/smtp/migrations.py +++ b/lnbits/extensions/smtp/migrations.py @@ -36,4 +36,4 @@ async def m001_initial(db): async def m002_add_payment_hash(db): - await db.execute(f"ALTER TABLE smtp.email ADD COLUMN payment_hash TEXT;") + await db.execute("ALTER TABLE smtp.email ADD COLUMN payment_hash TEXT;") diff --git a/lnbits/extensions/splitpayments/__init__.py b/lnbits/extensions/splitpayments/__init__.py index 9989728ea..5efb6335f 100644 --- a/lnbits/extensions/splitpayments/__init__.py +++ b/lnbits/extensions/splitpayments/__init__.py @@ -26,8 +26,8 @@ def splitpayments_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def splitpayments_start(): diff --git a/lnbits/extensions/streamalerts/__init__.py b/lnbits/extensions/streamalerts/__init__.py index 0e4311240..603547d1c 100644 --- a/lnbits/extensions/streamalerts/__init__.py +++ b/lnbits/extensions/streamalerts/__init__.py @@ -21,5 +21,5 @@ def streamalerts_renderer(): return template_renderer(["lnbits/extensions/streamalerts/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/streamalerts/crud.py b/lnbits/extensions/streamalerts/crud.py index 941134473..f376841a4 100644 --- a/lnbits/extensions/streamalerts/crud.py +++ b/lnbits/extensions/streamalerts/crud.py @@ -1,4 +1,3 @@ -from http import HTTPStatus from typing import Optional import httpx diff --git a/lnbits/extensions/subdomains/__init__.py b/lnbits/extensions/subdomains/__init__.py index 0b0774dc5..7434555d9 100644 --- a/lnbits/extensions/subdomains/__init__.py +++ b/lnbits/extensions/subdomains/__init__.py @@ -25,8 +25,8 @@ def subdomains_renderer(): from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 def subdomains_start(): diff --git a/lnbits/extensions/subdomains/cloudflare.py b/lnbits/extensions/subdomains/cloudflare.py index 5b951b21a..d0d8c4f31 100644 --- a/lnbits/extensions/subdomains/cloudflare.py +++ b/lnbits/extensions/subdomains/cloudflare.py @@ -54,6 +54,6 @@ async def cloudflare_deletesubdomain(domain: Domains, domain_id: str): async with httpx.AsyncClient() as client: try: r = await client.delete(url + "/" + domain_id, headers=header, timeout=40) - cf_response = r.text + r.text except AssertionError: - cf_response = "Error occured" + pass diff --git a/lnbits/extensions/subdomains/crud.py b/lnbits/extensions/subdomains/crud.py index aa358d11c..b3476ed93 100644 --- a/lnbits/extensions/subdomains/crud.py +++ b/lnbits/extensions/subdomains/crud.py @@ -36,7 +36,7 @@ async def set_subdomain_paid(payment_hash: str) -> Subdomains: "SELECT s.*, d.domain as domain_name FROM subdomains.subdomain s INNER JOIN subdomains.domain d ON (s.domain = d.id) WHERE s.id = ?", (payment_hash,), ) - if row[8] == False: + if row[8] is False: await db.execute( """ UPDATE subdomains.subdomain diff --git a/lnbits/extensions/subdomains/tasks.py b/lnbits/extensions/subdomains/tasks.py index ca57950b3..aef4b49b1 100644 --- a/lnbits/extensions/subdomains/tasks.py +++ b/lnbits/extensions/subdomains/tasks.py @@ -54,5 +54,6 @@ async def on_invoice_paid(payment: Payment) -> None: }, timeout=40, ) + assert r except AssertionError: - webhook = None + pass diff --git a/lnbits/extensions/subdomains/util.py b/lnbits/extensions/subdomains/util.py index 88f6e1341..9265e870a 100644 --- a/lnbits/extensions/subdomains/util.py +++ b/lnbits/extensions/subdomains/util.py @@ -12,7 +12,7 @@ def isValidDomain(str): # If the string is empty # return false - if str == None: + if str is None: return False # Return if the string diff --git a/lnbits/extensions/subdomains/views_api.py b/lnbits/extensions/subdomains/views_api.py index 9fbae4f3a..6f85c66e0 100644 --- a/lnbits/extensions/subdomains/views_api.py +++ b/lnbits/extensions/subdomains/views_api.py @@ -128,7 +128,7 @@ async def api_subdomain_make_subdomain(domain_id, data: CreateSubdomain): record_type=data.record_type, ip=data.ip, ) - if cf_response["success"] == True: + if cf_response["success"] is True: await cloudflare_deletesubdomain( domain=domain, domain_id=cf_response["result"]["id"] ) diff --git a/lnbits/extensions/tipjar/__init__.py b/lnbits/extensions/tipjar/__init__.py index a64de43f2..b7e2b9678 100644 --- a/lnbits/extensions/tipjar/__init__.py +++ b/lnbits/extensions/tipjar/__init__.py @@ -21,5 +21,5 @@ def tipjar_renderer(): return template_renderer(["lnbits/extensions/tipjar/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/watchonly/__init__.py b/lnbits/extensions/watchonly/__init__.py index a7fff888a..49adb4623 100644 --- a/lnbits/extensions/watchonly/__init__.py +++ b/lnbits/extensions/watchonly/__init__.py @@ -21,5 +21,5 @@ def watchonly_renderer(): return template_renderer(["lnbits/extensions/watchonly/templates"]) -from .views import * # noqa -from .views_api import * # noqa +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/extensions/watchonly/crud.py b/lnbits/extensions/watchonly/crud.py index 1d9abcec4..8472fa016 100644 --- a/lnbits/extensions/watchonly/crud.py +++ b/lnbits/extensions/watchonly/crud.py @@ -230,7 +230,7 @@ async def create_config(user: str) -> Config: async def update_config(config: Config, user: str) -> Optional[Config]: await db.execute( - f"""UPDATE watchonly.config SET json_data = ? WHERE "user" = ?""", + """UPDATE watchonly.config SET json_data = ? WHERE "user" = ?""", (json.dumps(config.dict()), user), ) row = await db.fetchone( diff --git a/lnbits/extensions/watchonly/migrations.py b/lnbits/extensions/watchonly/migrations.py index e33062c9f..bbef40a8c 100644 --- a/lnbits/extensions/watchonly/migrations.py +++ b/lnbits/extensions/watchonly/migrations.py @@ -30,7 +30,7 @@ async def m001_initial(db): """ CREATE TABLE watchonly.mempool ( "user" TEXT NOT NULL, - endpoint TEXT NOT NULL + endpoint TEXT NOT NULL ); """ ) diff --git a/lnbits/extensions/withdraw/__init__.py b/lnbits/extensions/withdraw/__init__.py index a0f4b6068..cb5eb9c43 100644 --- a/lnbits/extensions/withdraw/__init__.py +++ b/lnbits/extensions/withdraw/__init__.py @@ -22,6 +22,6 @@ def withdraw_renderer(): return template_renderer(["lnbits/extensions/withdraw/templates"]) -from .lnurl import * # noqa -from .views import * # noqa -from .views_api import * # noqa +from .lnurl import * # noqa: F401,F403 +from .views import * # noqa: F401,F403 +from .views_api import * # noqa: F401,F403 diff --git a/lnbits/helpers.py b/lnbits/helpers.py index 31f736d9b..cfff7bba8 100644 --- a/lnbits/helpers.py +++ b/lnbits/helpers.py @@ -83,19 +83,18 @@ def url_for_vendored(abspath: str) -> str: def url_for(endpoint: str, external: Optional[bool] = False, **params: Any) -> str: base = g().base_url if external else "" url_params = "?" - for key in params: - url_params += f"{key}={params[key]}&" + for key, value in params.items(): + url_params += f"{key}={value}&" url = f"{base}{endpoint}{url_params}" return url -def template_renderer(additional_folders: List = []) -> Jinja2Templates: +def template_renderer(additional_folders: List = None) -> Jinja2Templates: - t = Jinja2Templates( - loader=jinja2.FileSystemLoader( - ["lnbits/templates", "lnbits/core/templates", *additional_folders] - ) - ) + folders = ["lnbits/templates", "lnbits/core/templates"] + if additional_folders: + folders.extend(additional_folders) + t = Jinja2Templates(loader=jinja2.FileSystemLoader(folders)) if settings.lnbits_ad_space_enabled: t.env.globals["AD_SPACE"] = settings.lnbits_ad_space.split(",") @@ -135,7 +134,7 @@ def get_current_extension_name() -> str: import os callee_filepath = inspect.stack()[1].filename - callee_dirname, callee_filename = os.path.split(callee_filepath) + callee_dirname, _ = os.path.split(callee_filepath) path = os.path.normpath(callee_dirname) extension_director_name = path.split(os.sep)[-1] diff --git a/lnbits/jinja2_templating.py b/lnbits/jinja2_templating.py index 385703d19..5dfe36c36 100644 --- a/lnbits/jinja2_templating.py +++ b/lnbits/jinja2_templating.py @@ -7,8 +7,6 @@ from starlette import templating from starlette.datastructures import QueryParams from starlette.requests import Request -from lnbits.requestvars import g - try: import jinja2 except ImportError: # pragma: nocover @@ -16,7 +14,7 @@ except ImportError: # pragma: nocover class Jinja2Templates(templating.Jinja2Templates): - def __init__(self, loader: jinja2.BaseLoader) -> None: + def __init__(self, loader: jinja2.BaseLoader) -> None: # pylint: disable=W0231 assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates" self.env = self.get_environment(loader) diff --git a/lnbits/lnurl.py b/lnbits/lnurl.py index 6039545b0..8f5be4ef8 100644 --- a/lnbits/lnurl.py +++ b/lnbits/lnurl.py @@ -3,6 +3,7 @@ from bech32 import bech32_decode, bech32_encode, convertbits def decode(lnurl: str) -> str: hrp, data = bech32_decode(lnurl) + assert hrp assert data bech32_data = convertbits(data, 5, 8, False) assert bech32_data diff --git a/lnbits/settings.py b/lnbits/settings.py index bc317e05a..3bec3f72a 100644 --- a/lnbits/settings.py +++ b/lnbits/settings.py @@ -366,7 +366,7 @@ except: # printing enviroment variable for debugging if not settings.lnbits_admin_ui: - logger.debug(f"Enviroment Settings:") + logger.debug("Enviroment Settings:") for key, value in settings.dict(exclude_none=True).items(): logger.debug(f"{key}: {value}") diff --git a/lnbits/tasks.py b/lnbits/tasks.py index 00d367255..f4d3bf7be 100644 --- a/lnbits/tasks.py +++ b/lnbits/tasks.py @@ -3,7 +3,7 @@ import time import traceback import uuid from http import HTTPStatus -from typing import Callable, Dict, List +from typing import Dict from fastapi.exceptions import HTTPException from loguru import logger diff --git a/lnbits/wallets/__init__.py b/lnbits/wallets/__init__.py index fa533566f..76c47c048 100644 --- a/lnbits/wallets/__init__.py +++ b/lnbits/wallets/__init__.py @@ -1,4 +1,4 @@ -# flake8: noqa +# flake8: noqa: F401 from .cliche import ClicheWallet diff --git a/lnbits/wallets/base.py b/lnbits/wallets/base.py index e38b6d8fc..68e49c9d0 100644 --- a/lnbits/wallets/base.py +++ b/lnbits/wallets/base.py @@ -34,14 +34,14 @@ class PaymentStatus(NamedTuple): @property def failed(self) -> bool: - return self.paid == False + return self.paid is False def __str__(self) -> str: - if self.paid == True: + if self.paid is True: return "settled" - elif self.paid == False: + elif self.paid is False: return "failed" - elif self.paid == None: + elif self.paid is None: return "still pending" else: return "unknown (should never happen)" diff --git a/lnbits/wallets/cliche.py b/lnbits/wallets/cliche.py index c580dce71..211ba4f3d 100644 --- a/lnbits/wallets/cliche.py +++ b/lnbits/wallets/cliche.py @@ -1,9 +1,8 @@ import asyncio import hashlib import json -from typing import AsyncGenerator, Dict, Optional +from typing import AsyncGenerator, Optional -import httpx from loguru import logger from websocket import create_connection diff --git a/lnbits/wallets/cln.py b/lnbits/wallets/cln.py index a77cbf0a9..642aef508 100644 --- a/lnbits/wallets/cln.py +++ b/lnbits/wallets/cln.py @@ -4,9 +4,7 @@ except ImportError: # pragma: nocover LightningRpc = None import asyncio -import hashlib import random -import time from functools import partial, wraps from typing import AsyncGenerator, Optional @@ -85,7 +83,7 @@ class CoreLightningWallet(Wallet): unhashed_description: Optional[bytes] = None, **kwargs, ) -> InvoiceResponse: - label = "lbl{}".format(random.random()) + label = f"lbl{random.random()}" msat: int = int(amount * 1000) try: if description_hash and not unhashed_description: @@ -128,7 +126,7 @@ class CoreLightningWallet(Wallet): payload = { "bolt11": bolt11, - "maxfeepercent": "{:.11}".format(fee_limit_percent), + "maxfeepercent": f"{fee_limit_percent:.11}", "exemptfee": 0, # so fee_limit_percent is applied even on payments with fee < 5000 millisatoshi (which is default value of exemptfee) } try: diff --git a/lnbits/wallets/eclair.py b/lnbits/wallets/eclair.py index 0eb43ca0d..a45123b1b 100644 --- a/lnbits/wallets/eclair.py +++ b/lnbits/wallets/eclair.py @@ -11,11 +11,6 @@ from loguru import logger # TODO: https://github.com/lnbits/lnbits/issues/764 # mypy https://github.com/aaugustin/websockets/issues/940 from websockets import connect # type: ignore -from websockets.exceptions import ( - ConnectionClosed, - ConnectionClosedError, - ConnectionClosedOK, -) from lnbits.settings import settings @@ -98,7 +93,6 @@ class EclairWallet(Wallet): error_message = data["error"] except: error_message = r.text - pass return InvoiceResponse(False, None, None, error_message) @@ -120,7 +114,6 @@ class EclairWallet(Wallet): error_message = data["error"] except: error_message = r.text - pass return PaymentResponse(False, None, None, None, error_message) data = r.json() @@ -147,7 +140,6 @@ class EclairWallet(Wallet): error_message = data["error"] except: error_message = r.text - pass return PaymentResponse(None, checking_id, None, preimage, error_message) statuses = { diff --git a/lnbits/wallets/lnbits.py b/lnbits/wallets/lnbits.py index 27747ce95..74c9efcc5 100644 --- a/lnbits/wallets/lnbits.py +++ b/lnbits/wallets/lnbits.py @@ -1,5 +1,4 @@ import asyncio -import hashlib import json from typing import AsyncGenerator, Dict, Optional @@ -98,7 +97,7 @@ class LNbitsWallet(Wallet): json={"out": True, "bolt11": bolt11}, timeout=None, ) - ok, checking_id, fee_msat, preimage, error_message = ( + ok, checking_id, _, _, error_message = ( not r.is_error, None, None, diff --git a/lnbits/wallets/lndgrpc.py b/lnbits/wallets/lndgrpc.py index 541c6ab7a..4173e79ee 100644 --- a/lnbits/wallets/lndgrpc.py +++ b/lnbits/wallets/lndgrpc.py @@ -1,7 +1,6 @@ imports_ok = True try: import grpc - from google import protobuf from grpc import RpcError except ImportError: # pragma: nocover imports_ok = False @@ -9,7 +8,7 @@ except ImportError: # pragma: nocover import asyncio import base64 import hashlib -from os import environ, error +from os import environ from typing import AsyncGenerator, Dict, Optional from loguru import logger @@ -216,11 +215,11 @@ class LndWallet(Wallet): error_message = None checking_id = None - if statuses[resp.status] == True: # SUCCEEDED + if statuses[resp.status] is True: # SUCCEEDED fee_msat = -resp.htlcs[-1].route.total_fees_msat preimage = resp.payment_preimage checking_id = resp.payment_hash - elif statuses[resp.status] == False: + elif statuses[resp.status] is False: error_message = failure_reasons[resp.failure_reason] return PaymentResponse( @@ -238,7 +237,7 @@ class LndWallet(Wallet): return PaymentStatus(None) try: resp = await self.rpc.LookupInvoice(ln.PaymentHash(r_hash=r_hash)) - except RpcError as exc: + except RpcError: return PaymentStatus(None) if resp.settled: return PaymentStatus(True) diff --git a/lnbits/wallets/lndrest.py b/lnbits/wallets/lndrest.py index d317df3c3..6e5962267 100644 --- a/lnbits/wallets/lndrest.py +++ b/lnbits/wallets/lndrest.py @@ -2,13 +2,11 @@ import asyncio import base64 import hashlib import json -from pydoc import describe from typing import AsyncGenerator, Dict, Optional import httpx from loguru import logger -from lnbits import bolt11 as lnbits_bolt11 from lnbits.settings import settings from .base import ( @@ -114,7 +112,7 @@ class LndRestWallet(Wallet): async with httpx.AsyncClient(verify=self.cert) as client: # set the fee limit for the payment lnrpcFeeLimit = dict() - lnrpcFeeLimit["fixed_msat"] = "{}".format(fee_limit_msat) + lnrpcFeeLimit["fixed_msat"] = f"{fee_limit_msat}" r = await client.post( url=f"{self.endpoint}/v1/channels/transactions", diff --git a/lnbits/wallets/lntips.py b/lnbits/wallets/lntips.py index 92b33b7a5..4551a207b 100644 --- a/lnbits/wallets/lntips.py +++ b/lnbits/wallets/lntips.py @@ -77,7 +77,6 @@ class LnTipsWallet(Wallet): error_message = data["message"] except: error_message = r.text - pass return InvoiceResponse(False, None, None, error_message) @@ -103,7 +102,6 @@ class LnTipsWallet(Wallet): error_message = data["error"] except: error_message = r.text - pass return PaymentResponse(False, None, 0, None, error_message) data = r.json()["details"] @@ -165,7 +163,7 @@ class LnTipsWallet(Wallet): except: continue yield inv["payment_hash"] - except Exception as e: + except Exception: pass # do not sleep if the connection was active for more than 10s diff --git a/lnbits/wallets/lntxbot.py b/lnbits/wallets/lntxbot.py index ce315e75d..a1e41bd22 100644 --- a/lnbits/wallets/lntxbot.py +++ b/lnbits/wallets/lntxbot.py @@ -75,7 +75,6 @@ class LntxbotWallet(Wallet): error_message = data["message"] except: error_message = r.text - pass return InvoiceResponse(False, None, None, error_message) @@ -97,7 +96,6 @@ class LntxbotWallet(Wallet): error_message = data["message"] except: error_message = r.text - pass return PaymentResponse(False, None, None, None, error_message) data = r.json() diff --git a/lnbits/wallets/macaroon/__init__.py b/lnbits/wallets/macaroon/__init__.py index 16617aa65..7512e07f2 100644 --- a/lnbits/wallets/macaroon/__init__.py +++ b/lnbits/wallets/macaroon/__init__.py @@ -1 +1 @@ -from .macaroon import AESCipher, load_macaroon +from .macaroon import AESCipher, load_macaroon # noqa: F401 diff --git a/lnbits/wallets/macaroon/macaroon.py b/lnbits/wallets/macaroon/macaroon.py index 091551238..05d667be8 100644 --- a/lnbits/wallets/macaroon/macaroon.py +++ b/lnbits/wallets/macaroon/macaroon.py @@ -7,7 +7,6 @@ from Cryptodome.Cipher import AES from loguru import logger BLOCK_SIZE = 16 -import getpass def load_macaroon(macaroon: str) -> str: @@ -33,7 +32,7 @@ def load_macaroon(macaroon: str) -> str: return macaroon -class AESCipher(object): +class AESCipher: """This class is compatible with crypto-js/aes.js Encrypt and decrypt in Javascript using: diff --git a/lnbits/wallets/opennode.py b/lnbits/wallets/opennode.py index ff71ef079..89c7f1d58 100644 --- a/lnbits/wallets/opennode.py +++ b/lnbits/wallets/opennode.py @@ -7,7 +7,6 @@ import httpx from fastapi.exceptions import HTTPException from loguru import logger -from lnbits.helpers import url_for from lnbits.settings import settings from .base import ( diff --git a/lnbits/wallets/spark.py b/lnbits/wallets/spark.py index 25ff16685..edfa01d02 100644 --- a/lnbits/wallets/spark.py +++ b/lnbits/wallets/spark.py @@ -97,7 +97,7 @@ class SparkWallet(Wallet): unhashed_description: Optional[bytes] = None, **kwargs, ) -> InvoiceResponse: - label = "lbs{}".format(random.random()) + label = f"lbs{random.random()}" checking_id = label try: @@ -161,7 +161,6 @@ class SparkWallet(Wallet): # this may result in an error if it was paid previously # our database won't allow the same payment_hash to be added twice # this is good - pass fee_msat = -int(r["msatoshi_sent"] - r["msatoshi"]) preimage = r["payment_preimage"] diff --git a/poetry.lock b/poetry.lock index 866415154..956186134 100644 --- a/poetry.lock +++ b/poetry.lock @@ -64,6 +64,27 @@ files = [ {file = "asn1crypto-1.5.1.tar.gz", hash = "sha256:13ae38502be632115abf8a24cbe5f4da52e3b5231990aff31123c805306ccb9c"}, ] +[[package]] +name = "astroid" +version = "2.13.3" +description = "An abstract syntax tree for Python with inference support." +category = "dev" +optional = false +python-versions = ">=3.7.2" +files = [ + {file = "astroid-2.13.3-py3-none-any.whl", hash = "sha256:14c1603c41cc61aae731cad1884a073c4645e26f126d13ac8346113c95577f3b"}, + {file = "astroid-2.13.3.tar.gz", hash = "sha256:6afc22718a48a689ca24a97981ad377ba7fb78c133f40335dfd16772f29bcfb1"}, +] + +[package.dependencies] +lazy-object-proxy = ">=1.4.0" +typed-ast = {version = ">=1.4.0,<2.0", markers = "implementation_name == \"cpython\" and python_version < \"3.8\""} +typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.11\""} +wrapt = [ + {version = ">=1.11,<2", markers = "python_version < \"3.11\""}, + {version = ">=1.14,<2", markers = "python_version >= \"3.11\""}, +] + [[package]] name = "async-timeout" version = "4.0.2" @@ -550,13 +571,28 @@ files = [ cffi = ">=1.12" [package.extras] -docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx_rtd_theme"] +docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"] docstest = ["pyenchant (>=1.6.11)", "sphinxcontrib-spelling (>=4.0.1)", "twine (>=1.12.0)"] pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"] -sdist = ["setuptools_rust (>=0.11.4)"] +sdist = ["setuptools-rust (>=0.11.4)"] ssh = ["bcrypt (>=3.1.5)"] test = ["hypothesis (>=1.11.4,!=3.79.2)", "iso8601", "pretend", "pytest (>=6.2.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pytz"] +[[package]] +name = "dill" +version = "0.3.6" +description = "serialize all of python" +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "dill-0.3.6-py3-none-any.whl", hash = "sha256:a07ffd2351b8c678dfc4a856a3005f8067aea51d6ba6c700796a4d9e280f39f0"}, + {file = "dill-0.3.6.tar.gz", hash = "sha256:e5db55f3687856d8fbdab002ed78544e1c4559a130302693d839dfe8f93f2373"}, +] + +[package.extras] +graph = ["objgraph (>=1.7.2)"] + [[package]] name = "ecdsa" version = "0.18.0" @@ -659,6 +695,23 @@ dev = ["autoflake (>=1.4.0,<2.0.0)", "flake8 (>=3.8.3,<6.0.0)", "passlib[bcrypt] doc = ["mdx-include (>=1.4.1,<2.0.0)", "mkdocs (>=1.1.2,<2.0.0)", "mkdocs-markdownextradata-plugin (>=0.1.7,<0.3.0)", "mkdocs-material (>=8.1.4,<9.0.0)", "pyyaml (>=5.3.1,<7.0.0)", "typer (>=0.4.1,<0.5.0)"] test = ["anyio[trio] (>=3.2.1,<4.0.0)", "black (==22.3.0)", "databases[sqlite] (>=0.3.2,<0.6.0)", "email_validator (>=1.1.1,<2.0.0)", "flake8 (>=3.8.3,<6.0.0)", "flask (>=1.1.2,<3.0.0)", "httpx (>=0.14.0,<0.19.0)", "isort (>=5.0.6,<6.0.0)", "mypy (==0.910)", "orjson (>=3.2.1,<4.0.0)", "peewee (>=3.13.3,<4.0.0)", "pytest (>=6.2.4,<7.0.0)", "pytest-cov (>=2.12.0,<4.0.0)", "python-multipart (>=0.0.5,<0.0.6)", "requests (>=2.24.0,<3.0.0)", "sqlalchemy (>=1.3.18,<1.5.0)", "types-dataclasses (==0.6.5)", "types-orjson (==3.6.2)", "types-ujson (==4.2.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0)"] +[[package]] +name = "flake8" +version = "6.0.0" +description = "the modular source code checker: pep8 pyflakes and co" +category = "dev" +optional = false +python-versions = ">=3.8.1" +files = [ + {file = "flake8-6.0.0-py2.py3-none-any.whl", hash = "sha256:3833794e27ff64ea4e9cf5d410082a8b97ff1a06c16aa3d2027339cd0f1195c7"}, + {file = "flake8-6.0.0.tar.gz", hash = "sha256:c61007e76655af75e6785a931f452915b371dc48f56efd765247c8fe68f2b181"}, +] + +[package.dependencies] +mccabe = ">=0.7.0,<0.8.0" +pycodestyle = ">=2.10.0,<2.11.0" +pyflakes = ">=3.0.0,<3.1.0" + [[package]] name = "grpcio" version = "1.51.1" @@ -869,19 +922,19 @@ files = [ [[package]] name = "isort" -version = "5.11.4" +version = "5.11.5" description = "A Python utility / library to sort Python imports." category = "dev" optional = false python-versions = ">=3.7.0" files = [ - {file = "isort-5.11.4-py3-none-any.whl", hash = "sha256:c033fd0edb91000a7f09527fe5c75321878f98322a77ddcc81adbd83724afb7b"}, - {file = "isort-5.11.4.tar.gz", hash = "sha256:6db30c5ded9815d813932c04c2f85a360bcdd35fed496f4d8f35495ef0a261b6"}, + {file = "isort-5.11.5-py3-none-any.whl", hash = "sha256:ba1d72fb2595a01c7895a5128f9585a5cc4b6d395f1c8d514989b9a7eb2a8746"}, + {file = "isort-5.11.5.tar.gz", hash = "sha256:6be1f76a507cb2ecf16c7cf14a37e41609ca082330be4e3436a18ef74add55db"}, ] [package.extras] colors = ["colorama (>=0.4.3,<0.5.0)"] -pipfile-deprecated-finder = ["pipreqs", "requirementslib"] +pipfile-deprecated-finder = ["pip-shims (>=0.5.2)", "pipreqs", "requirementslib"] plugins = ["setuptools"] requirements-deprecated-finder = ["pip-api", "pipreqs"] @@ -903,6 +956,52 @@ MarkupSafe = ">=2.0" [package.extras] i18n = ["Babel (>=2.7)"] +[[package]] +name = "lazy-object-proxy" +version = "1.9.0" +description = "A fast and thorough lazy object proxy." +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "lazy-object-proxy-1.9.0.tar.gz", hash = "sha256:659fb5809fa4629b8a1ac5106f669cfc7bef26fbb389dda53b3e010d1ac4ebae"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b40387277b0ed2d0602b8293b94d7257e17d1479e257b4de114ea11a8cb7f2d7"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e8c6cfb338b133fbdbc5cfaa10fe3c6aeea827db80c978dbd13bc9dd8526b7d4"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:721532711daa7db0d8b779b0bb0318fa87af1c10d7fe5e52ef30f8eff254d0cd"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:66a3de4a3ec06cd8af3f61b8e1ec67614fbb7c995d02fa224813cb7afefee701"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:1aa3de4088c89a1b69f8ec0dcc169aa725b0ff017899ac568fe44ddc1396df46"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-win32.whl", hash = "sha256:f0705c376533ed2a9e5e97aacdbfe04cecd71e0aa84c7c0595d02ef93b6e4455"}, + {file = "lazy_object_proxy-1.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:ea806fd4c37bf7e7ad82537b0757999264d5f70c45468447bb2b91afdbe73a6e"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:946d27deaff6cf8452ed0dba83ba38839a87f4f7a9732e8f9fd4107b21e6ff07"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79a31b086e7e68b24b99b23d57723ef7e2c6d81ed21007b6281ebcd1688acb0a"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f699ac1c768270c9e384e4cbd268d6e67aebcfae6cd623b4d7c3bfde5a35db59"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:bfb38f9ffb53b942f2b5954e0f610f1e721ccebe9cce9025a38c8ccf4a5183a4"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:189bbd5d41ae7a498397287c408617fe5c48633e7755287b21d741f7db2706a9"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-win32.whl", hash = "sha256:81fc4d08b062b535d95c9ea70dbe8a335c45c04029878e62d744bdced5141586"}, + {file = "lazy_object_proxy-1.9.0-cp311-cp311-win_amd64.whl", hash = "sha256:f2457189d8257dd41ae9b434ba33298aec198e30adf2dcdaaa3a28b9994f6adb"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d9e25ef10a39e8afe59a5c348a4dbf29b4868ab76269f81ce1674494e2565a6e"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cbf9b082426036e19c6924a9ce90c740a9861e2bdc27a4834fd0a910742ac1e8"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9f5fa4a61ce2438267163891961cfd5e32ec97a2c444e5b842d574251ade27d2"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:8fa02eaab317b1e9e03f69aab1f91e120e7899b392c4fc19807a8278a07a97e8"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:e7c21c95cae3c05c14aafffe2865bbd5e377cfc1348c4f7751d9dc9a48ca4bda"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-win32.whl", hash = "sha256:f12ad7126ae0c98d601a7ee504c1122bcef553d1d5e0c3bfa77b16b3968d2734"}, + {file = "lazy_object_proxy-1.9.0-cp37-cp37m-win_amd64.whl", hash = "sha256:edd20c5a55acb67c7ed471fa2b5fb66cb17f61430b7a6b9c3b4a1e40293b1671"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2d0daa332786cf3bb49e10dc6a17a52f6a8f9601b4cf5c295a4f85854d61de63"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cd077f3d04a58e83d04b20e334f678c2b0ff9879b9375ed107d5d07ff160171"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:660c94ea760b3ce47d1855a30984c78327500493d396eac4dfd8bd82041b22be"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:212774e4dfa851e74d393a2370871e174d7ff0ebc980907723bb67d25c8a7c30"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:f0117049dd1d5635bbff65444496c90e0baa48ea405125c088e93d9cf4525b11"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-win32.whl", hash = "sha256:0a891e4e41b54fd5b8313b96399f8b0e173bbbfc03c7631f01efbe29bb0bcf82"}, + {file = "lazy_object_proxy-1.9.0-cp38-cp38-win_amd64.whl", hash = "sha256:9990d8e71b9f6488e91ad25f322898c136b008d87bf852ff65391b004da5e17b"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9e7551208b2aded9c1447453ee366f1c4070602b3d932ace044715d89666899b"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f83ac4d83ef0ab017683d715ed356e30dd48a93746309c8f3517e1287523ef4"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7322c3d6f1766d4ef1e51a465f47955f1e8123caee67dd641e67d539a534d006"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:18b78ec83edbbeb69efdc0e9c1cb41a3b1b1ed11ddd8ded602464c3fc6020494"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:09763491ce220c0299688940f8dc2c5d05fd1f45af1e42e636b2e8b2303e4382"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-win32.whl", hash = "sha256:9090d8e53235aa280fc9239a86ae3ea8ac58eff66a705fa6aa2ec4968b95c821"}, + {file = "lazy_object_proxy-1.9.0-cp39-cp39-win_amd64.whl", hash = "sha256:db1c1722726f47e10e0b5fdbf15ac3b8adb58c091d12b3ab713965795036985f"}, +] + [[package]] name = "lnurl" version = "0.3.6" @@ -1039,6 +1138,18 @@ docs = ["alabaster (==0.7.12)", "autodocsumm (==0.2.9)", "sphinx (==5.3.0)", "sp lint = ["flake8 (==5.0.4)", "flake8-bugbear (==22.10.25)", "mypy (==0.990)", "pre-commit (>=2.4,<3.0)"] tests = ["pytest", "pytz", "simplejson"] +[[package]] +name = "mccabe" +version = "0.7.0" +description = "McCabe checker, plugin for flake8" +category = "dev" +optional = false +python-versions = ">=3.6" +files = [ + {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"}, + {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, +] + [[package]] name = "mock" version = "4.0.3" @@ -1274,6 +1385,18 @@ files = [ {file = "psycopg2_binary-2.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:b4d7679a08fea64573c969f6994a2631908bb2c0e69a7235648642f3d2e39a68"}, ] +[[package]] +name = "pycodestyle" +version = "2.10.0" +description = "Python style guide checker" +category = "dev" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pycodestyle-2.10.0-py2.py3-none-any.whl", hash = "sha256:8a4eaf0d0495c7395bdab3589ac2db602797d76207242c17d470186815706610"}, + {file = "pycodestyle-2.10.0.tar.gz", hash = "sha256:347187bdb476329d98f695c213d7295a846d1152ff4fe9bacb8a9590b8ee7053"}, +] + [[package]] name = "pycparser" version = "2.21" @@ -1375,6 +1498,48 @@ typing-extensions = ">=4.2.0" dotenv = ["python-dotenv (>=0.10.4)"] email = ["email-validator (>=1.0.3)"] +[[package]] +name = "pyflakes" +version = "3.0.1" +description = "passive checker of Python programs" +category = "dev" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pyflakes-3.0.1-py2.py3-none-any.whl", hash = "sha256:ec55bf7fe21fff7f1ad2f7da62363d749e2a470500eab1b555334b67aa1ef8cf"}, + {file = "pyflakes-3.0.1.tar.gz", hash = "sha256:ec8b276a6b60bd80defed25add7e439881c19e64850afd9b346283d4165fd0fd"}, +] + +[[package]] +name = "pylint" +version = "2.15.10" +description = "python code static checker" +category = "dev" +optional = false +python-versions = ">=3.7.2" +files = [ + {file = "pylint-2.15.10-py3-none-any.whl", hash = "sha256:9df0d07e8948a1c3ffa3b6e2d7e6e63d9fb457c5da5b961ed63106594780cc7e"}, + {file = "pylint-2.15.10.tar.gz", hash = "sha256:b3dc5ef7d33858f297ac0d06cc73862f01e4f2e74025ec3eff347ce0bc60baf5"}, +] + +[package.dependencies] +astroid = ">=2.12.13,<=2.14.0-dev0" +colorama = {version = ">=0.4.5", markers = "sys_platform == \"win32\""} +dill = [ + {version = ">=0.2", markers = "python_version < \"3.11\""}, + {version = ">=0.3.6", markers = "python_version >= \"3.11\""}, +] +isort = ">=4.2.5,<6" +mccabe = ">=0.6,<0.8" +platformdirs = ">=2.2.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +tomlkit = ">=0.10.1" +typing-extensions = {version = ">=3.10.0", markers = "python_version < \"3.10\""} + +[package.extras] +spelling = ["pyenchant (>=3.2,<4.0)"] +testutils = ["gitpython (>3)"] + [[package]] name = "pyln-bolt7" version = "1.0.246" @@ -1802,7 +1967,7 @@ mssql = ["pyodbc"] mssql-pymssql = ["pymssql"] mssql-pyodbc = ["pyodbc"] mysql = ["mysqlclient"] -oracle = ["cx_oracle"] +oracle = ["cx-oracle"] postgresql = ["psycopg2"] postgresql-pg8000 = ["pg8000 (<1.16.6)"] postgresql-psycopg2binary = ["psycopg2-binary"] @@ -1873,6 +2038,18 @@ files = [ {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, ] +[[package]] +name = "tomlkit" +version = "0.11.6" +description = "Style preserving TOML library" +category = "dev" +optional = false +python-versions = ">=3.6" +files = [ + {file = "tomlkit-0.11.6-py3-none-any.whl", hash = "sha256:07de26b0d8cfc18f871aec595fda24d95b08fef89d147caa861939f37230bf4b"}, + {file = "tomlkit-0.11.6.tar.gz", hash = "sha256:71b952e5721688937fb02cf9d354dbcf0785066149d2855e44531ebdd2b65d73"}, +] + [[package]] name = "typed-ast" version = "1.5.4" @@ -2093,6 +2270,80 @@ files = [ [package.extras] dev = ["black (>=19.3b0)", "pytest (>=4.6.2)"] +[[package]] +name = "wrapt" +version = "1.14.1" +description = "Module for decorators, wrappers and monkey patching." +category = "dev" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" +files = [ + {file = "wrapt-1.14.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:1b376b3f4896e7930f1f772ac4b064ac12598d1c38d04907e696cc4d794b43d3"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:903500616422a40a98a5a3c4ff4ed9d0066f3b4c951fa286018ecdf0750194ef"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:5a9a0d155deafd9448baff28c08e150d9b24ff010e899311ddd63c45c2445e28"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:ddaea91abf8b0d13443f6dac52e89051a5063c7d014710dcb4d4abb2ff811a59"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:36f582d0c6bc99d5f39cd3ac2a9062e57f3cf606ade29a0a0d6b323462f4dd87"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:7ef58fb89674095bfc57c4069e95d7a31cfdc0939e2a579882ac7d55aadfd2a1"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:e2f83e18fe2f4c9e7db597e988f72712c0c3676d337d8b101f6758107c42425b"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:ee2b1b1769f6707a8a445162ea16dddf74285c3964f605877a20e38545c3c462"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:833b58d5d0b7e5b9832869f039203389ac7cbf01765639c7309fd50ef619e0b1"}, + {file = "wrapt-1.14.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:80bb5c256f1415f747011dc3604b59bc1f91c6e7150bd7db03b19170ee06b320"}, + {file = "wrapt-1.14.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:07f7a7d0f388028b2df1d916e94bbb40624c59b48ecc6cbc232546706fac74c2"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:02b41b633c6261feff8ddd8d11c711df6842aba629fdd3da10249a53211a72c4"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2fe803deacd09a233e4762a1adcea5db5d31e6be577a43352936179d14d90069"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:257fd78c513e0fb5cdbe058c27a0624c9884e735bbd131935fd49e9fe719d310"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:4fcc4649dc762cddacd193e6b55bc02edca674067f5f98166d7713b193932b7f"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:11871514607b15cfeb87c547a49bca19fde402f32e2b1c24a632506c0a756656"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8ad85f7f4e20964db4daadcab70b47ab05c7c1cf2a7c1e51087bfaa83831854c"}, + {file = "wrapt-1.14.1-cp310-cp310-win32.whl", hash = "sha256:a9a52172be0b5aae932bef82a79ec0a0ce87288c7d132946d645eba03f0ad8a8"}, + {file = "wrapt-1.14.1-cp310-cp310-win_amd64.whl", hash = "sha256:6d323e1554b3d22cfc03cd3243b5bb815a51f5249fdcbb86fda4bf62bab9e164"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:43ca3bbbe97af00f49efb06e352eae40434ca9d915906f77def219b88e85d907"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:6b1a564e6cb69922c7fe3a678b9f9a3c54e72b469875aa8018f18b4d1dd1adf3"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux2010_i686.whl", hash = "sha256:00b6d4ea20a906c0ca56d84f93065b398ab74b927a7a3dbd470f6fc503f95dc3"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:a85d2b46be66a71bedde836d9e41859879cc54a2a04fad1191eb50c2066f6e9d"}, + {file = "wrapt-1.14.1-cp35-cp35m-win32.whl", hash = "sha256:dbcda74c67263139358f4d188ae5faae95c30929281bc6866d00573783c422b7"}, + {file = "wrapt-1.14.1-cp35-cp35m-win_amd64.whl", hash = "sha256:b21bb4c09ffabfa0e85e3a6b623e19b80e7acd709b9f91452b8297ace2a8ab00"}, + {file = "wrapt-1.14.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9e0fd32e0148dd5dea6af5fee42beb949098564cc23211a88d799e434255a1f4"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9736af4641846491aedb3c3f56b9bc5568d92b0692303b5a305301a95dfd38b1"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b02d65b9ccf0ef6c34cba6cf5bf2aab1bb2f49c6090bafeecc9cd81ad4ea1c1"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21ac0156c4b089b330b7666db40feee30a5d52634cc4560e1905d6529a3897ff"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:9f3e6f9e05148ff90002b884fbc2a86bd303ae847e472f44ecc06c2cd2fcdb2d"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:6e743de5e9c3d1b7185870f480587b75b1cb604832e380d64f9504a0535912d1"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:d79d7d5dc8a32b7093e81e97dad755127ff77bcc899e845f41bf71747af0c569"}, + {file = "wrapt-1.14.1-cp36-cp36m-win32.whl", hash = "sha256:81b19725065dcb43df02b37e03278c011a09e49757287dca60c5aecdd5a0b8ed"}, + {file = "wrapt-1.14.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b014c23646a467558be7da3d6b9fa409b2c567d2110599b7cf9a0c5992b3b471"}, + {file = "wrapt-1.14.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:88bd7b6bd70a5b6803c1abf6bca012f7ed963e58c68d76ee20b9d751c74a3248"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b5901a312f4d14c59918c221323068fad0540e34324925c8475263841dbdfe68"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d77c85fedff92cf788face9bfa3ebaa364448ebb1d765302e9af11bf449ca36d"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8d649d616e5c6a678b26d15ece345354f7c2286acd6db868e65fcc5ff7c24a77"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7d2872609603cb35ca513d7404a94d6d608fc13211563571117046c9d2bcc3d7"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:ee6acae74a2b91865910eef5e7de37dc6895ad96fa23603d1d27ea69df545015"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:2b39d38039a1fdad98c87279b48bc5dce2c0ca0d73483b12cb72aa9609278e8a"}, + {file = "wrapt-1.14.1-cp37-cp37m-win32.whl", hash = "sha256:60db23fa423575eeb65ea430cee741acb7c26a1365d103f7b0f6ec412b893853"}, + {file = "wrapt-1.14.1-cp37-cp37m-win_amd64.whl", hash = "sha256:709fe01086a55cf79d20f741f39325018f4df051ef39fe921b1ebe780a66184c"}, + {file = "wrapt-1.14.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:8c0ce1e99116d5ab21355d8ebe53d9460366704ea38ae4d9f6933188f327b456"}, + {file = "wrapt-1.14.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e3fb1677c720409d5f671e39bac6c9e0e422584e5f518bfd50aa4cbbea02433f"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:642c2e7a804fcf18c222e1060df25fc210b9c58db7c91416fb055897fc27e8cc"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7b7c050ae976e286906dd3f26009e117eb000fb2cf3533398c5ad9ccc86867b1"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef3f72c9666bba2bab70d2a8b79f2c6d2c1a42a7f7e2b0ec83bb2f9e383950af"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:01c205616a89d09827986bc4e859bcabd64f5a0662a7fe95e0d359424e0e071b"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:5a0f54ce2c092aaf439813735584b9537cad479575a09892b8352fea5e988dc0"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2cf71233a0ed05ccdabe209c606fe0bac7379fdcf687f39b944420d2a09fdb57"}, + {file = "wrapt-1.14.1-cp38-cp38-win32.whl", hash = "sha256:aa31fdcc33fef9eb2552cbcbfee7773d5a6792c137b359e82879c101e98584c5"}, + {file = "wrapt-1.14.1-cp38-cp38-win_amd64.whl", hash = "sha256:d1967f46ea8f2db647c786e78d8cc7e4313dbd1b0aca360592d8027b8508e24d"}, + {file = "wrapt-1.14.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3232822c7d98d23895ccc443bbdf57c7412c5a65996c30442ebe6ed3df335383"}, + {file = "wrapt-1.14.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:988635d122aaf2bdcef9e795435662bcd65b02f4f4c1ae37fbee7401c440b3a7"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cca3c2cdadb362116235fdbd411735de4328c61425b0aa9f872fd76d02c4e86"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d52a25136894c63de15a35bc0bdc5adb4b0e173b9c0d07a2be9d3ca64a332735"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40e7bc81c9e2b2734ea4bc1aceb8a8f0ceaac7c5299bc5d69e37c44d9081d43b"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:b9b7a708dd92306328117d8c4b62e2194d00c365f18eff11a9b53c6f923b01e3"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:6a9a25751acb379b466ff6be78a315e2b439d4c94c1e99cb7266d40a537995d3"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:34aa51c45f28ba7f12accd624225e2b1e5a3a45206aa191f6f9aac931d9d56fe"}, + {file = "wrapt-1.14.1-cp39-cp39-win32.whl", hash = "sha256:dee0ce50c6a2dd9056c20db781e9c1cfd33e77d2d569f5d1d9321c641bb903d5"}, + {file = "wrapt-1.14.1-cp39-cp39-win_amd64.whl", hash = "sha256:dee60e1de1898bde3b238f18340eec6148986da0455d8ba7848d50470a7a32fb"}, + {file = "wrapt-1.14.1.tar.gz", hash = "sha256:380a85cf89e0e69b7cfbe2ea9f765f004ff419f34194018a6827ac0e3edfed4d"}, +] + [[package]] name = "zipp" version = "3.11.0" @@ -2112,4 +2363,4 @@ testing = ["flake8 (<5)", "func-timeout", "jaraco.functools", "jaraco.itertools" [metadata] lock-version = "2.0" python-versions = "^3.10 | ^3.9 | ^3.8 | ^3.7" -content-hash = "e3ac1dcb6e10cc8fd7ee1ae88698ca6d2d412efe353578d9f2134adc512a523b" +content-hash = "4b01b1c46a14633a5c2595662ca272aca32dc59a8bc62a0653fd9c974a2877bd" diff --git a/pyproject.toml b/pyproject.toml index cc30c311d..346f0dc88 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -75,6 +75,8 @@ pytest-asyncio = "^0.19.0" pytest-cov = "^3.0.0" mypy = "^0.971" types-protobuf = "^3.19.22" +flake8 = { version = "^6.0.0", python = ">=3.8.1" } +pylint = { version = "^2.15.10", python = ">=3.7.2" } [build-system] requires = ["poetry-core>=1.0.0", "pyScss"] @@ -126,3 +128,34 @@ addopts = "--durations=1 -s --cov=lnbits --cov-report=xml" testpaths = [ "tests" ] + +[tool.pylint.'MESSAGES CONTROL'] +max-line-length = 300 +disable = "all" +enable = [ + "assignment-from-none", + "chained-comparison", + "consider-merging-isinstance", + "consider-using-dict-comprehension", + "consider-using-dict-items", + "consider-using-f-string", + "consider-using-in", + "dangerous-default-value", + "inconsistent-return-statements", + "lost-exception", + "pointless-string-statement", + "simplifiable-if-statement", + "super-init-not-called", + "superfluous-parens", + "unused-variable", + "use-list-literal", + "useless-else-on-loop", + "useless-object-inheritance", +] + +[tool.pylint.MASTER] +ignore-paths = [ + "^lnbits/wallets/lnd_grpc_files/.*$", +] +fail-under = 10.0 +jobs = 0 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 000000000..cdd94f566 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,28 @@ +[flake8] +max-line-length = 300 +exclude = lnbits/wallets/lnd_grpc_files/ +ignore = + # E203 whitespace before ':' + E203, + # E221: multiple spaces before operator + E221, + # E241: multiple spaces after ':' + E241, + # E402: module level import not at top of file + E402, + # E501: line too long + E501, + # E741 ambiguous variable name + E741, + # W503: line break before binary operator + W503, + # F821: undefined name - should be addressed in future PR + F821, + # E265 block comment should start with '# ' - should be addressed in future PR + E265, + # E266 too many leading '#' for block comment - should be addressed in future PR + E266, + # E722 do not use bare 'except' - should be addressed in future PR + E722, + # flake8-requirements import checks + I diff --git a/tests/conftest.py b/tests/conftest.py index fc672dd6d..6bcb463fe 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,13 +1,11 @@ import asyncio -from typing import Tuple import pytest_asyncio from httpx import AsyncClient from lnbits.app import create_app from lnbits.commands import migrate_databases -from lnbits.core.crud import create_account, create_wallet, get_wallet -from lnbits.core.models import BalanceCheck, Payment, User, Wallet +from lnbits.core.crud import create_account, create_wallet from lnbits.core.views.api import CreateInvoiceData, api_payments_create_invoice from lnbits.db import Database from lnbits.settings import settings diff --git a/tests/core/views/test_api.py b/tests/core/views/test_api.py index dbc1c1298..d62936198 100644 --- a/tests/core/views/test_api.py +++ b/tests/core/views/test_api.py @@ -1,21 +1,16 @@ import hashlib import pytest -import pytest_asyncio from lnbits import bolt11 -from lnbits.core.crud import get_wallet -from lnbits.core.views.api import ( - CreateInvoiceData, - api_payment, - api_payments_create_invoice, -) +from lnbits.core.views.api import api_payment from lnbits.settings import get_wallet_class from ...helpers import get_random_invoice_data, is_regtest WALLET = get_wallet_class() + # check if the client is working @pytest.mark.asyncio async def test_core_views_generic(client): @@ -127,7 +122,7 @@ async def test_check_payment_without_key(client, invoice): # check the payment status response = await client.get(f"/api/v1/payments/{invoice['payment_hash']}") assert response.status_code < 300 - assert response.json()["paid"] == True + assert response.json()["paid"] is True assert invoice # not key, that's why no "details" assert "details" not in response.json() @@ -145,7 +140,7 @@ async def test_check_payment_with_key(client, invoice, inkey_headers_from): f"/api/v1/payments/{invoice['payment_hash']}", headers=inkey_headers_from ) assert response.status_code < 300 - assert response.json()["paid"] == True + assert response.json()["paid"] is True assert invoice # with key, that's why with "details" assert "details" in response.json() @@ -205,7 +200,7 @@ async def test_api_payment_without_key(invoice): # check the payment status response = await api_payment(invoice["payment_hash"]) assert type(response) == dict - assert response["paid"] == True + assert response["paid"] is True # no key, that's why no "details" assert "details" not in response @@ -218,7 +213,7 @@ async def test_api_payment_with_key(invoice, inkey_headers_from): invoice["payment_hash"], inkey_headers_from["X-Api-Key"] ) assert type(response) == dict - assert response["paid"] == True + assert response["paid"] is True assert "details" in response diff --git a/tests/core/views/test_generic.py b/tests/core/views/test_generic.py index e8fc6fcc0..333251575 100644 --- a/tests/core/views/test_generic.py +++ b/tests/core/views/test_generic.py @@ -1,7 +1,4 @@ import pytest -import pytest_asyncio - -from tests.conftest import client @pytest.mark.asyncio diff --git a/tests/core/views/test_public_api.py b/tests/core/views/test_public_api.py index 6ebaeabd3..144cd161e 100644 --- a/tests/core/views/test_public_api.py +++ b/tests/core/views/test_public_api.py @@ -1,7 +1,4 @@ import pytest -import pytest_asyncio - -from lnbits.core.crud import get_wallet # check if the client is working diff --git a/tests/extensions/bleskomat/conftest.py b/tests/extensions/bleskomat/conftest.py index 13be2b579..595ba6b87 100644 --- a/tests/extensions/bleskomat/conftest.py +++ b/tests/extensions/bleskomat/conftest.py @@ -1,7 +1,6 @@ import json import secrets -import pytest import pytest_asyncio from lnbits.core.crud import create_account, create_wallet diff --git a/tests/extensions/bleskomat/test_lnurl_api.py b/tests/extensions/bleskomat/test_lnurl_api.py index ec4a26dad..a66c92204 100644 --- a/tests/extensions/bleskomat/test_lnurl_api.py +++ b/tests/extensions/bleskomat/test_lnurl_api.py @@ -1,7 +1,6 @@ import secrets import pytest -import pytest_asyncio from lnbits.core.crud import get_wallet from lnbits.extensions.bleskomat.crud import get_bleskomat_lnurl @@ -10,8 +9,6 @@ from lnbits.extensions.bleskomat.helpers import ( query_to_signing_payload, ) from lnbits.settings import get_wallet_class, settings -from tests.conftest import client -from tests.extensions.bleskomat.conftest import bleskomat, lnurl from tests.helpers import credit_wallet, is_regtest WALLET = get_wallet_class() @@ -115,7 +112,7 @@ async def test_bleskomat_lnurl_api_action_insufficient_balance(client, lnurl): assert wallet.balance_msat == 0 bleskomat_lnurl = await get_bleskomat_lnurl(secret) assert bleskomat_lnurl, not None - assert bleskomat_lnurl.has_uses_remaining() == True + assert bleskomat_lnurl.has_uses_remaining() is True WALLET.pay_invoice.assert_not_called() @@ -140,5 +137,5 @@ async def test_bleskomat_lnurl_api_action_success(client, lnurl): assert wallet.balance_msat == 50000 bleskomat_lnurl = await get_bleskomat_lnurl(secret) assert bleskomat_lnurl, not None - assert bleskomat_lnurl.has_uses_remaining() == False + assert bleskomat_lnurl.has_uses_remaining() is False WALLET.pay_invoice.assert_called_once_with(pr, 2000) diff --git a/tests/extensions/invoices/conftest.py b/tests/extensions/invoices/conftest.py index 00b9c2375..522ba81fc 100644 --- a/tests/extensions/invoices/conftest.py +++ b/tests/extensions/invoices/conftest.py @@ -1,4 +1,3 @@ -import pytest import pytest_asyncio from lnbits.core.crud import create_account, create_wallet diff --git a/tests/extensions/invoices/test_invoices_api.py b/tests/extensions/invoices/test_invoices_api.py index ed236a8fd..3c337d7e8 100644 --- a/tests/extensions/invoices/test_invoices_api.py +++ b/tests/extensions/invoices/test_invoices_api.py @@ -1,12 +1,10 @@ import pytest -import pytest_asyncio -from loguru import logger +import pytest_asyncio # noqa: F401 +from loguru import logger # noqa: F401 -from lnbits.core.crud import get_wallet -from tests.conftest import adminkey_headers_from, client, invoice -from tests.extensions.invoices.conftest import accounting_invoice, invoices_wallet -from tests.helpers import credit_wallet -from tests.mocks import WALLET +from lnbits.core.crud import get_wallet # noqa: F401 +from tests.helpers import credit_wallet # noqa: F401 +from tests.mocks import WALLET # noqa: F401 @pytest.mark.asyncio @@ -80,7 +78,7 @@ async def test_invoices_api_partial_pay_invoice( f"/invoices/api/v1/invoice/{invoice_id}/payments/{payment_hash}" ) assert response.status_code == 200 - assert response.json()["paid"] == True + assert response.json()["paid"] is True # check invoice status response = await client.get(f"/invoices/api/v1/invoice/{invoice_id}") @@ -124,7 +122,7 @@ async def test_invoices_api_partial_pay_invoice( # f"/invoices/api/v1/invoice/{invoice_id}/payments/{payment_hash}" # ) # assert response.status_code == 200 -# assert response.json()["paid"] == True +# assert response.json()["paid"] is True # # check invoice status # response = await client.get(f"/invoices/api/v1/invoice/{invoice_id}") diff --git a/tests/helpers.py b/tests/helpers.py index 9bb10571a..9d2aae722 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -27,7 +27,7 @@ async def credit_wallet(wallet_id: str, amount: int): def get_random_string(N=10): return "".join( random.SystemRandom().choice(string.ascii_uppercase + string.digits) - for _ in range(10) + for _ in range(N) ) diff --git a/tools/conv.py b/tools/conv.py index f01295fc7..1b35e25a3 100644 --- a/tools/conv.py +++ b/tools/conv.py @@ -50,11 +50,13 @@ def check_db_versions(sqdb): postgres.execute("SELECT * FROM public.dbversions;") dbpost = dict(postgres.fetchall()) - for key in dblite.keys(): - if key in dblite and key in dbpost and dblite[key] != dbpost[key]: - raise Exception( - f"sqlite database version ({dblite[key]}) of {key} doesn't match postgres database version {dbpost[key]}" - ) + for key, value in dblite.items(): + if key in dblite and key in dbpost: + version = dbpost[key] + if value != version: + raise Exception( + f"sqlite database version ({value}) of {key} doesn't match postgres database version {version}" + ) connection = postgres.connection postgres.close() @@ -101,7 +103,7 @@ def insert_to_pg(query, data): connection.close() -def migrate_core(file: str, exclude_tables: List[str] = []): +def migrate_core(file: str, exclude_tables: List[str] = None): print(f"Migrating core: {file}") migrate_db(file, "public", exclude_tables) print("✅ Migrated core") @@ -115,7 +117,7 @@ def migrate_ext(file: str): print(f"✅ Migrated ext: {schema}") -def migrate_db(file: str, schema: str, exclude_tables: List[str] = []): +def migrate_db(file: str, schema: str, exclude_tables: List[str] = None): # first we check if this file exists: assert os.path.isfile(file), f"{file} does not exist!" @@ -133,7 +135,7 @@ def migrate_db(file: str, schema: str, exclude_tables: List[str] = []): # hard coded skip for dbversions (already produced during startup) if tableName == "dbversions": continue - if tableName in exclude_tables: + if exclude_tables and tableName in exclude_tables: continue columns = sq.execute(f"PRAGMA table_info({tableName})").fetchall()