From 6838b0be0527a2fb4d032f0063097dbf892e66d7 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Tue, 11 Oct 2022 00:41:55 +0200 Subject: [PATCH] mypy --- cashu/core/base.py | 9 ++++----- cashu/core/crypto.py | 2 +- cashu/core/settings.py | 4 ++-- cashu/lightning/lnbits.py | 41 ++++++++++++++++++--------------------- cashu/mint/crud.py | 10 +++++----- cashu/mint/router.py | 10 ++++------ cashu/wallet/__init__.py | 2 +- cashu/wallet/crud.py | 12 ++++++------ tests/test_wallet.py | 8 +++----- 9 files changed, 45 insertions(+), 53 deletions(-) diff --git a/cashu/core/base.py b/cashu/core/base.py index 2c7a31d..99ec2a4 100644 --- a/cashu/core/base.py +++ b/cashu/core/base.py @@ -166,7 +166,6 @@ class CheckFeesResponse(BaseModel): class MeltRequest(BaseModel): proofs: List[Proof] - amount: int = None # deprecated invoice: str @@ -233,7 +232,7 @@ class MintKeyset: id: str derivation_path: str private_keys: Dict[int, PrivateKey] - public_keys: Dict[int, PublicKey] = None + public_keys: Dict[int, PublicKey] = {} valid_from: Union[str, None] = None valid_to: Union[str, None] = None first_seen: Union[str, None] = None @@ -247,9 +246,9 @@ class MintKeyset: valid_to=None, first_seen=None, active=None, - seed: Union[None, str] = None, - derivation_path: str = None, - version: str = None, + seed: str = "", + derivation_path: str = "", + version: str = "", ): self.derivation_path = derivation_path self.id = id diff --git a/cashu/core/crypto.py b/cashu/core/crypto.py index 6cad72b..1563d94 100644 --- a/cashu/core/crypto.py +++ b/cashu/core/crypto.py @@ -27,7 +27,7 @@ def derive_pubkeys(keys: Dict[int, PrivateKey]): return {amt: keys[amt].pubkey for amt in [2**i for i in range(MAX_ORDER)]} -def derive_keyset_id(keys: Dict[str, PublicKey]): +def derive_keyset_id(keys: Dict[int, PublicKey]): """Deterministic derivation keyset_id from set of public keys.""" pubkeys_concat = "".join([p.serialize().hex() for _, p in keys.items()]) return base64.b64encode( diff --git a/cashu/core/settings.py b/cashu/core/settings.py index 30f2270..7c92601 100644 --- a/cashu/core/settings.py +++ b/cashu/core/settings.py @@ -7,13 +7,13 @@ from environs import Env # type: ignore env = Env() -ENV_FILE: Union[str, None] = os.path.join(str(Path.home()), ".cashu", ".env") +ENV_FILE = os.path.join(str(Path.home()), ".cashu", ".env") if not os.path.isfile(ENV_FILE): ENV_FILE = os.path.join(os.getcwd(), ".env") if os.path.isfile(ENV_FILE): env.read_env(ENV_FILE) else: - ENV_FILE = None + ENV_FILE = "" env.read_env() DEBUG = env.bool("DEBUG", default=False) diff --git a/cashu/lightning/lnbits.py b/cashu/lightning/lnbits.py index 97f8907..c422d10 100644 --- a/cashu/lightning/lnbits.py +++ b/cashu/lightning/lnbits.py @@ -1,8 +1,5 @@ -import asyncio -import hashlib -import json from os import getenv -from typing import AsyncGenerator, Dict, Optional +from typing import Dict, Optional import requests @@ -133,26 +130,26 @@ class LNbitsWallet(Wallet): return PaymentStatus(data["paid"], data["details"]["fee"], data["preimage"]) - async def paid_invoices_stream(self) -> AsyncGenerator[str, None]: - url = f"{self.endpoint}/api/v1/payments/sse" + # async def paid_invoices_stream(self) -> AsyncGenerator[str, None]: + # url = f"{self.endpoint}/api/v1/payments/sse" - while True: - try: - async with requests.stream("GET", url) as r: - async for line in r.aiter_lines(): - if line.startswith("data:"): - try: - data = json.loads(line[5:]) - except json.decoder.JSONDecodeError: - continue + # while True: + # try: + # async with requests.stream("GET", url) as r: + # async for line in r.aiter_lines(): + # if line.startswith("data:"): + # try: + # data = json.loads(line[5:]) + # except json.decoder.JSONDecodeError: + # continue - if type(data) is not dict: - continue + # if type(data) is not dict: + # continue - yield data["payment_hash"] # payment_hash + # yield data["payment_hash"] # payment_hash - except: - pass + # except: + # pass - print("lost connection to lnbits /payments/sse, retrying in 5 seconds") - await asyncio.sleep(5) + # print("lost connection to lnbits /payments/sse, retrying in 5 seconds") + # await asyncio.sleep(5) diff --git a/cashu/mint/crud.py b/cashu/mint/crud.py index fbb3bf3..3d4c99d 100644 --- a/cashu/mint/crud.py +++ b/cashu/mint/crud.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, List, Any from cashu.core.base import Invoice, MintKeyset, Proof from cashu.core.db import Connection, Database @@ -118,7 +118,7 @@ async def store_keyset( conn: Optional[Connection] = None, ): - await (conn or db).execute( + await (conn or db).execute( # type: ignore """ INSERT INTO keysets (id, derivation_path, valid_from, valid_to, first_seen, active, version) @@ -138,12 +138,12 @@ async def store_keyset( async def get_keyset( id: str = None, - derivation_path: str = None, + derivation_path: str = "", db: Database = None, conn: Optional[Connection] = None, ): clauses = [] - values = [] + values: List[Any] = [] clauses.append("active = ?") values.append(True) if id: @@ -156,7 +156,7 @@ async def get_keyset( if clauses: where = f"WHERE {' AND '.join(clauses)}" - rows = await (conn or db).fetchall( + rows = await (conn or db).fetchall( # type: ignore f""" SELECT * from keysets {where} diff --git a/cashu/mint/router.py b/cashu/mint/router.py index db64ea0..084d1f0 100644 --- a/cashu/mint/router.py +++ b/cashu/mint/router.py @@ -20,10 +20,6 @@ from cashu.mint import ledger router: APIRouter = APIRouter() -from starlette.requests import Request -from starlette_context import context - - @router.get("/keys") def keys(): """Get the public keys of the mint""" @@ -73,7 +69,7 @@ async def mint( @router.post("/melt") -async def melt(request: Request, payload: MeltRequest): +async def melt(payload: MeltRequest): """ Requests tokens to be destroyed and sent out via Lightning. """ @@ -100,7 +96,7 @@ async def check_fees(payload: CheckFeesRequest): @router.post("/split") -async def split(request: Request, payload: SplitRequest): +async def split(payload: SplitRequest): """ Requetst a set of tokens with amount "total" to be split into two newly minted sets with amount "split" and "total-split". @@ -108,6 +104,8 @@ async def split(request: Request, payload: SplitRequest): proofs = payload.proofs amount = payload.amount outputs = payload.outputs.blinded_messages if payload.outputs else None + # backwards compatibility with clients < v0.2.2 + assert outputs, Exception("no outputs provided.") try: split_return = await ledger.split(proofs, amount, outputs) except Exception as exc: diff --git a/cashu/wallet/__init__.py b/cashu/wallet/__init__.py index bf11b51..b4cdb6a 100644 --- a/cashu/wallet/__init__.py +++ b/cashu/wallet/__init__.py @@ -1,3 +1,3 @@ import sys -sys.tracebacklimit = None +sys.tracebacklimit = None # type: ignore diff --git a/cashu/wallet/crud.py b/cashu/wallet/crud.py index 12d8401..d6f8c47 100644 --- a/cashu/wallet/crud.py +++ b/cashu/wallet/crud.py @@ -93,7 +93,7 @@ async def update_proof_reserved( clauses.append("time_reserved = ?") values.append(int(time.time())) - await (conn or db).execute( + await (conn or db).execute( # type: ignore f"UPDATE proofs SET {', '.join(clauses)} WHERE secret = ?", (*values, str(proof.secret)), ) @@ -155,7 +155,7 @@ async def get_unused_locks( if clause: where = f"WHERE {' AND '.join(clause)}" - rows = await (conn or db).fetchall( + rows = await (conn or db).fetchall( # type: ignore f""" SELECT * from p2sh {where} @@ -176,7 +176,7 @@ async def update_p2sh_used( clauses.append("used = ?") values.append(used) - await (conn or db).execute( + await (conn or db).execute( # type: ignore f"UPDATE proofs SET {', '.join(clauses)} WHERE address = ?", (*values, str(p2sh.address)), ) @@ -189,7 +189,7 @@ async def store_keyset( conn: Optional[Connection] = None, ): - await (conn or db).execute( + await (conn or db).execute( # type: ignore """ INSERT INTO keysets (id, mint_url, valid_from, valid_to, first_seen, active) @@ -213,7 +213,7 @@ async def get_keyset( conn: Optional[Connection] = None, ): clauses = [] - values = [] + values: List[Any] = [] clauses.append("active = ?") values.append(True) if id: @@ -226,7 +226,7 @@ async def get_keyset( if clauses: where = f"WHERE {' AND '.join(clauses)}" - row = await (conn or db).fetchone( + row = await (conn or db).fetchone( # type: ignore f""" SELECT * from keysets {where} diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 300896b..74ac8ff 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -1,11 +1,9 @@ import time -from distutils.command.build_scripts import first_line_re -from re import S -from typing import List import pytest import pytest_asyncio +from typing import List from cashu.core.base import Proof from cashu.core.helpers import async_unwrap, sum_proofs from cashu.core.migrations import migrate_databases @@ -27,9 +25,9 @@ async def assert_err(f, msg): ) -def assert_amt(proofs, expected): +def assert_amt(proofs: List[Proof], expected: int): """Assert amounts the proofs contain.""" - assert [p["amount"] for p in proofs] == expected + assert [p.amount for p in proofs] == expected @pytest_asyncio.fixture(scope="function")