Skip to content

Commit

Permalink
reformat to 88 chars line-length
Browse files Browse the repository at this point in the history
  • Loading branch information
dni committed Aug 17, 2023
1 parent 664bf36 commit 03bd4fe
Show file tree
Hide file tree
Showing 20 changed files with 247 additions and 193 deletions.
37 changes: 21 additions & 16 deletions cashu/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ class SecretKind:


class SigFlags:
SIG_INPUTS = (
"SIG_INPUTS" # require signatures only on the inputs (default signature flag)
SIG_INPUTS = ( # require signatures only on the inputs (default signature flag)
"SIG_INPUTS"
)
SIG_ALL = "SIG_ALL" # require signatures on inputs and outputs

Expand Down Expand Up @@ -161,18 +161,20 @@ class Proof(BaseModel):

id: Union[
None, str
] = "" # NOTE: None for backwards compatibility for old clients that do not include the keyset id < 0.3
] = ( # NOTE: None for backwards compatibility for old clients that do not include the keyset id < 0.3
""
)
amount: int = 0
secret: str = "" # secret or message to be blinded and signed
C: str = "" # signature on secret, unblinded by wallet
p2pksigs: Union[List[str], None] = [] # P2PK signature
p2shscript: Union[P2SHScript, None] = None # P2SH spending condition
reserved: Union[
None, bool
] = False # whether this proof is reserved for sending, used for coin management in the wallet
send_id: Union[
None, str
] = "" # unique ID of send attempt, used for grouping pending tokens in the wallet
reserved: Union[None, bool] = (
False # whether this proof is reserved for sending, used for coin management in the wallet
)
send_id: Union[None, str] = (
"" # unique ID of send attempt, used for grouping pending tokens in the wallet
)
time_created: Union[None, str] = ""
time_reserved: Union[None, str] = ""
derivation_path: Union[None, str] = "" # derivation path of the proof
Expand Down Expand Up @@ -338,9 +340,9 @@ class CheckSpendableRequest(BaseModel):

class CheckSpendableResponse(BaseModel):
spendable: List[bool]
pending: Optional[
List[bool]
] = None # TODO: Uncomment when all mints are updated to 0.12.3 and support /check
pending: Optional[List[bool]] = (
None # TODO: Uncomment when all mints are updated to 0.12.3 and support /check
)
# with pending tokens (kept for backwards compatibility of new wallets with old mints)


Expand Down Expand Up @@ -421,9 +423,11 @@ def deserialize(serialized: str):

return cls(
id=row["id"],
public_keys=deserialize(str(row["public_keys"]))
if dict(row).get("public_keys")
else {},
public_keys=(
deserialize(str(row["public_keys"]))
if dict(row).get("public_keys")
else {}
),
mint_url=row["mint_url"],
valid_from=row["valid_from"],
valid_to=row["valid_to"],
Expand Down Expand Up @@ -489,7 +493,8 @@ def generate_keys(self, seed):
self.id = derive_keyset_id(self.public_keys) # type: ignore
if backwards_compatibility_pre_0_12:
logger.warning(
f"WARNING: Using weak key derivation for keyset {self.id} (backwards compatibility < 0.12)"
f"WARNING: Using weak key derivation for keyset {self.id} (backwards"
" compatibility < 0.12)"
)


Expand Down
1 change: 0 additions & 1 deletion cashu/core/bolt11.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ def lnencode(addr, privkey):
tags_set = set()

for k, v in addr.tags:

# BOLT #11:
#
# A writer MUST NOT include more than one `d`, `h`, `n` or `x` fields,
Expand Down
6 changes: 3 additions & 3 deletions cashu/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ def _parse_timestamp(value, _):
psycopg2.extensions.new_type( # type: ignore
(1082, 1083, 1266),
"DATE2INT",
lambda value, curs: time.mktime(value.timetuple())
if value is not None
else None,
lambda value, curs: (
time.mktime(value.timetuple()) if value is not None else None
),
)
)

Expand Down
6 changes: 4 additions & 2 deletions cashu/core/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ async def run_migration(db, migrations_module):
exists = None
if conn.type == SQLITE:
exists = await conn.fetchone(
f"SELECT * FROM sqlite_master WHERE type='table' AND name='{table_with_schema(db, 'dbversions')}'"
"SELECT * FROM sqlite_master WHERE type='table' AND"
f" name='{table_with_schema(db, 'dbversions')}'"
)
elif conn.type in {POSTGRES, COCKROACH}:
exists = await conn.fetchone(
f"SELECT * FROM information_schema.tables WHERE table_name = '{table_with_schema(db, 'dbversions')}'"
"SELECT * FROM information_schema.tables WHERE table_name ="
f" '{table_with_schema(db, 'dbversions')}'"
)

if not exists:
Expand Down
6 changes: 4 additions & 2 deletions cashu/core/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ def verify_bitcoin_script(txin_redeemScript_b64, txin_signature_b64):
txin_redeemScript_b64 = base64.urlsafe_b64encode(txin_redeemScript).decode()
txin_signature_b64 = base64.urlsafe_b64encode(txin_signature).decode()
print(
f"Carol to Bob:\nscript: {txin_redeemScript.__repr__()}\nscript: {txin_redeemScript_b64}\nsignature: {txin_signature_b64}\n"
f"Carol to Bob:\nscript: {txin_redeemScript.__repr__()}\nscript:"
f" {txin_redeemScript_b64}\nsignature: {txin_signature_b64}\n"
)
print("")
# ---------
Expand All @@ -155,7 +156,8 @@ def verify_bitcoin_script(txin_redeemScript_b64, txin_signature_b64):
tx, _ = step1_bob_carol_create_tx(txin_p2sh_address)

print(
f"Bob verifies:\nscript: {txin_redeemScript_b64}\nsignature: {txin_signature_b64}\n"
f"Bob verifies:\nscript: {txin_redeemScript_b64}\nsignature:"
f" {txin_signature_b64}\n"
)
script_valid = step3_bob_verify_script(txin_signature, txin_redeemScript, tx)
# MINT redeems tokens and stores P2SH:txin_p2sh_address
Expand Down
11 changes: 8 additions & 3 deletions cashu/mint/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,16 @@ def configure_logger() -> None:
class Formatter:
def __init__(self):
self.padding = 0
self.minimal_fmt: str = "<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | <level>{level}</level> | <level>{message}</level>\n"
self.minimal_fmt: str = (
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> |"
" <level>{level}</level> | <level>{message}</level>\n"
)
if settings.debug:
self.fmt: str = (
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | <level>{level: <4}</level> | <cyan>{name}</cyan>:<cyan>"
"{function}</cyan>:<cyan>{line}</cyan> | <level>{message}</level>\n"
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | <level>{level:"
" <4}</level> |"
" <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>"
" | <level>{message}</level>\n"
)
else:
self.fmt: str = self.minimal_fmt
Expand Down
12 changes: 4 additions & 8 deletions cashu/mint/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,9 @@ async def get_proofs_used(
db: Database,
conn: Optional[Connection] = None,
):
rows = await (conn or db).fetchall(
f"""
rows = await (conn or db).fetchall(f"""
SELECT secret from {table_with_schema(db, 'proofs_used')}
"""
)
""")
return [row[0] for row in rows]


Expand Down Expand Up @@ -123,11 +121,9 @@ async def get_proofs_pending(
db: Database,
conn: Optional[Connection] = None,
):
rows = await (conn or db).fetchall(
f"""
rows = await (conn or db).fetchall(f"""
SELECT * from {table_with_schema(db, 'proofs_pending')}
"""
)
""")
return [Proof(**r) for r in rows]


Expand Down
58 changes: 36 additions & 22 deletions cashu/mint/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,10 @@ def _verify_input_spending_conditions(self, proof: Proof) -> bool:
if not valid:
raise TransactionError("script invalid.")
# check if secret commits to script address
assert secret.data == str(
txin_p2sh_address
), f"secret does not contain correct P2SH address: {secret.data} is not {txin_p2sh_address}."
assert secret.data == str(txin_p2sh_address), (
f"secret does not contain correct P2SH address: {secret.data} is not"
f" {txin_p2sh_address}."
)
return True

# P2PK
Expand Down Expand Up @@ -310,9 +311,10 @@ def _verify_input_spending_conditions(self, proof: Proof) -> bool:
assert n_sigs_required > 0, "n_sigs must be positive."

# check if enough signatures are present
assert (
len(proof.p2pksigs) >= n_sigs_required
), f"not enough signatures provided: {len(proof.p2pksigs)} < {n_sigs_required}."
assert len(proof.p2pksigs) >= n_sigs_required, (
f"not enough signatures provided: {len(proof.p2pksigs)} <"
f" {n_sigs_required}."
)

n_valid_sigs_per_output = 0
# loop over all signatures in output
Expand All @@ -327,20 +329,24 @@ def _verify_input_spending_conditions(self, proof: Proof) -> bool:
):
n_valid_sigs_per_output += 1
logger.trace(
f"p2pk signature on input is valid: {input_sig} on {pubkey}."
f"p2pk signature on input is valid: {input_sig} on"
f" {pubkey}."
)
continue
else:
logger.trace(
f"p2pk signature on input is invalid: {input_sig} on {pubkey}."
f"p2pk signature on input is invalid: {input_sig} on"
f" {pubkey}."
)
# check if we have enough valid signatures
assert n_valid_sigs_per_output, "no valid signature provided for input."
assert (
n_valid_sigs_per_output >= n_sigs_required
), f"signature threshold not met. {n_valid_sigs_per_output} < {n_sigs_required}."
assert n_valid_sigs_per_output >= n_sigs_required, (
f"signature threshold not met. {n_valid_sigs_per_output} <"
f" {n_sigs_required}."
)
logger.trace(
f"{n_valid_sigs_per_output} of {n_sigs_required} valid signatures found."
f"{n_valid_sigs_per_output} of {n_sigs_required} valid signatures"
" found."
)

logger.trace(proof.p2pksigs)
Expand Down Expand Up @@ -424,11 +430,13 @@ def _verify_output_spending_conditions(
):
n_valid_sigs_per_output += 1
assert n_valid_sigs_per_output, "no valid signature provided for output."
assert (
n_valid_sigs_per_output >= n_sigs_required
), f"signature threshold not met. {n_valid_sigs_per_output} < {n_sigs_required}."
assert n_valid_sigs_per_output >= n_sigs_required, (
f"signature threshold not met. {n_valid_sigs_per_output} <"
f" {n_sigs_required}."
)
logger.trace(
f"{n_valid_sigs_per_output} of {n_sigs_required} valid signatures found."
f"{n_valid_sigs_per_output} of {n_sigs_required} valid signatures"
" found."
)
logger.trace(output.p2pksigs)
logger.trace("p2pk signatures on output is valid.")
Expand Down Expand Up @@ -492,7 +500,8 @@ async def _request_lightning_invoice(self, amount: int):
Tuple[str, str]: Bolt11 invoice and payment hash (for lookup)
"""
logger.trace(
f"_request_lightning_invoice: Requesting Lightning invoice for {amount} satoshis."
"_request_lightning_invoice: Requesting Lightning invoice for"
f" {amount} satoshis."
)
error, balance = await self.lightning.status()
logger.trace(f"_request_lightning_invoice: Lightning wallet balance: {balance}")
Expand Down Expand Up @@ -549,14 +558,16 @@ async def _check_lightning_invoice(
try:
if amount > invoice.amount:
raise LightningError(
f"requested amount too high: {amount}. Invoice amount: {invoice.amount}"
f"requested amount too high: {amount}. Invoice amount:"
f" {invoice.amount}"
)
logger.trace(
f"_check_lightning_invoice: checking invoice {invoice.payment_hash}"
)
status = await self.lightning.get_invoice_status(invoice.payment_hash)
logger.trace(
f"_check_lightning_invoice: invoice {invoice.payment_hash} status: {status}"
f"_check_lightning_invoice: invoice {invoice.payment_hash} status:"
f" {status}"
)
if status.paid:
return status.paid
Expand Down Expand Up @@ -658,7 +669,8 @@ async def _unset_proofs_pending(
try:
for p in proofs:
logger.trace(
f"crud: _unset_proofs_pending unsetting proof {p.secret} as pending"
f"crud: _unset_proofs_pending unsetting proof {p.secret} as"
" pending"
)
await self.crud.unset_proof_pending(proof=p, db=self.db, conn=conn)
logger.trace(
Expand Down Expand Up @@ -1005,7 +1017,8 @@ async def check_fees(self, pr: str):
decoded_invoice = bolt11.decode(pr)
amount = math.ceil(decoded_invoice.amount_msat / 1000)
logger.trace(
f"check_fees: checking lightning invoice: {decoded_invoice.payment_hash}"
"check_fees: checking lightning invoice:"
f" {decoded_invoice.payment_hash}"
)
paid = await self.lightning.get_invoice_status(decoded_invoice.payment_hash)
logger.trace(f"check_fees: paid: {paid}")
Expand Down Expand Up @@ -1071,7 +1084,8 @@ async def split(
# BEGIN backwards compatibility < 0.13.0
if amount is not None:
logger.debug(
"Split: Client provided `amount` - backwards compatibility response pre 0.13.0"
"Split: Client provided `amount` - backwards compatibility response pre"
" 0.13.0"
)
# split outputs according to amount
total = sum_proofs(proofs)
Expand Down
Loading

0 comments on commit 03bd4fe

Please sign in to comment.