refactor: move logic out of crud into the api layer

This commit is contained in:
Vlad Stan 2022-07-06 08:37:49 +03:00
parent 3d1b3b7173
commit 3f51117ea9
2 changed files with 37 additions and 17 deletions

View File

@ -12,19 +12,8 @@ from .helpers import parse_key, derive_address
##########################WALLETS####################
async def create_watch_wallet(user: str, masterpub: str, title: str) -> WalletAccount:
# check the masterpub is fine, it will raise an exception if not
(descriptor, _) = parse_key(masterpub)
type = descriptor.scriptpubkey_type()
fingerprint = descriptor.keys[0].fingerprint.hex()
async def create_watch_wallet(w: WalletAccount) -> WalletAccount:
wallet_id = urlsafe_short_hash()
wallets = await get_watch_wallets(user)
w = next((w for w in wallets if w.fingerprint == fingerprint), None)
if w:
raise ValueError("Account '{}' has the same master pulic key".format(w.title))
await db.execute(
"""
INSERT INTO watchonly.wallets (
@ -39,8 +28,16 @@ async def create_watch_wallet(user: str, masterpub: str, title: str) -> WalletAc
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
# address_no is -1 so fresh address on empty wallet can get address with index 0
(wallet_id, user, masterpub, fingerprint, title, type, -1, 0),
(
wallet_id,
w.user,
w.masterpub,
w.fingerprint,
w.title,
w.type,
w.address_no,
w.balance,
),
)
return await get_watch_wallet(wallet_id)

View File

@ -31,7 +31,7 @@ from .crud import (
get_config,
update_config,
)
from .models import CreateWallet, CreatePsbt, Config
from .models import CreateWallet, CreatePsbt, Config, WalletAccount
from .helpers import parse_key
@ -66,9 +66,32 @@ async def api_wallet_create_or_update(
data: CreateWallet, w: WalletTypeInfo = Depends(require_admin_key)
):
try:
wallet = await create_watch_wallet(
user=w.wallet.user, masterpub=data.masterpub, title=data.title
(descriptor, _) = parse_key(data.masterpub)
new_wallet = WalletAccount(
id="none",
user=w.wallet.user,
masterpub=data.masterpub,
fingerprint=descriptor.keys[0].fingerprint.hex(),
type=descriptor.scriptpubkey_type(),
title=data.title,
address_no=-1, # so fresh address on empty wallet can get address with index 0
balance=0,
)
wallets = await get_watch_wallets(w.wallet.user)
existing_wallet = next(
(ew for ew in wallets if ew.fingerprint == new_wallet.fingerprint), None
)
if existing_wallet:
raise ValueError(
"Account '{}' has the same master pulic key".format(
existing_wallet.title
)
)
wallet = await create_watch_wallet(new_wallet)
await api_get_addresses(wallet.id, w)
except Exception as e:
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))