From 355806608bb706756f3e4194a0e708172f018b1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dni=20=E2=9A=A1?= Date: Wed, 16 Aug 2023 12:17:54 +0200 Subject: [PATCH] [CHORE] E722 bare exception fix (#1871) * [CHORE] E722 bare exception fix remove all bare exceptions from codebase and change it in `.flake8` --- .flake8 | 2 -- lnbits/app.py | 2 +- lnbits/core/crud.py | 2 +- lnbits/core/helpers.py | 2 +- lnbits/core/migrations.py | 2 +- lnbits/core/models.py | 2 +- lnbits/core/services.py | 4 ++-- lnbits/core/views/admin_api.py | 4 ++-- lnbits/core/views/api.py | 16 ++++++++-------- lnbits/core/views/generic.py | 2 +- lnbits/core/views/public_api.py | 2 +- lnbits/decorators.py | 2 +- lnbits/helpers.py | 2 +- lnbits/settings.py | 2 +- lnbits/wallets/cliche.py | 4 ++-- lnbits/wallets/cln.py | 6 +++--- lnbits/wallets/eclair.py | 12 ++++++------ lnbits/wallets/lnbits.py | 4 ++-- lnbits/wallets/lndgrpc.py | 4 ++-- lnbits/wallets/lndrest.py | 4 ++-- lnbits/wallets/lnpay.py | 2 +- lnbits/wallets/lntips.py | 12 ++++++------ lnbits/wallets/macaroon/macaroon.py | 2 +- lnbits/wallets/spark.py | 2 +- 24 files changed, 48 insertions(+), 50 deletions(-) diff --git a/.flake8 b/.flake8 index 9fc73459..d3497030 100644 --- a/.flake8 +++ b/.flake8 @@ -10,7 +10,5 @@ ignore = W503, # F821: undefined name - should be addressed in future PR F821, - # E722 do not use bare 'except' - should be addressed in future PR - E722, # flake8-requirements import checks I diff --git a/lnbits/app.py b/lnbits/app.py index 8d9d64fa..74aefb94 100644 --- a/lnbits/app.py +++ b/lnbits/app.py @@ -133,7 +133,7 @@ async def check_funding_source() -> None: f"The backend for {WALLET.__class__.__name__} isn't working properly: '{error_message}'", RuntimeWarning, ) - except: + except Exception: pass if settings.lnbits_admin_ui and retry_counter == timeout: diff --git a/lnbits/core/crud.py b/lnbits/core/crud.py index fd608004..ea9edfe9 100644 --- a/lnbits/core/crud.py +++ b/lnbits/core/crud.py @@ -520,7 +520,7 @@ async def create_payment( try: invoice = bolt11.decode(payment_request) expiration_date = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry) - except: + except Exception: # assume maximum bolt11 expiry of 31 days to be on the safe side expiration_date = datetime.datetime.now() + datetime.timedelta(days=31) diff --git a/lnbits/core/helpers.py b/lnbits/core/helpers.py index 7e86840d..a5502a50 100644 --- a/lnbits/core/helpers.py +++ b/lnbits/core/helpers.py @@ -71,7 +71,7 @@ def to_valid_user_id(user_id: str) -> UUID: raise ValueError("User ID must have at least 128 bits") try: int(user_id, 16) - except: + except Exception: raise ValueError("Invalid hex string for User ID.") return UUID(hex=user_id[:32], version=4) diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py index 435e30b0..09f930a0 100644 --- a/lnbits/core/migrations.py +++ b/lnbits/core/migrations.py @@ -251,7 +251,7 @@ async def m007_set_invoice_expiries(db): checking_id, ), ) - except: + except Exception: continue except OperationalError: # this is necessary now because it may be the case that this migration will diff --git a/lnbits/core/models.py b/lnbits/core/models.py index da67bc5f..cd7c79f0 100644 --- a/lnbits/core/models.py +++ b/lnbits/core/models.py @@ -41,7 +41,7 @@ class Wallet(BaseModel): url = url_for("/withdraw", external=True, usr=self.user, wal=self.id) try: return lnurl_encode(url) - except: + except Exception: return "" def lnurlauth_key(self, domain: str) -> SigningKey: diff --git a/lnbits/core/services.py b/lnbits/core/services.py index 3fa8d84f..e4b3c9b0 100644 --- a/lnbits/core/services.py +++ b/lnbits/core/services.py @@ -299,7 +299,7 @@ async def redeem_lnurl_withdraw( extra=extra, conn=conn, ) - except: + except Exception: logger.warning( f"failed to create invoice on redeem_lnurl_withdraw from {lnurl}. params: {res}" ) @@ -495,7 +495,7 @@ def update_cached_settings(sets_dict: dict): if key not in readonly_variables: try: setattr(settings, key, value) - except: + except Exception: logger.warning(f"Failed overriding setting: {key}, value: {value}") if "super_user" in sets_dict: setattr(settings, "super_user", sets_dict["super_user"]) diff --git a/lnbits/core/views/admin_api.py b/lnbits/core/views/admin_api.py index 0f63800a..ea37fc6f 100644 --- a/lnbits/core/views/admin_api.py +++ b/lnbits/core/views/admin_api.py @@ -34,7 +34,7 @@ async def api_auditor(): "node_balance_msats": int(node_balance), "lnbits_balance_msats": int(total_balance), } - except: + except Exception: raise HTTPException( status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Could not audit balance.", @@ -94,7 +94,7 @@ async def api_topup_balance( ) -> dict[str, str]: try: await get_wallet(id) - except: + except Exception: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="wallet does not exist." ) diff --git a/lnbits/core/views/api.py b/lnbits/core/views/api.py index 11d47da9..323a17ed 100644 --- a/lnbits/core/views/api.py +++ b/lnbits/core/views/api.py @@ -513,7 +513,7 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type try: url = lnurl.decode(code) domain = urlparse(url).netloc - except: + except Exception: # parse internet identifier (user@domain.com) name_domain = code.split("@") if len(name_domain) == 2 and len(name_domain[1].split(".")) >= 2: @@ -648,7 +648,7 @@ async def api_payments_decode(data: DecodePayment, response: Response): "route_hints": invoice.route_hints, "min_final_cltv_expiry": invoice.min_final_cltv_expiry, } - except: + except Exception: response.status_code = HTTPStatus.BAD_REQUEST return {"message": "Failed to decode"} @@ -743,7 +743,7 @@ async def websocket_update_post(item_id: str, data: str): try: await websocketUpdater(item_id, data) return {"sent": True, "data": data} - except: + except Exception: return {"sent": False, "data": data} @@ -752,7 +752,7 @@ async def websocket_update_get(item_id: str, data: str): try: await websocketUpdater(item_id, data) return {"sent": True, "data": data} - except: + except Exception: return {"sent": False, "data": data} @@ -930,7 +930,7 @@ async def api_create_tinyurl( if tinyurl.wallet == wallet.wallet.inkey: return tinyurl return await create_tinyurl(url, endless, wallet.wallet.inkey) - except: + except Exception: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST, detail="Unable to create tinyurl" ) @@ -948,7 +948,7 @@ async def api_get_tinyurl( raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided." ) - except: + except Exception: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail="Unable to fetch tinyurl" ) @@ -967,7 +967,7 @@ async def api_delete_tinyurl( raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided." ) - except: + except Exception: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST, detail="Unable to delete" ) @@ -982,7 +982,7 @@ async def api_tinyurl(tinyurl_id: str): return response else: return - except: + except Exception: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail="unable to find tinyurl" ) diff --git a/lnbits/core/views/generic.py b/lnbits/core/views/generic.py index ff3bf6b8..7b36b4b7 100644 --- a/lnbits/core/views/generic.py +++ b/lnbits/core/views/generic.py @@ -275,7 +275,7 @@ async def lnurl_full_withdraw_callback(request: Request): async def pay(): try: await pay_invoice(wallet_id=wallet.id, payment_request=pr) - except: + except Exception: pass asyncio.create_task(pay()) diff --git a/lnbits/core/views/public_api.py b/lnbits/core/views/public_api.py index 934fc617..bbc33195 100644 --- a/lnbits/core/views/public_api.py +++ b/lnbits/core/views/public_api.py @@ -28,7 +28,7 @@ async def api_public_payment_longpolling(payment_hash): expiration = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry) if expiration < datetime.datetime.now(): return {"status": "expired"} - except: + except Exception: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST, detail="Invalid bolt11 invoice." ) diff --git a/lnbits/decorators.py b/lnbits/decorators.py index ee404635..b3c60570 100644 --- a/lnbits/decorators.py +++ b/lnbits/decorators.py @@ -173,7 +173,7 @@ async def get_key_type( pass else: raise - except: + except Exception: raise raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail="Wallet does not exist." diff --git a/lnbits/helpers.py b/lnbits/helpers.py index f1075b17..065d0d9b 100644 --- a/lnbits/helpers.py +++ b/lnbits/helpers.py @@ -86,7 +86,7 @@ def get_current_extension_name() -> str: with open(config_path) as json_file: config = json.load(json_file) ext_name = config["name"] - except: + except Exception: ext_name = extension_director_name return ext_name diff --git a/lnbits/settings.py b/lnbits/settings.py index 9caeebb4..6de31e72 100644 --- a/lnbits/settings.py +++ b/lnbits/settings.py @@ -388,7 +388,7 @@ try: .strip() .decode("ascii") ) -except: +except Exception: settings.lnbits_commit = "docker" settings.version = importlib.metadata.version("lnbits") diff --git a/lnbits/wallets/cliche.py b/lnbits/wallets/cliche.py index cb11f520..e6d6af7c 100644 --- a/lnbits/wallets/cliche.py +++ b/lnbits/wallets/cliche.py @@ -36,7 +36,7 @@ class ClicheWallet(Wallet): ) try: data = json.loads(r) - except: + except Exception: return StatusResponse( f"Failed to connect to {self.endpoint}, got: '{r[:200]}...'", 0 ) @@ -168,7 +168,7 @@ class ClicheWallet(Wallet): try: if data["result"]["status"]: yield data["result"]["payment_hash"] - except: + except Exception: continue except Exception as exc: logger.error( diff --git a/lnbits/wallets/cln.py b/lnbits/wallets/cln.py index 0bf46d87..b9d2e65f 100644 --- a/lnbits/wallets/cln.py +++ b/lnbits/wallets/cln.py @@ -135,7 +135,7 @@ class CoreLightningWallet(Wallet): except RpcError as exc: try: error_message = exc.error["attempts"][-1]["fail_reason"] - except: + except Exception: error_message = f"CLN method '{exc.method}' failed with '{exc.error.get('message') or exc.error}'." return PaymentResponse(False, None, None, None, error_message) except Exception as exc: @@ -149,7 +149,7 @@ class CoreLightningWallet(Wallet): async def get_invoice_status(self, checking_id: str) -> PaymentStatus: try: r = self.ln.listinvoices(payment_hash=checking_id) - except: + except Exception: return PaymentStatus(None) if not r["invoices"]: return PaymentStatus(None) @@ -170,7 +170,7 @@ class CoreLightningWallet(Wallet): async def get_payment_status(self, checking_id: str) -> PaymentStatus: try: r = self.ln.listpays(payment_hash=checking_id) - except: + except Exception: return PaymentStatus(None) if "pays" not in r or not r["pays"]: return PaymentStatus(None) diff --git a/lnbits/wallets/eclair.py b/lnbits/wallets/eclair.py index bf307e23..62f1b5cc 100644 --- a/lnbits/wallets/eclair.py +++ b/lnbits/wallets/eclair.py @@ -53,7 +53,7 @@ class EclairWallet(Wallet): r = await self.client.post("/globalbalance", timeout=5) try: data = r.json() - except: + except Exception: return StatusResponse( f"Failed to connect to {self.url}, got: '{r.text[:200]}...'", 0 ) @@ -93,7 +93,7 @@ class EclairWallet(Wallet): try: data = r.json() error_message = data["error"] - except: + except Exception: error_message = r.text return InvoiceResponse(False, None, None, error_message) @@ -112,7 +112,7 @@ class EclairWallet(Wallet): try: data = r.json() error_message = data["error"] - except: + except Exception: error_message = r.text return PaymentResponse(False, None, None, None, error_message) @@ -136,7 +136,7 @@ class EclairWallet(Wallet): try: data = r.json() error_message = data["error"] - except: + except Exception: error_message = r.text return PaymentResponse(None, checking_id, None, preimage, error_message) @@ -175,7 +175,7 @@ class EclairWallet(Wallet): "pending": None, } return PaymentStatus(statuses.get(data["status"]["type"])) - except: + except Exception: return PaymentStatus(None) async def get_payment_status(self, checking_id: str) -> PaymentStatus: @@ -206,7 +206,7 @@ class EclairWallet(Wallet): return PaymentStatus( statuses.get(data["status"]["type"]), fee_msat, preimage ) - except: + except Exception: return PaymentStatus(None) async def paid_invoices_stream(self) -> AsyncGenerator[str, None]: diff --git a/lnbits/wallets/lnbits.py b/lnbits/wallets/lnbits.py index 1e34ae50..0bc47d06 100644 --- a/lnbits/wallets/lnbits.py +++ b/lnbits/wallets/lnbits.py @@ -47,7 +47,7 @@ class LNbitsWallet(Wallet): try: data = r.json() - except: + except Exception: return StatusResponse( f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0 ) @@ -117,7 +117,7 @@ class LNbitsWallet(Wallet): if r.is_error: return PaymentStatus(None) return PaymentStatus(r.json()["paid"]) - except: + except Exception: return PaymentStatus(None) async def get_payment_status(self, checking_id: str) -> PaymentStatus: diff --git a/lnbits/wallets/lndgrpc.py b/lnbits/wallets/lndgrpc.py index 5cb90a7c..b471370c 100644 --- a/lnbits/wallets/lndgrpc.py +++ b/lnbits/wallets/lndgrpc.py @@ -83,7 +83,7 @@ def hex_to_b64(hex_str: str) -> str: def hex_to_bytes(hex_str: str) -> bytes: try: return bytes.fromhex(hex_str) - except: + except Exception: return b"" @@ -289,7 +289,7 @@ class LndWallet(Wallet): bytes_to_hex(payment.htlcs[-1].preimage), ) return PaymentStatus(statuses[payment.status]) - except: # most likely the payment wasn't found + except Exception: # most likely the payment wasn't found return PaymentStatus(None) return PaymentStatus(None) diff --git a/lnbits/wallets/lndrest.py b/lnbits/wallets/lndrest.py index 4b00dbbc..d8d51fd6 100644 --- a/lnbits/wallets/lndrest.py +++ b/lnbits/wallets/lndrest.py @@ -201,7 +201,7 @@ class LndRestWallet(Wallet): ) else: return PaymentStatus(None) - except: + except Exception: continue return PaymentStatus(None) @@ -216,7 +216,7 @@ class LndRestWallet(Wallet): inv = json.loads(line)["result"] if not inv["settled"]: continue - except: + except Exception: continue payment_hash = base64.b64decode(inv["r_hash"]).hex() diff --git a/lnbits/wallets/lnpay.py b/lnbits/wallets/lnpay.py index b2394d57..0f2ad191 100644 --- a/lnbits/wallets/lnpay.py +++ b/lnbits/wallets/lnpay.py @@ -102,7 +102,7 @@ class LNPayWallet(Wallet): try: data = r.json() - except: + except Exception: return PaymentResponse( False, None, 0, None, f"Got invalid JSON: {r.text[:200]}" ) diff --git a/lnbits/wallets/lntips.py b/lnbits/wallets/lntips.py index a4c935fe..f19f9c4f 100644 --- a/lnbits/wallets/lntips.py +++ b/lnbits/wallets/lntips.py @@ -42,7 +42,7 @@ class LnTipsWallet(Wallet): r = await self.client.get("/api/v1/balance", timeout=40) try: data = r.json() - except: + except Exception: return StatusResponse( f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0 ) @@ -76,7 +76,7 @@ class LnTipsWallet(Wallet): try: data = r.json() error_message = data["message"] - except: + except Exception: error_message = r.text return InvoiceResponse(False, None, None, error_message) @@ -99,7 +99,7 @@ class LnTipsWallet(Wallet): try: data = r.json() error_message = data["error"] - except: + except Exception: error_message = r.text return PaymentResponse(False, None, 0, None, error_message) @@ -120,7 +120,7 @@ class LnTipsWallet(Wallet): data = r.json() return PaymentStatus(data["paid"]) - except: + except Exception: return PaymentStatus(None) async def get_payment_status(self, checking_id: str) -> PaymentStatus: @@ -135,7 +135,7 @@ class LnTipsWallet(Wallet): paid_to_status = {False: None, True: True} return PaymentStatus(paid_to_status[data.get("paid")]) - except: + except Exception: return PaymentStatus(None) async def paid_invoices_stream(self) -> AsyncGenerator[str, None]: @@ -154,7 +154,7 @@ class LnTipsWallet(Wallet): inv = json.loads(data) if not inv.get("payment_hash"): continue - except: + except Exception: continue yield inv["payment_hash"] except Exception: diff --git a/lnbits/wallets/macaroon/macaroon.py b/lnbits/wallets/macaroon/macaroon.py index 05d667be..ca75303e 100644 --- a/lnbits/wallets/macaroon/macaroon.py +++ b/lnbits/wallets/macaroon/macaroon.py @@ -27,7 +27,7 @@ def load_macaroon(macaroon: str) -> str: # convert the bas64 macaroon to hex try: macaroon = base64.b64decode(macaroon).hex() - except: + except Exception: pass return macaroon diff --git a/lnbits/wallets/spark.py b/lnbits/wallets/spark.py index 17410a1b..2e312109 100644 --- a/lnbits/wallets/spark.py +++ b/lnbits/wallets/spark.py @@ -73,7 +73,7 @@ class SparkWallet(Wallet): try: data = r.json() - except: + except Exception: raise UnknownError(r.text) if r.is_error: