black formatting

This commit is contained in:
Ben Arc 2021-04-09 00:41:19 +01:00
parent 6a18766a82
commit d872f0d138
8 changed files with 98 additions and 28 deletions

View file

@ -5,7 +5,8 @@ db = Database("ext_satspay")
satspay_ext: Blueprint = Blueprint( satspay_ext: Blueprint = Blueprint(
"satspay", __name__, static_folder="static", template_folder="templates") "satspay", __name__, static_folder="static", template_folder="templates"
)
from .views_api import * # noqa from .views_api import * # noqa

View file

@ -15,7 +15,17 @@ from ..watchonly.crud import get_watch_wallet, get_fresh_address, get_mempool
###############CHARGES########################## ###############CHARGES##########################
async def create_charge(user: str, description: str = None, onchainwallet: Optional[str] = None, lnbitswallet: Optional[str] = None, webhook: Optional[str] = None, completelink: Optional[str] = None, completelinktext: Optional[str] = None, time: Optional[int] = None, amount: Optional[int] = None) -> Charges: async def create_charge(
user: str,
description: str = None,
onchainwallet: Optional[str] = None,
lnbitswallet: Optional[str] = None,
webhook: Optional[str] = None,
completelink: Optional[str] = None,
completelinktext: Optional[str] = None,
time: Optional[int] = None,
amount: Optional[int] = None,
) -> Charges:
charge_id = urlsafe_short_hash() charge_id = urlsafe_short_hash()
if onchainwallet: if onchainwallet:
wallet = await get_watch_wallet(onchainwallet) wallet = await get_watch_wallet(onchainwallet)
@ -25,9 +35,8 @@ async def create_charge(user: str, description: str = None, onchainwallet: Optio
onchainaddress = None onchainaddress = None
if lnbitswallet: if lnbitswallet:
payment_hash, payment_request = await create_invoice( payment_hash, payment_request = await create_invoice(
wallet_id=lnbitswallet, wallet_id=lnbitswallet, amount=amount, memo=charge_id
amount=amount, )
memo=charge_id)
else: else:
payment_hash = None payment_hash = None
payment_request = None payment_request = None
@ -51,15 +60,31 @@ async def create_charge(user: str, description: str = None, onchainwallet: Optio
) )
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
(charge_id, user, description, onchainwallet, onchainaddress, lnbitswallet, (
payment_request, payment_hash, webhook, completelink, completelinktext, time, amount, 0), charge_id,
user,
description,
onchainwallet,
onchainaddress,
lnbitswallet,
payment_request,
payment_hash,
webhook,
completelink,
completelinktext,
time,
amount,
0,
),
) )
return await get_charge(charge_id) return await get_charge(charge_id)
async def update_charge(charge_id: str, **kwargs) -> Optional[Charges]: async def update_charge(charge_id: str, **kwargs) -> Optional[Charges]:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute(f"UPDATE charges SET {q} WHERE id = ?", (*kwargs.values(), charge_id)) await db.execute(
f"UPDATE charges SET {q} WHERE id = ?", (*kwargs.values(), charge_id)
)
row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,)) row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,))
return Charges.from_row(row) if row else None return Charges.from_row(row) if row else None
@ -85,14 +110,18 @@ async def check_address_balance(charge_id: str) -> List[Charges]:
mempool = await get_mempool(charge.user) mempool = await get_mempool(charge.user)
try: try:
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
r = await client.get(mempool.endpoint + "/api/address/" + charge.onchainaddress) r = await client.get(
respAmount = r.json()['chain_stats']['funded_txo_sum'] mempool.endpoint + "/api/address/" + charge.onchainaddress
)
respAmount = r.json()["chain_stats"]["funded_txo_sum"]
if respAmount >= charge.balance: if respAmount >= charge.balance:
await update_charge(charge_id=charge_id, balance=respAmount) await update_charge(charge_id=charge_id, balance=respAmount)
except Exception: except Exception:
pass pass
if charge.lnbitswallet: if charge.lnbitswallet:
invoice_status = await check_invoice_status(charge.lnbitswallet, charge.payment_hash) invoice_status = await check_invoice_status(
charge.lnbitswallet, charge.payment_hash
)
if invoice_status.paid: if invoice_status.paid:
return await update_charge(charge_id=charge_id, balance=charge.amount) return await update_charge(charge_id=charge_id, balance=charge.amount)
row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,)) row = await db.fetchone("SELECT * FROM charges WHERE id = ?", (charge_id,))

View file

@ -17,5 +17,6 @@ async def index():
@satspay_ext.route("/<charge_id>") @satspay_ext.route("/<charge_id>")
async def display(charge_id): async def display(charge_id):
charge = await get_charge(charge_id) or abort( charge = await get_charge(charge_id) or abort(
HTTPStatus.NOT_FOUND, "Charge link does not exist.") HTTPStatus.NOT_FOUND, "Charge link does not exist."
)
return await render_template("satspay/display.html", charge=charge) return await render_template("satspay/display.html", charge=charge)

View file

@ -48,7 +48,19 @@ async def api_charge_create_or_update(charge_id=None):
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
async def api_charges_retrieve(): async def api_charges_retrieve():
try: try:
return jsonify([{**charge._asdict(), **{"time_elapsed": charge.time_elapsed}, **{"paid": charge.paid}}for charge in await get_charges(g.wallet.user)]), HTTPStatus.OK return (
jsonify(
[
{
**charge._asdict(),
**{"time_elapsed": charge.time_elapsed},
**{"paid": charge.paid},
}
for charge in await get_charges(g.wallet.user)
]
),
HTTPStatus.OK,
)
except: except:
return "" return ""
@ -61,7 +73,16 @@ async def api_charge_retrieve(charge_id):
if not charge: if not charge:
return jsonify({"message": "charge does not exist"}), HTTPStatus.NOT_FOUND return jsonify({"message": "charge does not exist"}), HTTPStatus.NOT_FOUND
return jsonify({**charge._asdict(), **{"time_elapsed": charge.time_elapsed}, **{"paid": charge.paid}}), HTTPStatus.OK return (
jsonify(
{
**charge._asdict(),
**{"time_elapsed": charge.time_elapsed},
**{"paid": charge.paid},
}
),
HTTPStatus.OK,
)
@satspay_ext.route("/api/v1/charge/<charge_id>", methods=["DELETE"]) @satspay_ext.route("/api/v1/charge/<charge_id>", methods=["DELETE"])
@ -79,6 +100,7 @@ async def api_charge_delete(charge_id):
#############################BALANCE########################## #############################BALANCE##########################
@satspay_ext.route("/api/v1/charges/balance/<charge_id>", methods=["GET"]) @satspay_ext.route("/api/v1/charges/balance/<charge_id>", methods=["GET"])
async def api_charges_balance(charge_id): async def api_charges_balance(charge_id):
@ -110,6 +132,7 @@ async def api_charges_balance(charge_id):
charge.webhook = None charge.webhook = None
return jsonify(charge._asdict()), HTTPStatus.OK return jsonify(charge._asdict()), HTTPStatus.OK
#############################MEMPOOL########################## #############################MEMPOOL##########################

View file

@ -5,7 +5,8 @@ db = Database("ext_watchonly")
watchonly_ext: Blueprint = Blueprint( watchonly_ext: Blueprint = Blueprint(
"watchonly", __name__, static_folder="static", template_folder="templates") "watchonly", __name__, static_folder="static", template_folder="templates"
)
from .views_api import * # noqa from .views_api import * # noqa

View file

@ -15,6 +15,7 @@ import httpx
##########################WALLETS#################### ##########################WALLETS####################
def detect_network(k): def detect_network(k):
version = k.key.version version = k.key.version
for network_name in NETWORKS: for network_name in NETWORKS:
@ -23,6 +24,7 @@ def detect_network(k):
if version in [net["xpub"], net["ypub"], net["zpub"], net["Zpub"], net["Ypub"]]: if version in [net["xpub"], net["ypub"], net["zpub"], net["Zpub"], net["Ypub"]]:
return net return net
def parse_key(masterpub: str): def parse_key(masterpub: str):
"""Parses masterpub or descriptor and returns a tuple: (Descriptor, network) """Parses masterpub or descriptor and returns a tuple: (Descriptor, network)
To create addresses use descriptor.derive(num).address(network=network) To create addresses use descriptor.derive(num).address(network=network)
@ -37,7 +39,9 @@ def parse_key(masterpub: str):
raise ValueError("Private keys are not allowed") raise ValueError("Private keys are not allowed")
# check depth # check depth
if k.key.depth != 3: if k.key.depth != 3:
raise ValueError("Non-standard depth. Only bip44, bip49 and bip84 are supported with bare xpubs. For custom derivation paths use descriptors.") raise ValueError(
"Non-standard depth. Only bip44, bip49 and bip84 are supported with bare xpubs. For custom derivation paths use descriptors."
)
# if allowed derivation is not provided use default /{0,1}/* # if allowed derivation is not provided use default /{0,1}/*
if k.allowed_derivation is None: if k.allowed_derivation is None:
k.allowed_derivation = AllowedDerivation.default() k.allowed_derivation = AllowedDerivation.default()
@ -110,7 +114,9 @@ async def get_watch_wallets(user: str) -> List[Wallets]:
async def update_watch_wallet(wallet_id: str, **kwargs) -> Optional[Wallets]: async def update_watch_wallet(wallet_id: str, **kwargs) -> Optional[Wallets]:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute(f"UPDATE wallets SET {q} WHERE id = ?", (*kwargs.values(), wallet_id)) await db.execute(
f"UPDATE wallets SET {q} WHERE id = ?", (*kwargs.values(), wallet_id)
)
row = await db.fetchone("SELECT * FROM wallets WHERE id = ?", (wallet_id,)) row = await db.fetchone("SELECT * FROM wallets WHERE id = ?", (wallet_id,))
return Wallets.from_row(row) if row else None return Wallets.from_row(row) if row else None
@ -161,6 +167,7 @@ async def get_addresses(wallet_id: str) -> List[Addresses]:
rows = await db.fetchall("SELECT * FROM addresses WHERE wallet = ?", (wallet_id,)) rows = await db.fetchall("SELECT * FROM addresses WHERE wallet = ?", (wallet_id,))
return [Addresses(**row) for row in rows] return [Addresses(**row) for row in rows]
######################MEMPOOL####################### ######################MEMPOOL#######################
@ -173,7 +180,7 @@ async def create_mempool(user: str) -> Mempool:
) )
VALUES (?, ?) VALUES (?, ?)
""", """,
(user, 'https://mempool.space'), (user, "https://mempool.space"),
) )
row = await db.fetchone("SELECT * FROM mempool WHERE user = ?", (user,)) row = await db.fetchone("SELECT * FROM mempool WHERE user = ?", (user,))
return Mempool.from_row(row) if row else None return Mempool.from_row(row) if row else None

View file

@ -16,6 +16,7 @@ async def index():
@watchonly_ext.route("/<charge_id>") @watchonly_ext.route("/<charge_id>")
async def display(charge_id): async def display(charge_id):
link = get_payment(charge_id) or abort( link = get_payment(charge_id) or abort(
HTTPStatus.NOT_FOUND, "Charge link does not exist.") HTTPStatus.NOT_FOUND, "Charge link does not exist."
)
return await render_template("watchonly/display.html", link=link) return await render_template("watchonly/display.html", link=link)

View file

@ -30,7 +30,10 @@ async def api_wallets_retrieve():
try: try:
return ( return (
jsonify([wallet._asdict() for wallet in await get_watch_wallets(g.wallet.user)]), HTTPStatus.OK jsonify(
[wallet._asdict() for wallet in await get_watch_wallets(g.wallet.user)]
),
HTTPStatus.OK,
) )
except: except:
return "" return ""
@ -57,7 +60,9 @@ async def api_wallet_retrieve(wallet_id):
) )
async def api_wallet_create_or_update(wallet_id=None): async def api_wallet_create_or_update(wallet_id=None):
try: try:
wallet = await create_watch_wallet(user=g.wallet.user, masterpub=g.data["masterpub"], title=g.data["title"]) wallet = await create_watch_wallet(
user=g.wallet.user, masterpub=g.data["masterpub"], title=g.data["title"]
)
except Exception as e: except Exception as e:
return jsonify({"message": str(e)}), HTTPStatus.BAD_REQUEST return jsonify({"message": str(e)}), HTTPStatus.BAD_REQUEST
mempool = await get_mempool(g.wallet.user) mempool = await get_mempool(g.wallet.user)
@ -81,6 +86,7 @@ async def api_wallet_delete(wallet_id):
#############################ADDRESSES########################## #############################ADDRESSES##########################
@watchonly_ext.route("/api/v1/address/<wallet_id>", methods=["GET"]) @watchonly_ext.route("/api/v1/address/<wallet_id>", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
async def api_fresh_address(wallet_id): async def api_fresh_address(wallet_id):
@ -110,6 +116,7 @@ async def api_get_addresses(wallet_id):
#############################MEMPOOL########################## #############################MEMPOOL##########################
@watchonly_ext.route("/api/v1/mempool", methods=["PUT"]) @watchonly_ext.route("/api/v1/mempool", methods=["PUT"])
@api_check_wallet_key("admin") @api_check_wallet_key("admin")
@api_validate_post_request( @api_validate_post_request(