Skip to content

Commit

Permalink
yo
Browse files Browse the repository at this point in the history
  • Loading branch information
callebtc committed May 25, 2024
1 parent da33d9f commit 6aefdea
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 42 deletions.
13 changes: 12 additions & 1 deletion cashu/core/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,21 @@
from functools import partial, wraps
from typing import List

from ..core.base import BlindedSignature, Proof
from ..core.base import Amount, BlindedSignature, Proof, Unit
from ..core.settings import settings


def amount_summary(proofs: List[Proof], unit: Unit) -> str:
amounts_we_have = [
(amount, len([p for p in proofs if p.amount == amount]))
for amount in set([p.amount for p in proofs])
]
amounts_we_have.sort(key=lambda x: x[0])
return (
f"{', '.join([f'{Amount(unit, a).str()} ({c}x)' for a, c in amounts_we_have])}"
)


def sum_proofs(proofs: List[Proof]):
return sum([p.amount for p in proofs])

Expand Down
44 changes: 28 additions & 16 deletions cashu/wallet/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,8 @@ async def wallets(ctx):
@coro
async def info(ctx: Context, mint: bool, mnemonic: bool):
wallet: Wallet = ctx.obj["WALLET"]
await wallet.load_keysets_from_db(unit=None)

print(f"Version: {settings.version}")
print(f"Wallet: {ctx.obj['WALLET_NAME']}")
if settings.debug:
Expand All @@ -866,30 +868,38 @@ async def info(ctx: Context, mint: bool, mnemonic: bool):
mint_list = await list_mints(wallet)
print("Mints:")
for mint_url in mint_list:
print(f" - {mint_url}")
print(f" - URL: {mint_url}")
keysets_strs = [
f"ID: {k.id} unit: {k.unit.name} active: {str(bool(k.active)) + ' ' if k.active else str(bool(k.active))} fee (ppk): {k.input_fee_ppk}"
for k in wallet.keysets.values()
]
if keysets_strs:
print(" - Keysets:")
for k in keysets_strs:
print(f" - {k}")
if mint:
wallet.url = mint_url
try:
mint_info: dict = (await wallet.load_mint_info()).dict()
print("")
print("---- Mint information ----")
print("")
print(f"Mint URL: {mint_url}")
if mint_info:
print(f"Mint name: {mint_info['name']}")
print(f" - Mint name: {mint_info['name']}")
if mint_info.get("description"):
print(f"Description: {mint_info['description']}")
print(f" - Description: {mint_info['description']}")
if mint_info.get("description_long"):
print(f"Long description: {mint_info['description_long']}")
if mint_info.get("contact"):
print(f"Contact: {mint_info['contact']}")
print(
f" - Long description: {mint_info['description_long']}"
)
if mint_info.get("contact") and mint_info.get("contact") != [
["", ""]
]:
print(f" - Contact: {mint_info['contact']}")
if mint_info.get("version"):
print(f"Version: {mint_info['version']}")
print(f" - Version: {mint_info['version']}")
if mint_info.get("motd"):
print(f"Message of the day: {mint_info['motd']}")
print(f" - Message of the day: {mint_info['motd']}")
if mint_info.get("nuts"):
print(
"Supported NUTS:"
" - Supported NUTS:"
f" {', '.join(['NUT-'+str(k) for k in mint_info['nuts'].keys()])}"
)
print("")
Expand All @@ -901,14 +911,16 @@ async def info(ctx: Context, mint: bool, mnemonic: bool):
assert wallet.mnemonic
print(f"Mnemonic:\n - {wallet.mnemonic}")
if settings.env_file:
print(f"Settings: {settings.env_file}")
print("Settings:")
print(f" - File: {settings.env_file}")
if settings.tor:
print(f"Tor enabled: {settings.tor}")
if settings.nostr_private_key:
try:
client = NostrClient(private_key=settings.nostr_private_key, connect=False)
print(f"Nostr public key: {client.public_key.bech32()}")
print(f"Nostr relays: {', '.join(settings.nostr_relays)}")
print("Nostr:")
print(f" - Public key: {client.public_key.bech32()}")
print(f" - Relays: {', '.join(settings.nostr_relays)}")
except Exception:
print("Nostr: Error. Invalid key.")
if settings.socks_proxy:
Expand Down
4 changes: 2 additions & 2 deletions cashu/wallet/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ async def store_keyset(

async def get_keysets(
id: str = "",
mint_url: str = "",
unit: str = "",
mint_url: Optional[str] = None,
unit: Optional[str] = None,
db: Optional[Database] = None,
conn: Optional[Connection] = None,
) -> List[WalletKeyset]:
Expand Down
21 changes: 8 additions & 13 deletions cashu/wallet/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
WalletKeyset,
)
from ..core.db import Database
from ..core.helpers import sum_proofs
from ..core.helpers import amount_summary, sum_proofs
from ..wallet.crud import (
update_proof,
)
Expand Down Expand Up @@ -82,13 +82,10 @@ async def _select_proofs_to_send(
if sum_proofs(proofs) < amount_to_send:
logger.trace("_select_proofs_to_send: not enough proofs to pay the amount.")
return []
# amounts_we_have = [
# (amount, len([p for p in proofs if p.amount == amount]))
# for amount in set([p.amount for p in proofs])
# ]
# logger.trace(
# f"_select_proofs_to_send – amount_to_send: {amount_to_send} – amounts we have: {amounts_we_have}"
# )
logger.trace(
f"_select_proofs_to_send – amount_to_send: {amount_to_send} – amounts we have: {amount_summary(proofs, self.unit)}"
)

sorted_proofs = sorted(proofs, key=lambda p: p.amount)

next_bigger = next(
Expand Down Expand Up @@ -148,11 +145,9 @@ async def _select_proofs_to_split(
Raises:
Exception: If the balance is too low to send the amount
"""
# amounts_we_have = [
# (amount, len([p for p in proofs if p.amount == amount]))
# for amount in set([p.amount for p in proofs])
# ]
# logger.debug(f"_select_proofs_to_split - amounts we have: {amounts_we_have}")
logger.debug(
f"_select_proofs_to_split - amounts we have: {amount_summary(proofs, self.unit)}"
)
send_proofs: List[Proof] = []

# check that enough spendable proofs exist
Expand Down
21 changes: 11 additions & 10 deletions cashu/wallet/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from loguru import logger

from ..core.base import (
Amount,
BlindedMessage,
BlindedSignature,
DLEQWallet,
Expand All @@ -21,7 +20,7 @@
from ..core.crypto.secp import PrivateKey, PublicKey
from ..core.db import Database
from ..core.errors import KeysetNotFoundError
from ..core.helpers import calculate_number_of_blank_outputs, sum_proofs
from ..core.helpers import amount_summary, calculate_number_of_blank_outputs, sum_proofs
from ..core.migrations import migrate_databases
from ..core.models import (
PostCheckStateResponse,
Expand Down Expand Up @@ -279,9 +278,16 @@ async def load_proofs(self, reload: bool = False) -> None:
f"Proofs loaded for keysets: {' '.join([k.id + f' ({k.unit})' for k in self.keysets.values()])}"
)

async def load_keysets_from_db(self):
async def load_keysets_from_db(
self, url: Union[str, None] = "", unit: Union[str, None] = ""
):
"""Load all keysets of the selected mint and unit from the database into self.keysets."""
keysets = await get_keysets(mint_url=self.url, unit=self.unit.name, db=self.db)
# so that the caller can set unit = None, otherwise use defaults
if unit == "":
unit = self.unit.name
if url == "":
url = self.url
keysets = await get_keysets(mint_url=url, unit=unit, db=self.db)
for keyset in keysets:
self.keysets[keyset.id] = keyset
logger.trace(
Expand Down Expand Up @@ -903,14 +909,9 @@ async def select_to_send(
proofs, amount, set_reserved=False
)
else:
amounts_we_have = [
(amount, len([p for p in proofs if p.amount == amount]))
for amount in set([p.amount for p in proofs])
]
amounts_we_have.sort(key=lambda x: x[0])
raise Exception(
"Could not select proofs in offline mode. Available amounts:"
f" {', '.join([f'{Amount(self.unit, a).str()} ({c}x)' for a, c in amounts_we_have])}"
+ amount_summary(proofs, self.unit)
)
if set_reserved:
await self.set_reserved(send_proofs, reserved=True)
Expand Down

0 comments on commit 6aefdea

Please sign in to comment.