Skip to content

Commit

Permalink
The alias function is used to create a unique_id out of a user input,…
Browse files Browse the repository at this point in the history
… e.g. for device and most importantly for wallet names. The naming of this function now reflect this. (#2439)

Signed-off-by: Simon Castano <[email protected]>
Co-authored-by: k9ert <[email protected]>
  • Loading branch information
roshii and k9ert authored May 29, 2024
1 parent 92f10e0 commit 50b5d63
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 40 deletions.
18 changes: 11 additions & 7 deletions src/cryptoadvance/specter/devices/bitcoin_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from embit import bip32, bip39, networks

from ..device import Device
from ..helpers import alias
from ..helpers import create_unique_id
from ..key import Key
from ..rpc import get_default_datadir
from ..specter_error import SpecterError
Expand Down Expand Up @@ -115,9 +115,11 @@ def add_hot_wallet_keys(
{
"desc": AddChecksum(
"{}({}{}/0/*)".format(
"tr"
if path.startswith("m/86h") and taproot_available
else "wpkh",
(
"tr"
if path.startswith("m/86h") and taproot_available
else "wpkh"
),
xprv,
path.rstrip("/").replace("m", ""),
)
Expand All @@ -130,9 +132,11 @@ def add_hot_wallet_keys(
{
"desc": AddChecksum(
"{}({}{}/1/*)".format(
"tr"
if path.startswith("m/86h") and taproot_available
else "wpkh",
(
"tr"
if path.startswith("m/86h") and taproot_available
else "wpkh"
),
xprv,
path.rstrip("/").replace("m", ""),
)
Expand Down
9 changes: 4 additions & 5 deletions src/cryptoadvance/specter/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,9 @@ def to_ascii20(name: str) -> str:
return "".join([c for c in name if ord(c) < 127])[:20]


# TODO: Rename this function to sth. like create_unique_id
def alias(name):
def create_unique_id(name):
"""
Create a filesystem-friendly alias from a string.
Create a filesystem-friendly unique ID from a string.
Leading and trailing whitespaces are removed.
Replaces space(s) and hyphen(s) with one underscore.
Keeps only alphanumeric chars and returns in lowercase.
Expand All @@ -128,12 +127,12 @@ def alias(name):

def fullpath(data_folder, name):
"""Quick way to get a fullpath which usually"""
return os.path.join(data_folder, f"{alias(name)}.json")
return os.path.join(data_folder, f"{create_unique_id(name)}.json")


def calc_fullpath(data_folder, name):
"""Get a fullpath for a Businessobject with a name quickly"""
return os.path.join(data_folder, f"{alias(name)}.json")
return os.path.join(data_folder, f"{create_unique_id(name)}.json")


def deep_update(d, u):
Expand Down
6 changes: 3 additions & 3 deletions src/cryptoadvance/specter/managers/device_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from cryptoadvance.specter.devices.bitcoin_core import BitcoinCore, BitcoinCoreWatchOnly

from ..helpers import alias, load_jsons
from ..helpers import create_unique_id, load_jsons
from ..rpc import get_default_datadir

from ..devices import __all__ as all_device_classes
Expand Down Expand Up @@ -59,11 +59,11 @@ def devices_names(self):
return sorted(self.devices.keys())

def add_device(self, name, device_type, keys):
device_alias = alias(name)
device_alias = create_unique_id(name)
fullpath = os.path.join(self.data_folder, "%s.json" % device_alias)
i = 2
while os.path.isfile(fullpath):
device_alias = alias("%s %d" % (name, i))
device_alias = create_unique_id("%s %d" % (name, i))
fullpath = os.path.join(self.data_folder, "%s.json" % device_alias)
i += 1
# remove duplicated keys if any exist
Expand Down
10 changes: 5 additions & 5 deletions src/cryptoadvance/specter/managers/node_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from ..rpc import get_default_datadir, RPC_PORTS
from ..specter_error import SpecterError, SpecterInternalException
from ..persistence import PersistentObject, write_node, delete_file
from ..helpers import alias, calc_fullpath, load_jsons
from ..helpers import create_unique_id, calc_fullpath, load_jsons
from ..node import Node, NonExistingNode
from ..internal_node import InternalNode
from ..services import callbacks
Expand Down Expand Up @@ -193,11 +193,11 @@ def add_external_node(
This should only be used for an external node. Use add_internal_node for internal node
and if you have defined your own node type, use save_node directly to save the node (and create it yourself)
"""
node_alias = alias(name)
node_alias = create_unique_id(name)
fullpath = os.path.join(self.data_folder, "%s.json" % node_alias)
i = 2
while os.path.isfile(fullpath):
node_alias = alias("%s %d" % (name, i))
node_alias = create_unique_id("%s %d" % (name, i))
fullpath = os.path.join(self.data_folder, "%s.json" % node_alias)
i += 1

Expand Down Expand Up @@ -239,11 +239,11 @@ def add_internal_node(
This should only be used for internal nodes. Use add__External_node for external nodes
and if you have defined your own node-type, use save_node directly. to save the node (and create it yourself)
"""
node_alias = alias(name)
node_alias = create_unique_id(name)
fullpath = os.path.join(self.data_folder, "%s.json" % node_alias)
i = 2
while os.path.isfile(fullpath):
node_alias = alias("%s %d" % (name, i))
node_alias = create_unique_id("%s %d" % (name, i))
fullpath = os.path.join(self.data_folder, "%s.json" % node_alias)
i += 1
if not datadir:
Expand Down
4 changes: 2 additions & 2 deletions src/cryptoadvance/specter/managers/wallet_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from cryptoadvance.specter.rpc import BitcoinRPC
from cryptoadvance.specter.key import Key

from ..helpers import add_dicts, alias, is_liquid, load_jsons
from ..helpers import add_dicts, create_unique_id, is_liquid, load_jsons
from ..liquid.wallet import LWallet
from ..persistence import delete_folder
from ..rpc import RpcError, get_default_datadir, BrokenCoreConnectionException
Expand Down Expand Up @@ -348,7 +348,7 @@ def create_wallet(
except:
walletsindir = []
self._check_duplicate_keys(keys)
wallet_alias = alias(name)
wallet_alias = create_unique_id(name)

w = self.WalletClass.create(
self.rpc,
Expand Down
6 changes: 3 additions & 3 deletions src/cryptoadvance/specter/server_endpoints/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from cryptoadvance.specter.specter import Specter

from ..helpers import alias, is_relative_url
from ..helpers import create_unique_id, is_relative_url
from ..server_endpoints import flash
from ..services import ExtensionException
from ..user import User, hash_password, verify_password
Expand Down Expand Up @@ -161,11 +161,11 @@ def register():
)
return redirect("register?otp={}".format(otp))
if app.specter.otp_manager.validate_new_user_otp(otp):
user_id = alias(username)
user_id = create_unique_id(username)
i = 1
while app.specter.user_manager.get_user(user_id):
i += 1
user_id = "{}{}".format(alias(username), i)
user_id = "{}{}".format(create_unique_id(username), i)
if app.specter.user_manager.get_user_by_username(username):
flash(
_("Username is already taken, please choose another one"), "error"
Expand Down
6 changes: 4 additions & 2 deletions src/cryptoadvance/specter/server_endpoints/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from flask_babel import lazy_gettext as _
from flask_login import login_required

from ..helpers import alias
from ..helpers import create_unique_id
from ..util.bitcoind_setup_tasks import (
setup_bitcoind_directory_thread,
setup_bitcoind_thread,
Expand All @@ -28,6 +28,7 @@
# Setup endpoint blueprint
setup_endpoint = Blueprint("setup_endpoint", __name__)


######################### Setup pages #######################################
@setup_endpoint.route("/start/", methods=["GET"])
@login_required
Expand Down Expand Up @@ -169,7 +170,8 @@ def setup_bitcoind_datadir():
else f"Specter {network.title()} {i}"
)
node_default_datadir = os.path.join(
app.specter.node_manager.data_folder, f"{alias(node_name)}/.bitcoin-{network}"
app.specter.node_manager.data_folder,
f"{create_unique_id(node_name)}/.bitcoin-{network}",
)
user_selected_datadir = request.form.get(
"bitcoin_core_datadir", node_default_datadir
Expand Down
18 changes: 15 additions & 3 deletions src/cryptoadvance/specter/server_endpoints/wallets/wallets.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@
from flask_login import login_required

from ...commands.psbt_creator import PsbtCreator
from ...helpers import bcur2base64, get_devices_with_keys_by_type, get_txid, alias
from ...helpers import (
bcur2base64,
get_devices_with_keys_by_type,
get_txid,
create_unique_id,
)
from ...key import Key
from ...managers.wallet_manager import purposes
from ...persistence import delete_file
Expand Down Expand Up @@ -246,7 +251,10 @@ def new_wallet(wallet_type):
address_type = request.form["type"]
sigs_total = int(request.form.get("sigs_total", 1))
sigs_required = int(request.form.get("sigs_required", 1))
if alias(wallet_name) in app.specter.wallet_manager.wallets_aliases:
if (
create_unique_id(wallet_name)
in app.specter.wallet_manager.wallets_aliases
):
err = _("Wallet name already exists. Choose a different name!")
if err:
devices = [
Expand Down Expand Up @@ -383,6 +391,7 @@ def new_wallet(wallet_type):

################## Wallet pages #######################


###### Wallet index page ######
@wallets_endpoint.route("/wallet/<wallet_alias>/")
@login_required
Expand Down Expand Up @@ -805,7 +814,10 @@ def settings(wallet_alias):
flash(_("Wallet name cannot be empty"), "error")
elif wallet_name == wallet.name:
pass
elif alias(wallet_name) in app.specter.wallet_manager.wallets_aliases:
elif (
create_unique_id(wallet_name)
in app.specter.wallet_manager.wallets_aliases
):
flash(
_("Wallet name already exists. Choose a different name!"), "error"
)
Expand Down
17 changes: 13 additions & 4 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import logging
from cryptoadvance.specter.helpers import deep_update, load_jsons, is_ip_private, alias
from cryptoadvance.specter.helpers import (
deep_update,
load_jsons,
is_ip_private,
create_unique_id,
)

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -80,7 +85,7 @@ def test_is_ip_private(caplog):
assert not is_ip_private(ip)


def test_alias():
def test_create_unique_id():
the_same_unique_names = [
"ghost wallet",
"Ghost Wallet",
Expand All @@ -97,7 +102,9 @@ def test_alias():
"Ghost Wallet?",
"Ghost Wallet***",
]
assert all(alias(name) == "ghost_wallet" for name in the_same_unique_names)
assert all(
create_unique_id(name) == "ghost_wallet" for name in the_same_unique_names
)
not_the_same_unique_names = [
"ghost wallet",
"ghost wallet 2",
Expand All @@ -106,4 +113,6 @@ def test_alias():
"ghostwallet123",
"my_ghos_wallet",
]
assert not all(alias(name) == "ghost_wallet" for name in not_the_same_unique_names)
assert not all(
create_unique_id(name) == "ghost_wallet" for name in not_the_same_unique_names
)
10 changes: 5 additions & 5 deletions tests/test_specter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
from decimal import Decimal

import pytest
from cryptoadvance.specter.helpers import alias
from cryptoadvance.specter.helpers import create_unique_id
from cryptoadvance.specter.managers.wallet_manager import WalletManager
from cryptoadvance.specter.specter import Specter
from cryptoadvance.specter.specter_error import SpecterError
from cryptoadvance.specter.util.mnemonic import generate_mnemonic


def test_alias():
assert alias("wurst 1") == "wurst_1"
assert alias("wurst_1") == "wurst_1"
assert alias("Wurst$ 1") == "wurst_1"
def test_create_unique_id():
assert create_unique_id("wurst 1") == "wurst_1"
assert create_unique_id("wurst_1") == "wurst_1"
assert create_unique_id("Wurst$ 1") == "wurst_1"


def test_specter(specter_regtest_configured, caplog):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_util_tx.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging, pytest
from cryptoadvance.specter.helpers import alias
from cryptoadvance.specter.helpers import create_unique_id
from cryptoadvance.specter.key import Key
from cryptoadvance.specter.process_controller.node_controller import NodeController
from cryptoadvance.specter.rpc import BitcoinRPC
Expand Down

0 comments on commit 50b5d63

Please sign in to comment.