Skip to content

Commit

Permalink
chore: modernize f-string usage
Browse files Browse the repository at this point in the history
  • Loading branch information
prusnak committed Sep 29, 2024
1 parent d8d3037 commit 8773688
Show file tree
Hide file tree
Showing 23 changed files with 53 additions and 59 deletions.
2 changes: 1 addition & 1 deletion cashu/core/crypto/aes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cashu/core/crypto/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]):
Expand Down
6 changes: 3 additions & 3 deletions cashu/core/crypto/secp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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):
Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions cashu/lightning/blink.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cashu/lightning/lndrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion cashu/lightning/strike.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down
6 changes: 3 additions & 3 deletions cashu/mint/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))},
)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cashu/mint/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 1 addition & 1 deletion cashu/mint/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
2 changes: 1 addition & 1 deletion cashu/mint/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion cashu/nostr/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion cashu/nostr/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cashu/nostr/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion cashu/tor/tor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
12 changes: 5 additions & 7 deletions cashu/wallet/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.")
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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("")
Expand Down
4 changes: 2 additions & 2 deletions cashu/wallet/cli/cli_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion cashu/wallet/nostr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand Down
8 changes: 3 additions & 5 deletions cashu/wallet/v1_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 4 additions & 6 deletions cashu/wallet/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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] = ""
Expand Down
12 changes: 6 additions & 6 deletions cashu/wallet/wallet_deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 5 additions & 5 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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()

Expand Down
Loading

0 comments on commit 8773688

Please sign in to comment.