mirror of
https://github.com/aljazceru/nutshell.git
synced 2025-12-20 18:44:20 +01:00
chore: modernize f-string usage (#627)
This commit is contained in:
@@ -20,7 +20,7 @@ class AESCipher:
|
|||||||
|
|
||||||
def __init__(self, key: str, description=""):
|
def __init__(self, key: str, description=""):
|
||||||
self.key: str = key
|
self.key: str = key
|
||||||
self.description = description + " "
|
self.description = f"{description} "
|
||||||
|
|
||||||
def pad(self, data):
|
def pad(self, data):
|
||||||
length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
|
length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ def derive_keyset_id(keys: Dict[int, PublicKey]):
|
|||||||
# sort public keys by amount
|
# sort public keys by amount
|
||||||
sorted_keys = dict(sorted(keys.items()))
|
sorted_keys = dict(sorted(keys.items()))
|
||||||
pubkeys_concat = b"".join([p.serialize() for _, p in 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]):
|
def derive_keyset_id_deprecated(keys: Dict[int, PublicKey]):
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ class PublicKeyExt(PublicKey):
|
|||||||
new_pub.combine([self.public_key, pubkey2.public_key])
|
new_pub.combine([self.public_key, pubkey2.public_key])
|
||||||
return new_pub
|
return new_pub
|
||||||
else:
|
else:
|
||||||
raise TypeError("Cant add pubkey and %s" % pubkey2.__class__)
|
raise TypeError(f"Can't add pubkey and {pubkey2.__class__}")
|
||||||
|
|
||||||
def __neg__(self):
|
def __neg__(self):
|
||||||
serialized = self.serialize()
|
serialized = self.serialize()
|
||||||
@@ -23,7 +23,7 @@ class PublicKeyExt(PublicKey):
|
|||||||
if isinstance(pubkey2, PublicKey):
|
if isinstance(pubkey2, PublicKey):
|
||||||
return self + (-pubkey2) # type: ignore
|
return self + (-pubkey2) # type: ignore
|
||||||
else:
|
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):
|
def mult(self, privkey):
|
||||||
if isinstance(privkey, PrivateKey):
|
if isinstance(privkey, PrivateKey):
|
||||||
@@ -37,7 +37,7 @@ class PublicKeyExt(PublicKey):
|
|||||||
seq2 = pubkey2.to_data() # type: ignore
|
seq2 = pubkey2.to_data() # type: ignore
|
||||||
return seq1 == seq2
|
return seq1 == seq2
|
||||||
else:
|
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):
|
def to_data(self):
|
||||||
assert self.public_key
|
assert self.public_key
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ class BlinkWallet(LightningBackend):
|
|||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error(f"Blink API error: {str(exc)}")
|
logger.error(f"Blink API error: {exc}")
|
||||||
return StatusResponse(
|
return StatusResponse(
|
||||||
error_message=f"Failed to connect to {self.endpoint} due to: {exc}",
|
error_message=f"Failed to connect to {self.endpoint} due to: {exc}",
|
||||||
balance=0,
|
balance=0,
|
||||||
@@ -158,7 +158,7 @@ class BlinkWallet(LightningBackend):
|
|||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
except Exception as e:
|
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))
|
return InvoiceResponse(ok=False, error_message=str(e))
|
||||||
|
|
||||||
resp = r.json()
|
resp = r.json()
|
||||||
@@ -212,7 +212,7 @@ class BlinkWallet(LightningBackend):
|
|||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Blink API error: {str(e)}")
|
logger.error(f"Blink API error: {e}")
|
||||||
return PaymentResponse(
|
return PaymentResponse(
|
||||||
result=PaymentResult.UNKNOWN,
|
result=PaymentResult.UNKNOWN,
|
||||||
error_message=str(e),
|
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 = await self.client.post(url=self.endpoint, data=json.dumps(data)) # type: ignore
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
except Exception as e:
|
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))
|
return PaymentStatus(result=PaymentResult.UNKNOWN, error_message=str(e))
|
||||||
resp: dict = r.json()
|
resp: dict = r.json()
|
||||||
error_message = (
|
error_message = (
|
||||||
@@ -449,7 +449,7 @@ class BlinkWallet(LightningBackend):
|
|||||||
except httpx.ReadTimeout:
|
except httpx.ReadTimeout:
|
||||||
pass
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Blink API error: {str(e)}")
|
logger.error(f"Blink API error: {e}")
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
invoice_obj = decode(bolt11)
|
invoice_obj = decode(bolt11)
|
||||||
|
|||||||
@@ -305,7 +305,7 @@ class LndRestWallet(LightningBackend):
|
|||||||
try:
|
try:
|
||||||
data = r.json()
|
data = r.json()
|
||||||
except json.JSONDecodeError as e:
|
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))
|
return PaymentStatus(result=PaymentResult.UNKNOWN, error_message=str(e))
|
||||||
if not data or not data.get("state"):
|
if not data or not data.get("state"):
|
||||||
return PaymentStatus(
|
return PaymentStatus(
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ INVOICE_RESULT_MAP = {
|
|||||||
class StrikeWallet(LightningBackend):
|
class StrikeWallet(LightningBackend):
|
||||||
"""https://docs.strike.me/api/"""
|
"""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
|
supports_description: bool = False
|
||||||
currency_map = {Unit.sat: "BTC", Unit.usd: "USD", Unit.eur: "EUR"}
|
currency_map = {Unit.sat: "BTC", Unit.usd: "USD", Unit.eur: "EUR"}
|
||||||
|
|
||||||
|
|||||||
@@ -306,7 +306,7 @@ class LedgerCrudSqlite(LedgerCrud):
|
|||||||
rows = await (conn or db).fetchall(
|
rows = await (conn or db).fetchall(
|
||||||
f"""
|
f"""
|
||||||
SELECT * from {db.table_with_schema('promises')}
|
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))},
|
{f"b_{i}": b_s[i] for i in range(len(b_s))},
|
||||||
)
|
)
|
||||||
@@ -376,7 +376,7 @@ class LedgerCrudSqlite(LedgerCrud):
|
|||||||
) -> List[Proof]:
|
) -> List[Proof]:
|
||||||
query = f"""
|
query = f"""
|
||||||
SELECT * from {db.table_with_schema('proofs_pending')}
|
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))}
|
values = {f"y_{i}": Ys[i] for i in range(len(Ys))}
|
||||||
rows = await (conn or db).fetchall(query, values)
|
rows = await (conn or db).fetchall(query, values)
|
||||||
@@ -729,7 +729,7 @@ class LedgerCrudSqlite(LedgerCrud):
|
|||||||
) -> List[Proof]:
|
) -> List[Proof]:
|
||||||
query = f"""
|
query = f"""
|
||||||
SELECT * from {db.table_with_schema('proofs_used')}
|
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))}
|
values = {f"y_{i}": Ys[i] for i in range(len(Ys))}
|
||||||
rows = await (conn or db).fetchall(query, values)
|
rows = await (conn or db).fetchall(query, values)
|
||||||
|
|||||||
@@ -905,7 +905,7 @@ class Ledger(LedgerVerification, LedgerSpendingConditions, LedgerTasks, LedgerFe
|
|||||||
melt_quote, melt_quote.fee_reserve * 1000
|
melt_quote, melt_quote.fee_reserve * 1000
|
||||||
)
|
)
|
||||||
logger.debug(
|
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'}"
|
f" fee: {payment.fee.str() if payment.fee is not None else 'None'}"
|
||||||
)
|
)
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ async def rotate_keys(n_seconds=60):
|
|||||||
i += 1
|
i += 1
|
||||||
logger.info("Rotating keys.")
|
logger.info("Rotating keys.")
|
||||||
incremented_derivation_path = (
|
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)
|
await ledger.activate_keyset(derivation_path=incremented_derivation_path)
|
||||||
logger.info(f"Current keyset: {ledger.keyset.id}")
|
logger.info(f"Current keyset: {ledger.keyset.id}")
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ class LedgerVerification(
|
|||||||
"""Any amount used should be positive and not larger than 2^MAX_ORDER."""
|
"""Any amount used should be positive and not larger than 2^MAX_ORDER."""
|
||||||
valid = amount > 0 and amount < 2**settings.max_order
|
valid = amount > 0 and amount < 2**settings.max_order
|
||||||
if not valid:
|
if not valid:
|
||||||
raise NotAllowedError("invalid amount: " + str(amount))
|
raise NotAllowedError(f"invalid amount: {amount}")
|
||||||
return amount
|
return amount
|
||||||
|
|
||||||
def _verify_units_match(
|
def _verify_units_match(
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ def bech32_create_checksum(hrp, data, spec):
|
|||||||
def bech32_encode(hrp, data, spec):
|
def bech32_encode(hrp, data, spec):
|
||||||
"""Compute a Bech32 string given HRP and data values."""
|
"""Compute a Bech32 string given HRP and data values."""
|
||||||
combined = data + bech32_create_checksum(hrp, data, spec)
|
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):
|
def bech32_decode(bech):
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ class Event:
|
|||||||
|
|
||||||
def verify(self) -> bool:
|
def verify(self) -> bool:
|
||||||
pub_key = PublicKey(
|
pub_key = PublicKey(
|
||||||
bytes.fromhex("02" + self.public_key), True
|
bytes.fromhex(f"02{self.public_key}"), True
|
||||||
) # add 02 for schnorr (bip340)
|
) # add 02 for schnorr (bip340)
|
||||||
return pub_key.schnorr_verify(
|
return pub_key.schnorr_verify(
|
||||||
bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True
|
bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ class PrivateKey:
|
|||||||
return sk.tweak_add(scalar)
|
return sk.tweak_add(scalar)
|
||||||
|
|
||||||
def compute_shared_secret(self, public_key_hex: str) -> bytes:
|
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)
|
return pk.ecdh(self.raw_secret, hashfn=copy_x)
|
||||||
|
|
||||||
def encrypt_message(self, message: str, public_key_hex: str) -> str:
|
def encrypt_message(self, message: str, public_key_hex: str) -> str:
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ class TorProxy:
|
|||||||
stderr=subprocess.STDOUT,
|
stderr=subprocess.STDOUT,
|
||||||
start_new_session=True,
|
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:
|
with open(self.pid_file, "w", encoding="utf-8") as f:
|
||||||
f.write(str(self.tor_proc.pid))
|
f.write(str(self.tor_proc.pid))
|
||||||
|
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ async def pay(
|
|||||||
send_proofs, invoice, quote.fee_reserve, quote.quote
|
send_proofs, invoice, quote.fee_reserve, quote.quote
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" Error paying invoice: {str(e)}")
|
print(f" Error paying invoice: {e}")
|
||||||
return
|
return
|
||||||
if (
|
if (
|
||||||
melt_response.state
|
melt_response.state
|
||||||
@@ -336,7 +336,7 @@ async def invoice(
|
|||||||
# set paid so we won't react to any more callbacks
|
# set paid so we won't react to any more callbacks
|
||||||
paid = True
|
paid = True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error during mint: {str(e)}")
|
print(f"Error during mint: {e}")
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
logger.debug("Quote not paid yet.")
|
logger.debug("Quote not paid yet.")
|
||||||
@@ -389,7 +389,7 @@ async def invoice(
|
|||||||
print(".", end="", flush=True)
|
print(".", end="", flush=True)
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
print(f"Error: {str(e)}")
|
print(f"Error: {e}")
|
||||||
if not paid:
|
if not paid:
|
||||||
print("\n")
|
print("\n")
|
||||||
print(
|
print(
|
||||||
@@ -1024,10 +1024,8 @@ async def info(ctx: Context, mint: bool, mnemonic: bool):
|
|||||||
if mint_info.get("time"):
|
if mint_info.get("time"):
|
||||||
print(f" - Server time: {mint_info['time']}")
|
print(f" - Server time: {mint_info['time']}")
|
||||||
if mint_info.get("nuts"):
|
if mint_info.get("nuts"):
|
||||||
print(
|
nuts_str = ', '.join([f"NUT-{k}" for k in mint_info['nuts'].keys()])
|
||||||
" - Supported NUTS:"
|
print(f" - Supported NUTS: {nuts_str}")
|
||||||
f" {', '.join(['NUT-'+str(k) for k in mint_info['nuts'].keys()])}"
|
|
||||||
)
|
|
||||||
print("")
|
print("")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("")
|
print("")
|
||||||
|
|||||||
@@ -212,8 +212,8 @@ async def receive_all_pending(ctx: Context, wallet: Wallet):
|
|||||||
if mint_url and token_obj:
|
if mint_url and token_obj:
|
||||||
unit = Unit[token_obj.unit]
|
unit = Unit[token_obj.unit]
|
||||||
print(
|
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:
|
else:
|
||||||
print(f"Could not receive token: {str(e)}")
|
print(f"Could not receive token: {e}")
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ async def nip5_to_pubkey(wallet: Wallet, address: str):
|
|||||||
await wallet._init_s()
|
await wallet._init_s()
|
||||||
# if no username is given, use default _ (NIP-05 stuff)
|
# if no username is given, use default _ (NIP-05 stuff)
|
||||||
if "@" not in address:
|
if "@" not in address:
|
||||||
address = "_@" + address
|
address = f"_@{address}"
|
||||||
# now we can use it
|
# now we can use it
|
||||||
user, host = address.split("@")
|
user, host = address.split("@")
|
||||||
resp_dict = {}
|
resp_dict = {}
|
||||||
|
|||||||
@@ -170,10 +170,8 @@ class LedgerAPI(LedgerAPIDeprecated):
|
|||||||
keys_dict: dict = resp.json()
|
keys_dict: dict = resp.json()
|
||||||
assert len(keys_dict), Exception("did not receive any keys")
|
assert len(keys_dict), Exception("did not receive any keys")
|
||||||
keys = KeysResponse.parse_obj(keys_dict)
|
keys = KeysResponse.parse_obj(keys_dict)
|
||||||
logger.debug(
|
keysets_str = ' '.join([f"{k.id} ({k.unit})" for k in keys.keysets])
|
||||||
f"Received {len(keys.keysets)} keysets from mint:"
|
logger.debug(f"Received {len(keys.keysets)} keysets from mint: {keysets_str}.")
|
||||||
f" {' '.join([k.id + f' ({k.unit})' for k in keys.keysets])}."
|
|
||||||
)
|
|
||||||
ret = [
|
ret = [
|
||||||
WalletKeyset(
|
WalletKeyset(
|
||||||
id=keyset.id,
|
id=keyset.id,
|
||||||
@@ -388,7 +386,7 @@ class LedgerAPI(LedgerAPIDeprecated):
|
|||||||
ret: CheckFeesResponse_deprecated = await self.check_fees_deprecated(
|
ret: CheckFeesResponse_deprecated = await self.check_fees_deprecated(
|
||||||
payment_request
|
payment_request
|
||||||
)
|
)
|
||||||
quote_id = "deprecated_" + str(uuid.uuid4())
|
quote_id = f"deprecated_{uuid.uuid4()}"
|
||||||
return PostMeltQuoteResponse(
|
return PostMeltQuoteResponse(
|
||||||
quote=quote_id,
|
quote=quote_id,
|
||||||
amount=amount or invoice_obj.amount_msat // 1000,
|
amount=amount or invoice_obj.amount_msat // 1000,
|
||||||
|
|||||||
@@ -162,9 +162,8 @@ class Wallet(
|
|||||||
self.keysets = {k.id: k for k in keysets_active_unit}
|
self.keysets = {k.id: k for k in keysets_active_unit}
|
||||||
else:
|
else:
|
||||||
self.keysets = {k.id: k for k in keysets_list}
|
self.keysets = {k.id: k for k in keysets_list}
|
||||||
logger.debug(
|
keysets_str = ' '.join([f"{i} {k.unit}" for i, k in self.keysets.items()])
|
||||||
f"Loaded keysets: {' '.join([i + f' {k.unit}' for i, k in self.keysets.items()])}"
|
logger.debug(f"Loaded keysets: {keysets_str}")
|
||||||
)
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
async def _migrate_database(self):
|
async def _migrate_database(self):
|
||||||
@@ -349,9 +348,9 @@ class Wallet(
|
|||||||
for keyset_id in self.keysets:
|
for keyset_id in self.keysets:
|
||||||
proofs = await get_proofs(db=self.db, id=keyset_id, conn=conn)
|
proofs = await get_proofs(db=self.db, id=keyset_id, conn=conn)
|
||||||
self.proofs.extend(proofs)
|
self.proofs.extend(proofs)
|
||||||
logger.trace(
|
keysets_str = ' '.join([f"{k.id} ({k.unit})" for k in self.keysets.values()])
|
||||||
f"Proofs loaded for keysets: {' '.join([k.id + f' ({k.unit})' for k in self.keysets.values()])}"
|
logger.trace(f"Proofs loaded for keysets: {keysets_str}")
|
||||||
)
|
|
||||||
|
|
||||||
async def load_keysets_from_db(
|
async def load_keysets_from_db(
|
||||||
self, url: Union[str, None] = "", unit: Union[str, None] = ""
|
self, url: Union[str, None] = "", unit: Union[str, None] = ""
|
||||||
|
|||||||
@@ -155,7 +155,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
|
|||||||
"""
|
"""
|
||||||
logger.warning(f"Using deprecated API call: {url}/keys")
|
logger.warning(f"Using deprecated API call: {url}/keys")
|
||||||
resp = await self.httpx.get(
|
resp = await self.httpx.get(
|
||||||
url + "/keys",
|
f"{url}/keys",
|
||||||
)
|
)
|
||||||
self.raise_on_error(resp)
|
self.raise_on_error(resp)
|
||||||
keys: dict = resp.json()
|
keys: dict = resp.json()
|
||||||
@@ -185,7 +185,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
|
|||||||
logger.warning(f"Using deprecated API call: {url}/keys/{keyset_id}")
|
logger.warning(f"Using deprecated API call: {url}/keys/{keyset_id}")
|
||||||
keyset_id_urlsafe = keyset_id.replace("+", "-").replace("/", "_")
|
keyset_id_urlsafe = keyset_id.replace("+", "-").replace("/", "_")
|
||||||
resp = await self.httpx.get(
|
resp = await self.httpx.get(
|
||||||
url + f"/keys/{keyset_id_urlsafe}",
|
f"{url}/keys/{keyset_id_urlsafe}",
|
||||||
)
|
)
|
||||||
self.raise_on_error(resp)
|
self.raise_on_error(resp)
|
||||||
keys = resp.json()
|
keys = resp.json()
|
||||||
@@ -217,7 +217,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
|
|||||||
"""
|
"""
|
||||||
logger.warning(f"Using deprecated API call: {url}/keysets")
|
logger.warning(f"Using deprecated API call: {url}/keysets")
|
||||||
resp = await self.httpx.get(
|
resp = await self.httpx.get(
|
||||||
url + "/keysets",
|
f"{url}/keysets",
|
||||||
)
|
)
|
||||||
self.raise_on_error(resp)
|
self.raise_on_error(resp)
|
||||||
keysets_dict = resp.json()
|
keysets_dict = resp.json()
|
||||||
@@ -244,7 +244,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
|
|||||||
Exception: If the mint request fails
|
Exception: If the mint request fails
|
||||||
"""
|
"""
|
||||||
logger.warning("Using deprecated API call: Requesting mint: GET /mint")
|
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)
|
self.raise_on_error(resp)
|
||||||
return_dict = resp.json()
|
return_dict = resp.json()
|
||||||
mint_response = GetMintResponse_deprecated.parse_obj(return_dict)
|
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"
|
"Using deprecated API call:Checking Lightning invoice. POST /mint"
|
||||||
)
|
)
|
||||||
resp = await self.httpx.post(
|
resp = await self.httpx.post(
|
||||||
self.url + "/mint",
|
f"{self.url}/mint",
|
||||||
json=payload,
|
json=payload,
|
||||||
params={
|
params={
|
||||||
"hash": hash,
|
"hash": hash,
|
||||||
@@ -330,7 +330,7 @@ class LedgerAPIDeprecated(SupportsHttpxClient, SupportsMintURL):
|
|||||||
}
|
}
|
||||||
|
|
||||||
resp = await self.httpx.post(
|
resp = await self.httpx.post(
|
||||||
self.url + "/melt",
|
f"{self.url}/melt",
|
||||||
json=payload.dict(include=_meltrequest_include_fields(proofs)), # type: ignore
|
json=payload.dict(include=_meltrequest_include_fields(proofs)), # type: ignore
|
||||||
)
|
)
|
||||||
self.raise_on_error(resp)
|
self.raise_on_error(resp)
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ async def test_db_get_connection(ledger: Ledger):
|
|||||||
# )
|
# )
|
||||||
# except Exception as exc:
|
# except Exception as exc:
|
||||||
# # this is expected to raise
|
# # this is expected to raise
|
||||||
# raise Exception(f"conn2: {str(exc)}")
|
# raise Exception(f"conn2: {exc}")
|
||||||
|
|
||||||
# except Exception as exc:
|
# except Exception as exc:
|
||||||
# if str(exc).startswith("conn2"):
|
# 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:
|
except Exception as exc:
|
||||||
# this is expected to raise
|
# this is expected to raise
|
||||||
raise Exception(f"conn2: {str(exc)}")
|
raise Exception(f"conn2: {exc}")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
if "conn2" in str(exc):
|
if "conn2" in str(exc):
|
||||||
raise exc
|
raise exc
|
||||||
else:
|
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")
|
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:
|
except Exception as exc:
|
||||||
# this is expected to raise
|
# this is expected to raise
|
||||||
raise Exception(f"conn2: {str(exc)}")
|
raise Exception(f"conn2: {exc}")
|
||||||
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
if "conn2" in str(exc):
|
if "conn2" in str(exc):
|
||||||
raise exc
|
raise exc
|
||||||
else:
|
else:
|
||||||
raise Exception(f"not expected to happen: {str(exc)}")
|
raise Exception(f"not expected to happen: {exc}")
|
||||||
|
|
||||||
await get_connection2()
|
await get_connection2()
|
||||||
|
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ async def test_htlc_redeem_with_wrong_preimage(wallet1: Wallet, wallet2: Wallet)
|
|||||||
preimage = "00000000000000000000000000000000"
|
preimage = "00000000000000000000000000000000"
|
||||||
# preimage_hash = hashlib.sha256(bytes.fromhex(preimage)).hexdigest()
|
# preimage_hash = hashlib.sha256(bytes.fromhex(preimage)).hexdigest()
|
||||||
secret = await wallet1.create_htlc_lock(
|
secret = await wallet1.create_htlc_lock(
|
||||||
preimage=preimage[:-5] + "11111"
|
preimage=f"{preimage[:-5]}11111"
|
||||||
) # wrong preimage
|
) # wrong preimage
|
||||||
_, send_proofs = await wallet1.swap_to_send(wallet1.proofs, 8, secret_lock=secret)
|
_, send_proofs = await wallet1.swap_to_send(wallet1.proofs, 8, secret_lock=secret)
|
||||||
for p in send_proofs:
|
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)
|
signatures = await wallet1.sign_p2pk_proofs(send_proofs)
|
||||||
for p, s in zip(send_proofs, signatures):
|
for p, s in zip(send_proofs, signatures):
|
||||||
p.witness = HTLCWitness(
|
p.witness = HTLCWitness(
|
||||||
preimage=preimage, signature=s[:-5] + "11111"
|
preimage=preimage, signature=f"{s[:-5]}11111"
|
||||||
).json() # wrong signature
|
).json() # wrong signature
|
||||||
|
|
||||||
await assert_err(
|
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)
|
signatures = await wallet1.sign_p2pk_proofs(send_proofs)
|
||||||
for p, s in zip(send_proofs, signatures):
|
for p, s in zip(send_proofs, signatures):
|
||||||
p.witness = HTLCWitness(
|
p.witness = HTLCWitness(
|
||||||
preimage=preimage, signature=s[:-5] + "11111"
|
preimage=preimage, signature=f"{s[:-5]}11111"
|
||||||
).json() # wrong signature
|
).json() # wrong signature
|
||||||
|
|
||||||
# should error because we used wallet2 signatures for the hash lock
|
# should error because we used wallet2 signatures for the hash lock
|
||||||
|
|||||||
@@ -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 [r.private_key for r in rs1] == [r.private_key for r in rs2]
|
||||||
assert derivation_paths1 == derivation_paths2
|
assert derivation_paths1 == derivation_paths2
|
||||||
for s in secrets1:
|
for s in secrets1:
|
||||||
print('"' + s + '",')
|
print(f'"{s}",')
|
||||||
assert secrets1 == [
|
assert secrets1 == [
|
||||||
"485875df74771877439ac06339e284c3acfcd9be7abf3bc20b516faeadfe77ae",
|
"485875df74771877439ac06339e284c3acfcd9be7abf3bc20b516faeadfe77ae",
|
||||||
"8f2b39e8e594a4056eb1e6dbb4b0c38ef13b1b2c751f64f810ec04ee35b77270",
|
"8f2b39e8e594a4056eb1e6dbb4b0c38ef13b1b2c751f64f810ec04ee35b77270",
|
||||||
@@ -114,7 +114,7 @@ async def test_bump_secret_derivation(wallet3: Wallet):
|
|||||||
]
|
]
|
||||||
|
|
||||||
for d in derivation_paths1:
|
for d in derivation_paths1:
|
||||||
print('"' + d + '",')
|
print(f'"{d}",')
|
||||||
assert derivation_paths1 == [
|
assert derivation_paths1 == [
|
||||||
"m/129372'/0'/864559728'/0'",
|
"m/129372'/0'/864559728'/0'",
|
||||||
"m/129372'/0'/864559728'/1'",
|
"m/129372'/0'/864559728'/1'",
|
||||||
|
|||||||
Reference in New Issue
Block a user