diff --git a/cashu/core/crypto/aes.py b/cashu/core/crypto/aes.py index 7f856bf7..562e35db 100644 --- a/cashu/core/crypto/aes.py +++ b/cashu/core/crypto/aes.py @@ -20,7 +20,7 @@ class AESCipher: def __init__(self, key: str, description=""): self.key: str = key - self.description = description + " " + self.description = f"{description} " def pad(self, data): length = BLOCK_SIZE - (len(data) % BLOCK_SIZE) diff --git a/cashu/core/crypto/keys.py b/cashu/core/crypto/keys.py index 36fb7974..95abac6f 100644 --- a/cashu/core/crypto/keys.py +++ b/cashu/core/crypto/keys.py @@ -56,7 +56,7 @@ def derive_keyset_id(keys: Dict[int, PublicKey]): # sort public keys by amount sorted_keys = dict(sorted(keys.items())) pubkeys_concat = b"".join([p.serialize() for _, p in sorted_keys.items()]) - return "00" + hashlib.sha256(pubkeys_concat).hexdigest()[:14] + return f"00{hashlib.sha256(pubkeys_concat).hexdigest()[:14]}" def derive_keyset_id_deprecated(keys: Dict[int, PublicKey]): diff --git a/cashu/core/crypto/secp.py b/cashu/core/crypto/secp.py index d0bb0e10..fc46f4a2 100644 --- a/cashu/core/crypto/secp.py +++ b/cashu/core/crypto/secp.py @@ -10,7 +10,7 @@ def __add__(self, pubkey2): new_pub.combine([self.public_key, pubkey2.public_key]) return new_pub else: - raise TypeError("Cant add pubkey and %s" % pubkey2.__class__) + raise TypeError(f"Can't add pubkey and {pubkey2.__class__}") def __neg__(self): serialized = self.serialize() @@ -23,7 +23,7 @@ def __sub__(self, pubkey2): if isinstance(pubkey2, PublicKey): return self + (-pubkey2) # type: ignore else: - raise TypeError("Can't add pubkey and %s" % pubkey2.__class__) + raise TypeError(f"Can't add pubkey and {pubkey2.__class__}") def mult(self, privkey): if isinstance(privkey, PrivateKey): @@ -37,7 +37,7 @@ def __eq__(self, pubkey2): seq2 = pubkey2.to_data() # type: ignore return seq1 == seq2 else: - raise TypeError("Can't compare pubkey and %s" % pubkey2.__class__) + raise TypeError(f"Can't compare pubkey and {pubkey2.__class__}") def to_data(self): assert self.public_key diff --git a/cashu/lightning/blink.py b/cashu/lightning/blink.py index 5c9fe7ba..9d18d671 100644 --- a/cashu/lightning/blink.py +++ b/cashu/lightning/blink.py @@ -85,7 +85,7 @@ async def status(self) -> StatusResponse: ) r.raise_for_status() except Exception as exc: - logger.error(f"Blink API error: {str(exc)}") + logger.error(f"Blink API error: {exc}") return StatusResponse( error_message=f"Failed to connect to {self.endpoint} due to: {exc}", balance=0, @@ -158,7 +158,7 @@ async def create_invoice( ) r.raise_for_status() except Exception as e: - logger.error(f"Blink API error: {str(e)}") + logger.error(f"Blink API error: {e}") return InvoiceResponse(ok=False, error_message=str(e)) resp = r.json() @@ -212,7 +212,7 @@ async def pay_invoice( ) r.raise_for_status() except Exception as e: - logger.error(f"Blink API error: {str(e)}") + logger.error(f"Blink API error: {e}") return PaymentResponse( result=PaymentResult.UNKNOWN, error_message=str(e), @@ -283,7 +283,7 @@ async def get_invoice_status(self, checking_id: str) -> PaymentStatus: r = await self.client.post(url=self.endpoint, data=json.dumps(data)) # type: ignore r.raise_for_status() except Exception as e: - logger.error(f"Blink API error: {str(e)}") + logger.error(f"Blink API error: {e}") return PaymentStatus(result=PaymentResult.UNKNOWN, error_message=str(e)) resp: dict = r.json() error_message = ( @@ -449,7 +449,7 @@ async def get_payment_quote( except httpx.ReadTimeout: pass except Exception as e: - logger.error(f"Blink API error: {str(e)}") + logger.error(f"Blink API error: {e}") raise e invoice_obj = decode(bolt11) diff --git a/cashu/lightning/lndrest.py b/cashu/lightning/lndrest.py index 7b503397..e7ea3d18 100644 --- a/cashu/lightning/lndrest.py +++ b/cashu/lightning/lndrest.py @@ -305,7 +305,7 @@ async def get_invoice_status(self, checking_id: str) -> PaymentStatus: try: data = r.json() except json.JSONDecodeError as e: - logger.error(f"Incomprehensible response: {str(e)}") + logger.error(f"Incomprehensible response: {e}") return PaymentStatus(result=PaymentResult.UNKNOWN, error_message=str(e)) if not data or not data.get("state"): return PaymentStatus( diff --git a/cashu/lightning/strike.py b/cashu/lightning/strike.py index dbf2e07f..34cec97e 100644 --- a/cashu/lightning/strike.py +++ b/cashu/lightning/strike.py @@ -89,7 +89,7 @@ class StrikePaymentResponse(BaseModel): class StrikeWallet(LightningBackend): """https://docs.strike.me/api/""" - supported_units = set([Unit.sat, Unit.usd, Unit.eur]) + supported_units = {Unit.sat, Unit.usd, Unit.eur} supports_description: bool = False currency_map = {Unit.sat: "BTC", Unit.usd: "USD", Unit.eur: "EUR"} diff --git a/cashu/mint/crud.py b/cashu/mint/crud.py index a3f6b1f2..ff5457bb 100644 --- a/cashu/mint/crud.py +++ b/cashu/mint/crud.py @@ -306,7 +306,7 @@ async def get_promises( rows = await (conn or db).fetchall( f""" SELECT * from {db.table_with_schema('promises')} - WHERE b_ IN ({','.join([':b_' + str(i) for i in range(len(b_s))])}) + WHERE b_ IN ({','.join([f":b_{i}" for i in range(len(b_s))])}) """, {f"b_{i}": b_s[i] for i in range(len(b_s))}, ) @@ -376,7 +376,7 @@ async def get_proofs_pending( ) -> List[Proof]: query = f""" SELECT * from {db.table_with_schema('proofs_pending')} - WHERE y IN ({','.join([':y_' + str(i) for i in range(len(Ys))])}) + WHERE y IN ({','.join([f":y_{i}" for i in range(len(Ys))])}) """ values = {f"y_{i}": Ys[i] for i in range(len(Ys))} rows = await (conn or db).fetchall(query, values) @@ -729,7 +729,7 @@ async def get_proofs_used( ) -> List[Proof]: query = f""" SELECT * from {db.table_with_schema('proofs_used')} - WHERE y IN ({','.join([':y_' + str(i) for i in range(len(Ys))])}) + WHERE y IN ({','.join([f":y_{i}" for i in range(len(Ys))])}) """ values = {f"y_{i}": Ys[i] for i in range(len(Ys))} rows = await (conn or db).fetchall(query, values) diff --git a/cashu/mint/ledger.py b/cashu/mint/ledger.py index a48bfc7d..5441aa2e 100644 --- a/cashu/mint/ledger.py +++ b/cashu/mint/ledger.py @@ -905,7 +905,7 @@ async def melt( melt_quote, melt_quote.fee_reserve * 1000 ) logger.debug( - f"Melt – Result: {str(payment.result)}: preimage: {payment.preimage}," + f"Melt – Result: {payment.result}: preimage: {payment.preimage}," f" fee: {payment.fee.str() if payment.fee is not None else 'None'}" ) if ( diff --git a/cashu/mint/startup.py b/cashu/mint/startup.py index f846061f..7820d17a 100644 --- a/cashu/mint/startup.py +++ b/cashu/mint/startup.py @@ -86,7 +86,7 @@ async def rotate_keys(n_seconds=60): i += 1 logger.info("Rotating keys.") incremented_derivation_path = ( - "/".join(ledger.derivation_path.split("/")[:-1]) + f"/{i}" + f"{'/'.join(ledger.derivation_path.split('/')[:-1])}/{i}" ) await ledger.activate_keyset(derivation_path=incremented_derivation_path) logger.info(f"Current keyset: {ledger.keyset.id}") diff --git a/cashu/mint/verification.py b/cashu/mint/verification.py index 5521d64f..ca34b7b5 100644 --- a/cashu/mint/verification.py +++ b/cashu/mint/verification.py @@ -214,7 +214,7 @@ def _verify_amount(self, amount: int) -> int: """Any amount used should be positive and not larger than 2^MAX_ORDER.""" valid = amount > 0 and amount < 2**settings.max_order if not valid: - raise NotAllowedError("invalid amount: " + str(amount)) + raise NotAllowedError(f"invalid amount: {amount}") return amount def _verify_units_match( diff --git a/cashu/nostr/bech32.py b/cashu/nostr/bech32.py index 0ae6c808..20411a5c 100644 --- a/cashu/nostr/bech32.py +++ b/cashu/nostr/bech32.py @@ -73,7 +73,7 @@ def bech32_create_checksum(hrp, data, spec): def bech32_encode(hrp, data, spec): """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data, spec) - return hrp + "1" + "".join([CHARSET[d] for d in combined]) + return f"{hrp}1{''.join([CHARSET[d] for d in combined])}" def bech32_decode(bech): diff --git a/cashu/nostr/event.py b/cashu/nostr/event.py index 6271e7ef..06f495b2 100644 --- a/cashu/nostr/event.py +++ b/cashu/nostr/event.py @@ -70,7 +70,7 @@ def add_event_ref(self, event_id: str): def verify(self) -> bool: pub_key = PublicKey( - bytes.fromhex("02" + self.public_key), True + bytes.fromhex(f"02{self.public_key}"), True ) # add 02 for schnorr (bip340) return pub_key.schnorr_verify( bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True diff --git a/cashu/nostr/key.py b/cashu/nostr/key.py index 6988964a..ecc45add 100644 --- a/cashu/nostr/key.py +++ b/cashu/nostr/key.py @@ -63,7 +63,7 @@ def tweak_add(self, scalar: bytes) -> bytes: return sk.tweak_add(scalar) def compute_shared_secret(self, public_key_hex: str) -> bytes: - pk = secp256k1.PublicKey(bytes.fromhex("02" + public_key_hex), True) + pk = secp256k1.PublicKey(bytes.fromhex(f"02{public_key_hex}"), True) return pk.ecdh(self.raw_secret, hashfn=copy_x) def encrypt_message(self, message: str, public_key_hex: str) -> str: diff --git a/cashu/tor/tor.py b/cashu/tor/tor.py index b4f9193d..ea91f2f7 100755 --- a/cashu/tor/tor.py +++ b/cashu/tor/tor.py @@ -65,7 +65,7 @@ def run_daemon(self, verbose=False): stderr=subprocess.STDOUT, start_new_session=True, ) - logger.debug("Running tor daemon with pid {}".format(self.tor_proc.pid)) + logger.debug(f"Running tor daemon with pid {self.tor_proc.pid}") with open(self.pid_file, "w", encoding="utf-8") as f: f.write(str(self.tor_proc.pid)) diff --git a/cashu/wallet/cli/cli.py b/cashu/wallet/cli/cli.py index 1f994d53..9e8e927a 100644 --- a/cashu/wallet/cli/cli.py +++ b/cashu/wallet/cli/cli.py @@ -229,7 +229,7 @@ async def pay( send_proofs, invoice, quote.fee_reserve, quote.quote ) except Exception as e: - print(f" Error paying invoice: {str(e)}") + print(f" Error paying invoice: {e}") return if ( melt_response.state @@ -333,7 +333,7 @@ def mint_invoice_callback(msg: JSONRPCNotficationParams): # set paid so we won't react to any more callbacks paid = True except Exception as e: - print(f"Error during mint: {str(e)}") + print(f"Error during mint: {e}") return else: logger.debug("Quote not paid yet.") @@ -386,7 +386,7 @@ def mint_invoice_callback(msg: JSONRPCNotficationParams): print(".", end="", flush=True) continue else: - print(f"Error: {str(e)}") + print(f"Error: {e}") if not paid: print("\n") print( @@ -1021,10 +1021,8 @@ async def info(ctx: Context, mint: bool, mnemonic: bool): if mint_info.get("time"): print(f" - Server time: {mint_info['time']}") if mint_info.get("nuts"): - print( - " - Supported NUTS:" - f" {', '.join(['NUT-'+str(k) for k in mint_info['nuts'].keys()])}" - ) + nuts_str = ', '.join([f"NUT-{k}" for k in mint_info['nuts'].keys()]) + print(f" - Supported NUTS: {nuts_str}") print("") except Exception as e: print("") diff --git a/cashu/wallet/cli/cli_helpers.py b/cashu/wallet/cli/cli_helpers.py index 1e146ca3..52205b21 100644 --- a/cashu/wallet/cli/cli_helpers.py +++ b/cashu/wallet/cli/cli_helpers.py @@ -212,8 +212,8 @@ async def receive_all_pending(ctx: Context, wallet: Wallet): if mint_url and token_obj: unit = Unit[token_obj.unit] print( - f"Could not receive {unit.str(token_obj.amount)} from mint {mint_url}: {str(e)}" + f"Could not receive {unit.str(token_obj.amount)} from mint {mint_url}: {e}" ) else: - print(f"Could not receive token: {str(e)}") + print(f"Could not receive token: {e}") continue diff --git a/cashu/wallet/nostr.py b/cashu/wallet/nostr.py index bb989d03..9550c6e9 100644 --- a/cashu/wallet/nostr.py +++ b/cashu/wallet/nostr.py @@ -24,7 +24,7 @@ async def nip5_to_pubkey(wallet: Wallet, address: str): await wallet._init_s() # if no username is given, use default _ (NIP-05 stuff) if "@" not in address: - address = "_@" + address + address = f"_@{address}" # now we can use it user, host = address.split("@") resp_dict = {} diff --git a/cashu/wallet/v1_api.py b/cashu/wallet/v1_api.py index 5905391a..3cb007c3 100644 --- a/cashu/wallet/v1_api.py +++ b/cashu/wallet/v1_api.py @@ -170,10 +170,8 @@ async def _get_keys(self) -> List[WalletKeyset]: keys_dict: dict = resp.json() assert len(keys_dict), Exception("did not receive any keys") keys = KeysResponse.parse_obj(keys_dict) - logger.debug( - f"Received {len(keys.keysets)} keysets from mint:" - f" {' '.join([k.id + f' ({k.unit})' for k in keys.keysets])}." - ) + keysets_str = ' '.join([f"{k.id} ({k.unit})" for k in keys.keysets]) + logger.debug(f"Received {len(keys.keysets)} keysets from mint: {keysets_str}.") ret = [ WalletKeyset( id=keyset.id, @@ -388,7 +386,7 @@ async def melt_quote( ret: CheckFeesResponse_deprecated = await self.check_fees_deprecated( payment_request ) - quote_id = "deprecated_" + str(uuid.uuid4()) + quote_id = f"deprecated_{uuid.uuid4()}" return PostMeltQuoteResponse( quote=quote_id, amount=amount or invoice_obj.amount_msat // 1000, diff --git a/cashu/wallet/wallet.py b/cashu/wallet/wallet.py index 7640baf7..d33c41bf 100644 --- a/cashu/wallet/wallet.py +++ b/cashu/wallet/wallet.py @@ -162,9 +162,8 @@ async def with_db( self.keysets = {k.id: k for k in keysets_active_unit} else: self.keysets = {k.id: k for k in keysets_list} - logger.debug( - f"Loaded keysets: {' '.join([i + f' {k.unit}' for i, k in self.keysets.items()])}" - ) + keysets_str = ' '.join([f"{i} {k.unit}" for i, k in self.keysets.items()]) + logger.debug(f"Loaded keysets: {keysets_str}") return self async def _migrate_database(self): @@ -349,9 +348,8 @@ async def load_proofs(self, reload: bool = False, all_keysets=False) -> None: for keyset_id in self.keysets: proofs = await get_proofs(db=self.db, id=keyset_id, conn=conn) self.proofs.extend(proofs) - logger.trace( - f"Proofs loaded for keysets: {' '.join([k.id + f' ({k.unit})' for k in self.keysets.values()])}" - ) + proofs_str = ' '.join([f"{k.id} ({k.unit})" for k in self.keysets.values()]) + logger.trace(f"Proofs loaded for keysets: {proofs_str}") async def load_keysets_from_db( self, url: Union[str, None] = "", unit: Union[str, None] = "" diff --git a/cashu/wallet/wallet_deprecated.py b/cashu/wallet/wallet_deprecated.py index 7db58efa..fc6326ec 100644 --- a/cashu/wallet/wallet_deprecated.py +++ b/cashu/wallet/wallet_deprecated.py @@ -155,7 +155,7 @@ async def _get_keys_deprecated(self, url: str) -> WalletKeyset: """ logger.warning(f"Using deprecated API call: {url}/keys") resp = await self.httpx.get( - url + "/keys", + f"{url}/keys", ) self.raise_on_error(resp) keys: dict = resp.json() @@ -185,7 +185,7 @@ async def _get_keyset_deprecated(self, url: str, keyset_id: str) -> WalletKeyset logger.warning(f"Using deprecated API call: {url}/keys/{keyset_id}") keyset_id_urlsafe = keyset_id.replace("+", "-").replace("/", "_") resp = await self.httpx.get( - url + f"/keys/{keyset_id_urlsafe}", + f"{url}/keys/{keyset_id_urlsafe}", ) self.raise_on_error(resp) keys = resp.json() @@ -217,7 +217,7 @@ async def _get_keysets_deprecated(self, url: str) -> List[KeysetsResponseKeyset] """ logger.warning(f"Using deprecated API call: {url}/keysets") resp = await self.httpx.get( - url + "/keysets", + f"{url}/keysets", ) self.raise_on_error(resp) keysets_dict = resp.json() @@ -244,7 +244,7 @@ async def request_mint_deprecated(self, amount) -> PostMintQuoteResponse: Exception: If the mint request fails """ logger.warning("Using deprecated API call: Requesting mint: GET /mint") - resp = await self.httpx.get(self.url + "/mint", params={"amount": amount}) + resp = await self.httpx.get(f"{self.url}/mint", params={"amount": amount}) self.raise_on_error(resp) return_dict = resp.json() mint_response = GetMintResponse_deprecated.parse_obj(return_dict) @@ -289,7 +289,7 @@ def _mintrequest_include_fields(outputs: List[BlindedMessage]): "Using deprecated API call:Checking Lightning invoice. POST /mint" ) resp = await self.httpx.post( - self.url + "/mint", + f"{self.url}/mint", json=payload, params={ "hash": hash, @@ -330,7 +330,7 @@ def _meltrequest_include_fields(proofs: List[Proof]): } resp = await self.httpx.post( - self.url + "/melt", + f"{self.url}/melt", json=payload.dict(include=_meltrequest_include_fields(proofs)), # type: ignore ) self.raise_on_error(resp) diff --git a/tests/test_db.py b/tests/test_db.py index 5d686630..fca93b6f 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -133,7 +133,7 @@ async def test_db_get_connection(ledger: Ledger): # ) # except Exception as exc: # # this is expected to raise -# raise Exception(f"conn2: {str(exc)}") +# raise Exception(f"conn2: {exc}") # except Exception as exc: # if str(exc).startswith("conn2"): @@ -174,12 +174,12 @@ async def get_connection(): ) except Exception as exc: # this is expected to raise - raise Exception(f"conn2: {str(exc)}") + raise Exception(f"conn2: {exc}") except Exception as exc: if "conn2" in str(exc): raise exc else: - raise Exception(f"not expected to happen: {str(exc)}") + raise Exception(f"not expected to happen: {exc}") await assert_err(get_connection(), "failed to acquire database lock") @@ -280,13 +280,13 @@ async def get_connection2(): except Exception as exc: # this is expected to raise - raise Exception(f"conn2: {str(exc)}") + raise Exception(f"conn2: {exc}") except Exception as exc: if "conn2" in str(exc): raise exc else: - raise Exception(f"not expected to happen: {str(exc)}") + raise Exception(f"not expected to happen: {exc}") await get_connection2() diff --git a/tests/test_wallet_htlc.py b/tests/test_wallet_htlc.py index 0a36ecd1..c1f75aaa 100644 --- a/tests/test_wallet_htlc.py +++ b/tests/test_wallet_htlc.py @@ -101,7 +101,7 @@ async def test_htlc_redeem_with_wrong_preimage(wallet1: Wallet, wallet2: Wallet) preimage = "00000000000000000000000000000000" # preimage_hash = hashlib.sha256(bytes.fromhex(preimage)).hexdigest() secret = await wallet1.create_htlc_lock( - preimage=preimage[:-5] + "11111" + preimage=f"{preimage[:-5]}11111" ) # wrong preimage _, send_proofs = await wallet1.swap_to_send(wallet1.proofs, 8, secret_lock=secret) for p in send_proofs: @@ -146,7 +146,7 @@ async def test_htlc_redeem_with_wrong_signature(wallet1: Wallet, wallet2: Wallet signatures = await wallet1.sign_p2pk_proofs(send_proofs) for p, s in zip(send_proofs, signatures): p.witness = HTLCWitness( - preimage=preimage, signature=s[:-5] + "11111" + preimage=preimage, signature=f"{s[:-5]}11111" ).json() # wrong signature await assert_err( @@ -231,7 +231,7 @@ async def test_htlc_redeem_hashlock_wrong_signature_timelock_wrong_signature( signatures = await wallet1.sign_p2pk_proofs(send_proofs) for p, s in zip(send_proofs, signatures): p.witness = HTLCWitness( - preimage=preimage, signature=s[:-5] + "11111" + preimage=preimage, signature=f"{s[:-5]}11111" ).json() # wrong signature # should error because we used wallet2 signatures for the hash lock diff --git a/tests/test_wallet_restore.py b/tests/test_wallet_restore.py index e245d492..0755db11 100644 --- a/tests/test_wallet_restore.py +++ b/tests/test_wallet_restore.py @@ -97,7 +97,7 @@ async def test_bump_secret_derivation(wallet3: Wallet): assert [r.private_key for r in rs1] == [r.private_key for r in rs2] assert derivation_paths1 == derivation_paths2 for s in secrets1: - print('"' + s + '",') + print(f'"{s}",') assert secrets1 == [ "485875df74771877439ac06339e284c3acfcd9be7abf3bc20b516faeadfe77ae", "8f2b39e8e594a4056eb1e6dbb4b0c38ef13b1b2c751f64f810ec04ee35b77270", @@ -114,7 +114,7 @@ async def test_bump_secret_derivation(wallet3: Wallet): ] for d in derivation_paths1: - print('"' + d + '",') + print(f'"{d}",') assert derivation_paths1 == [ "m/129372'/0'/864559728'/0'", "m/129372'/0'/864559728'/1'",