Skip to content

Commit

Permalink
Merge branch 'main' into postgres_compat_latest
Browse files Browse the repository at this point in the history
  • Loading branch information
trbouma committed Nov 29, 2023
2 parents f091faf + fa5193c commit ff1824d
Show file tree
Hide file tree
Showing 18 changed files with 341 additions and 173 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
python-version: ["3.9", "3.10"]
python-version: ["3.10"]
poetry-version: ["1.5.1"]
mint-cache-secrets: ["true", "false"]
# db-url: ["", "postgres://cashu:cashu@localhost:5432/test"] # TODO: Postgres test not working
db-url: [""]
backend-wallet-class: ["FakeWallet"]
uses: ./.github/workflows/tests.yml
with:
python-version: ${{ matrix.python-version }}
poetry-version: ${{ matrix.poetry-version }}
mint-cache-secrets: ${{ matrix.mint-cache-secrets }}
regtest:
uses: ./.github/workflows/regtest.yml
strategy:
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ on:
os:
default: "ubuntu-latest"
type: string
mint-cache-secrets:
default: "false"
type: string

jobs:
poetry:
Expand Down Expand Up @@ -47,6 +50,7 @@ jobs:
MINT_HOST: localhost
MINT_PORT: 3337
MINT_DATABASE: ${{ inputs.db-url }}
MINT_CACHE_SECRETS: ${{ inputs.mint-cache-secrets }}
TOR: false
run: |
make test
Expand Down
9 changes: 7 additions & 2 deletions cashu/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,11 @@ def __init__(
self.public_keys = public_keys
# overwrite id by deriving it from the public keys
self.id = derive_keyset_id(self.public_keys)
logger.trace(f"Derived keyset id {self.id} from public keys.")
if id and id != self.id:
logger.warning(
f"WARNING: Keyset id {self.id} does not match the given id {id}."
)

def serialize(self):
return json.dumps(
Expand All @@ -356,9 +361,9 @@ def serialize(self):

@classmethod
def from_row(cls, row: Row):
def deserialize(serialized: str):
def deserialize(serialized: str) -> Dict[int, PublicKey]:
return {
amount: PublicKey(bytes.fromhex(hex_key), raw=True)
int(amount): PublicKey(bytes.fromhex(hex_key), raw=True)
for amount, hex_key in dict(json.loads(serialized)).items()
}

Expand Down
3 changes: 2 additions & 1 deletion cashu/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from contextlib import asynccontextmanager
from typing import Optional, Union

from loguru import logger
from sqlalchemy import create_engine
from sqlalchemy_aio.base import AsyncConnection
from sqlalchemy_aio.strategy import ASYNCIO_STRATEGY # type: ignore
Expand Down Expand Up @@ -130,7 +131,7 @@ def _parse_timestamp(value, _):
# )
else:
if not os.path.exists(self.db_location):
print(f"Creating database directory: {self.db_location}")
logger.info(f"Creating database directory: {self.db_location}")
os.makedirs(self.db_location)
self.path = os.path.join(self.db_location, f"{self.name}.sqlite3")
database_uri = f"sqlite:///{self.path}"
Expand Down
4 changes: 4 additions & 0 deletions cashu/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class EnvSettings(CashuSettings):
debug: bool = Field(default=False)
log_level: str = Field(default="INFO")
cashu_dir: str = Field(default=os.path.join(str(Path.home()), ".cashu"))
debug_profiling: bool = Field(default=False)


class MintSettings(CashuSettings):
Expand All @@ -56,10 +57,13 @@ class MintSettings(CashuSettings):
mint_peg_out_only: bool = Field(default=False)
mint_max_peg_in: int = Field(default=None)
mint_max_peg_out: int = Field(default=None)
mint_max_balance: int = Field(default=None)

mint_lnbits_endpoint: str = Field(default=None)
mint_lnbits_key: str = Field(default=None)

mint_cache_secrets: bool = Field(default=True)


class MintInformation(CashuSettings):
mint_info_name: str = Field(default="Cashu mint")
Expand Down
9 changes: 6 additions & 3 deletions cashu/mint/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
)
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

# from fastapi_profiler import PyInstrumentProfilerMiddleware
from loguru import logger
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
Expand All @@ -20,6 +18,9 @@
from .router import router
from .startup import start_mint_init

if settings.debug_profiling:
from fastapi_profiler import PyInstrumentProfilerMiddleware

# from starlette_context import context
# from starlette_context.middleware import RawContextMiddleware

Expand Down Expand Up @@ -108,7 +109,9 @@ def emit(self, record):
middleware=middleware,
)

# app.add_middleware(PyInstrumentProfilerMiddleware)
if settings.debug_profiling:
assert PyInstrumentProfilerMiddleware is not None
app.add_middleware(PyInstrumentProfilerMiddleware)

return app

Expand Down
59 changes: 55 additions & 4 deletions cashu/mint/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async def get_lightning_invoice(
db: Database,
id: str,
conn: Optional[Connection] = None,
):
) -> Optional[Invoice]:
return await get_lightning_invoice(
db=db,
id=id,
Expand All @@ -42,8 +42,23 @@ async def get_secrets_used(
self,
db: Database,
conn: Optional[Connection] = None,
):
return await get_secrets_used(db=db, conn=conn)
) -> List[str]:
return await get_secrets_used(
db=db,
conn=conn,
)

async def get_proof_used(
self,
db: Database,
proof: Proof,
conn: Optional[Connection] = None,
) -> Optional[Proof]:
return await get_proof_used(
db=db,
proof=proof,
conn=conn,
)

async def invalidate_proof(
self,
Expand Down Expand Up @@ -158,6 +173,16 @@ async def update_lightning_invoice(
conn=conn,
)

async def get_balance(
self,
db: Database,
conn: Optional[Connection] = None,
) -> int:
return await get_balance(
db=db,
conn=conn,
)


async def store_promise(
*,
Expand Down Expand Up @@ -205,7 +230,7 @@ async def get_promise(
async def get_secrets_used(
db: Database,
conn: Optional[Connection] = None,
):
) -> List[str]:
rows = await (conn or db).fetchall(f"""
SELECT secret from {table_with_schema(db, 'proofs_used')}
""")
Expand Down Expand Up @@ -243,6 +268,21 @@ async def get_proofs_pending(
return [Proof(**r) for r in rows]


async def get_proof_used(
db: Database,
proof: Proof,
conn: Optional[Connection] = None,
) -> Optional[Proof]:
row = await (conn or db).fetchone(
f"""
SELECT 1 from {table_with_schema(db, 'proofs_used')}
WHERE secret = ?
""",
(str(proof.secret),),
)
return Proof(**row) if row else None


async def set_proof_pending(
db: Database,
proof: Proof,
Expand Down Expand Up @@ -394,3 +434,14 @@ async def get_keyset(
tuple(values),
)
return [MintKeyset(**row) for row in rows]


async def get_balance(
db: Database,
conn: Optional[Connection] = None,
) -> int:
row = await (conn or db).fetchone(f"""
SELECT * from {table_with_schema(db, 'balance')}
""")
assert row, "Balance not found"
return int(row[0])
Loading

0 comments on commit ff1824d

Please sign in to comment.