Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions bittensor_cli/src/bittensor/extrinsics/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import backoff
from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from Crypto.Hash import keccak
import numpy as np
from rich.prompt import Confirm
Expand All @@ -37,6 +36,7 @@
get_human_readable,
print_verbose,
print_error,
unlock_key,
)

if typing.TYPE_CHECKING:
Expand Down Expand Up @@ -726,10 +726,8 @@ async def run_faucet_extrinsic(
return False, "Requires torch"

# Unlock coldkey
try:
wallet.unlock_coldkey()
except KeyFileError:
return False, "There was an error unlocking your coldkey"
if not (unlock_status := unlock_key(wallet, print_out=False)).success:
return False, unlock_status.message

# Get previous balance.
old_balance = await subtensor.get_balance(wallet.coldkeypub.ss58_address)
Expand Down Expand Up @@ -1639,10 +1637,7 @@ async def swap_hotkey_extrinsic(
)
return False

try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

if prompt:
Expand Down
12 changes: 3 additions & 9 deletions bittensor_cli/src/bittensor/extrinsics/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from typing import Union, List, TYPE_CHECKING

from bittensor_wallet import Wallet, Keypair
from bittensor_wallet.errors import KeyFileError
import numpy as np
from numpy.typing import NDArray
from rich.prompt import Confirm
Expand All @@ -37,6 +36,7 @@
u16_normalized_float,
print_verbose,
format_error_message,
unlock_key,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -306,10 +306,7 @@ async def root_register_extrinsic(
the response is `True`.
"""

try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

print_verbose(f"Checking if hotkey ({wallet.hotkey_str}) is registered on root")
Expand Down Expand Up @@ -427,10 +424,7 @@ async def _do_set_weights():
err_console.print("Your hotkey is not registered to the root network")
return False

try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

# First convert types.
Expand Down
7 changes: 2 additions & 5 deletions bittensor_cli/src/bittensor/extrinsics/transfer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import asyncio

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm
from substrateinterface.exceptions import SubstrateRequestException

Expand All @@ -16,6 +15,7 @@
get_explorer_url_for_network,
is_valid_bittensor_address_or_public_key,
print_error,
unlock_key,
)


Expand Down Expand Up @@ -115,10 +115,7 @@ async def do_transfer() -> tuple[bool, str, str]:
return False
console.print(f"[dark_orange]Initiating transfer on network: {subtensor.network}")
# Unlock wallet coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

# Check balance.
Expand Down
41 changes: 40 additions & 1 deletion bittensor_cli/src/bittensor/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ast
from collections import namedtuple
import math
import os
import sqlite3
Expand All @@ -9,7 +10,7 @@

from bittensor_wallet import Wallet, Keypair
from bittensor_wallet.utils import SS58_FORMAT
from bittensor_wallet.errors import KeyFileError
from bittensor_wallet.errors import KeyFileError, PasswordError
from bittensor_wallet import utils
from jinja2 import Template
from markupsafe import Markup
Expand All @@ -35,6 +36,8 @@
err_console = Console(stderr=True)
verbose_console = Console(quiet=True)

UnlockStatus = namedtuple("UnlockStatus", ["success", "message"])


def print_console(message: str, colour: str, title: str, console: Console):
console.print(
Expand Down Expand Up @@ -977,3 +980,39 @@ def retry_prompt(
return var
else:
err_console.print(rejection_text)


def unlock_key(
wallet: Wallet, unlock_type="cold", print_out: bool = True
) -> "UnlockStatus":
"""
Attempts to decrypt a wallet's coldkey or hotkey
Args:
wallet: a Wallet object
unlock_type: the key type, 'cold' or 'hot'
print_out: whether to print out the error message to the err_console

Returns: UnlockStatus for success status of unlock, with error message if unsuccessful

"""
if unlock_type == "cold":
unlocker = "unlock_coldkey"
elif unlock_type == "hot":
unlocker = "unlock_hotkey"
else:
raise ValueError(
f"Invalid unlock type provided: {unlock_type}. Must be 'cold' or 'hot'."
)
try:
getattr(wallet, unlocker)()
return UnlockStatus(True, "")
except PasswordError:
err_msg = f"The password used to decrypt your {unlock_type.capitalize()}key Keyfile is invalid."
if print_out:
err_console.print(f":cross_mark: [red]{err_msg}[/red]")
return UnlockStatus(False, err_msg)
except KeyFileError:
err_msg = f"{unlock_type.capitalize()}key Keyfile is corrupt, non-writable, or non-readable, or non-existent."
if print_out:
err_console.print(f":cross_mark: [red]{err_msg}[/red]")
return UnlockStatus(False, err_msg)
30 changes: 6 additions & 24 deletions bittensor_cli/src/commands/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from typing import Optional, TYPE_CHECKING

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
import numpy as np
from numpy.typing import NDArray
from rich import box
Expand Down Expand Up @@ -42,6 +41,7 @@
ss58_to_vec_u8,
update_metadata_table,
group_subnets,
unlock_key,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -280,10 +280,7 @@ async def burned_register_extrinsic(
finalization/inclusion, the response is `True`.
"""

try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

with console.status(
Expand Down Expand Up @@ -537,10 +534,7 @@ async def get_stake_for_coldkey_and_hotkey(
delegate_string = "delegate" if delegate else "undelegate"

# Decrypt key
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

print_verbose("Checking if hotkey is a delegate")
Expand Down Expand Up @@ -1098,11 +1092,7 @@ async def senate_vote(
return False

# Unlock the wallet.
try:
wallet.unlock_hotkey()
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success and unlock_key(wallet, "hot").success:
return False

console.print(f"Fetching proposals in [dark_orange]network: {subtensor.network}")
Expand Down Expand Up @@ -1322,11 +1312,7 @@ async def _do_set_take() -> bool:

console.print(f"Setting take on [dark_orange]network: {subtensor.network}")
# Unlock the wallet.
try:
wallet.unlock_hotkey()
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success and unlock_key(wallet, "hot").success:
return False

result_ = await _do_set_take()
Expand Down Expand Up @@ -1724,11 +1710,7 @@ async def nominate(wallet: Wallet, subtensor: SubtensorInterface, prompt: bool):

console.print(f"Nominating on [dark_orange]network: {subtensor.network}")
# Unlock the wallet.
try:
wallet.unlock_hotkey()
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success and unlock_key(wallet, "hot").success:
return False

print_verbose(f"Checking hotkey ({wallet.hotkey_str}) is a delegate")
Expand Down
14 changes: 5 additions & 9 deletions bittensor_cli/src/commands/stake/children_hotkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Optional

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm, Prompt, IntPrompt
from rich.table import Table
from rich.text import Text
Expand All @@ -19,6 +18,7 @@
u64_to_float,
is_valid_ss58_address,
format_error_message,
unlock_key,
)


Expand Down Expand Up @@ -72,10 +72,8 @@ async def set_children_extrinsic(
return False, "Operation Cancelled"

# Decrypt coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
return False, "There was an error unlocking your coldkey."
if not (unlock_status := unlock_key(wallet, print_out=False)).success:
return False, unlock_status.message

with console.status(
f":satellite: {operation} on [white]{subtensor.network}[/white] ..."
Expand Down Expand Up @@ -158,10 +156,8 @@ async def set_childkey_take_extrinsic(
return False, "Operation Cancelled"

# Decrypt coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
return False, "There was an error unlocking your coldkey."
if not (unlock_status := unlock_key(wallet, print_out=False)).success:
return False, unlock_status.message

with console.status(
f":satellite: Setting childkey take on [white]{subtensor.network}[/white] ..."
Expand Down
24 changes: 6 additions & 18 deletions bittensor_cli/src/commands/stake/stake.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from typing import TYPE_CHECKING, Optional, Sequence, Union, cast

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm
from rich.table import Table, Column
import typer
Expand All @@ -28,6 +27,7 @@
render_tree,
u16_normalized_float,
validate_coldkey_presence,
unlock_key,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -103,10 +103,7 @@ async def add_stake_extrinsic(
"""

# Decrypt keys,
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

# Default to wallet's own hotkey if the value is not passed.
Expand Down Expand Up @@ -310,10 +307,7 @@ async def add_stake_multiple_extrinsic(
return True

# Decrypt coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

with console.status(
Expand Down Expand Up @@ -491,11 +485,8 @@ async def unstake_extrinsic(
:return: success: `True` if extrinsic was finalized or included in the block. If we did not wait for
finalization/inclusion, the response is `True`.
"""
# Decrypt keys,
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
# Decrypt coldkey
if not unlock_key(wallet).success:
return False

if hotkey_ss58 is None:
Expand Down Expand Up @@ -663,10 +654,7 @@ async def unstake_multiple_extrinsic(
return True

# Unlock coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

with console.status(
Expand Down
7 changes: 2 additions & 5 deletions bittensor_cli/src/commands/subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import TYPE_CHECKING, Optional, cast

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm
from rich.table import Column, Table

Expand All @@ -28,6 +27,7 @@
millify,
render_table,
update_metadata_table,
unlock_key,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -100,10 +100,7 @@ async def _find_event_attributes_in_extrinsic_receipt(
):
return False

try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
if not unlock_key(wallet).success:
return False

with console.status(":satellite: Registering subnet...", spinner="earth"):
Expand Down
Loading