chore: modernize f-string usage (#627)

This commit is contained in:
Pavol Rusnak
2024-10-04 14:11:00 +02:00
committed by GitHub
parent 4d8b6a7a74
commit 75ffa39807
23 changed files with 54 additions and 59 deletions

View File

@@ -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)

View File

@@ -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]):

View File

@@ -10,7 +10,7 @@ class PublicKeyExt(PublicKey):
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 @@ class PublicKeyExt(PublicKey):
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 @@ class PublicKeyExt(PublicKey):
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

View File

@@ -85,7 +85,7 @@ class BlinkWallet(LightningBackend):
)
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 @@ class BlinkWallet(LightningBackend):
)
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 @@ class BlinkWallet(LightningBackend):
)
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 @@ class BlinkWallet(LightningBackend):
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 @@ class BlinkWallet(LightningBackend):
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)

View File

@@ -305,7 +305,7 @@ class LndRestWallet(LightningBackend):
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(

View File

@@ -89,7 +89,7 @@ INVOICE_RESULT_MAP = {
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"}

View File

@@ -306,7 +306,7 @@ class LedgerCrudSqlite(LedgerCrud):
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 @@ class LedgerCrudSqlite(LedgerCrud):
) -> 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 @@ class LedgerCrudSqlite(LedgerCrud):
) -> 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)

View File

@@ -905,7 +905,7 @@ class Ledger(LedgerVerification, LedgerSpendingConditions, LedgerTasks, LedgerFe
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 (

View File

@@ -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}")

View File

@@ -214,7 +214,7 @@ class LedgerVerification(
"""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(

View File

@@ -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):

View File

@@ -70,7 +70,7 @@ class Event:
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

View File

@@ -63,7 +63,7 @@ class PrivateKey:
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:

View File

@@ -65,7 +65,7 @@ class TorProxy:
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))

View File

@@ -232,7 +232,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
@@ -336,7 +336,7 @@ async def invoice(
# 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.")
@@ -389,7 +389,7 @@ async def invoice(
print(".", end="", flush=True)
continue
else:
print(f"Error: {str(e)}")
print(f"Error: {e}")
if not paid:
print("\n")
print(
@@ -1024,10 +1024,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("")

View File

@@ -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

View File

@@ -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 = {}

View File

@@ -170,10 +170,8 @@ class LedgerAPI(LedgerAPIDeprecated):
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 @@ class LedgerAPI(LedgerAPIDeprecated):
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,

View File

@@ -162,9 +162,8 @@ class Wallet(
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,9 @@ class Wallet(
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()])}"
)
keysets_str = ' '.join([f"{k.id} ({k.unit})" for k in self.keysets.values()])
logger.trace(f"Proofs loaded for keysets: {keysets_str}")
async def load_keysets_from_db(
self, url: Union[str, None] = "", unit: Union[str, None] = ""

View File

@@ -155,7 +155,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
"""
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 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
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 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
"""
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 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
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 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
"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 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
}
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)

View File

@@ -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 test_db_get_connection_lock_row(wallet: Wallet, 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 "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 test_db_get_connection_lock_different_row(wallet: Wallet, ledger: Ledg
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()

View File

@@ -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

View File

@@ -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'",