From 88f645d610d08ab942faecae0088d6d4f91c5bdf Mon Sep 17 00:00:00 2001 From: Benjamin Himes Date: Thu, 14 Nov 2024 17:14:35 +0200 Subject: [PATCH] Uses a more general-use hex_to_bytes function for converting rather than the try:except --- .../bittensor/async_substrate_interface.py | 7 ++--- .../src/bittensor/extrinsics/registration.py | 7 +++-- .../src/bittensor/subtensor_interface.py | 29 ++++--------------- bittensor_cli/src/bittensor/utils.py | 13 ++++++++- bittensor_cli/src/commands/subnets.py | 7 ++--- bittensor_cli/src/commands/wallets.py | 10 ++----- 6 files changed, 29 insertions(+), 44 deletions(-) diff --git a/bittensor_cli/src/bittensor/async_substrate_interface.py b/bittensor_cli/src/bittensor/async_substrate_interface.py index 08e0cc9b..82bfc9d0 100644 --- a/bittensor_cli/src/bittensor/async_substrate_interface.py +++ b/bittensor_cli/src/bittensor/async_substrate_interface.py @@ -22,6 +22,8 @@ from substrateinterface.storage import StorageKey import websockets +from bittensor_cli.src.bittensor.utils import hex_to_bytes + ResultHandler = Callable[[dict, Any], Awaitable[tuple[dict, bool]]] @@ -2564,10 +2566,7 @@ def concat_hash_len(key_hasher: str) -> int: item_key = None try: - try: - item_bytes = bytes.fromhex(item[1][2:]) - except ValueError: - item_bytes = bytes.fromhex(item[1]) + item_bytes = hex_to_bytes(item[1]) item_value = await self.decode_scale( type_string=value_type, diff --git a/bittensor_cli/src/bittensor/extrinsics/registration.py b/bittensor_cli/src/bittensor/extrinsics/registration.py index d73837d2..33c9c156 100644 --- a/bittensor_cli/src/bittensor/extrinsics/registration.py +++ b/bittensor_cli/src/bittensor/extrinsics/registration.py @@ -37,6 +37,7 @@ print_verbose, print_error, unlock_key, + hex_to_bytes, ) if typing.TYPE_CHECKING: @@ -863,7 +864,7 @@ async def _check_for_newest_block_and_update( block_number, difficulty, block_hash = await _get_block_with_retry( subtensor=subtensor, netuid=netuid ) - block_bytes = bytes.fromhex(block_hash[2:]) + block_bytes = hex_to_bytes(block_hash) update_curr_block( curr_diff, @@ -970,7 +971,7 @@ async def _block_solver( subtensor=subtensor, netuid=netuid ) - block_bytes = bytes.fromhex(block_hash[2:]) + block_bytes = hex_to_bytes(block_hash) old_block_number = block_number # Set to current block _update_curr_block( @@ -1249,7 +1250,7 @@ def _terminate_workers_and_wait_for_exit( @backoff.on_exception(backoff.constant, Exception, interval=1, max_tries=3) async def _get_block_with_retry( subtensor: "SubtensorInterface", netuid: int -) -> tuple[int, int, bytes]: +) -> tuple[int, int, str]: """ Gets the current block number, difficulty, and block hash from the substrate node. diff --git a/bittensor_cli/src/bittensor/subtensor_interface.py b/bittensor_cli/src/bittensor/subtensor_interface.py index b8cfb7af..54ca20b6 100644 --- a/bittensor_cli/src/bittensor/subtensor_interface.py +++ b/bittensor_cli/src/bittensor/subtensor_interface.py @@ -35,6 +35,7 @@ err_console, decode_hex_identity_dict, validate_chain_endpoint, + hex_to_bytes, ) @@ -213,12 +214,7 @@ async def get_delegates( block_hash=block_hash, ) if hex_bytes_result is not None: - try: - bytes_result = bytes.fromhex(hex_bytes_result[2:]) - except ValueError: - bytes_result = bytes.fromhex(hex_bytes_result) - - return DelegateInfo.list_from_vec_u8(bytes_result) + return DelegateInfo.list_from_vec_u8(hex_to_bytes(hex_bytes_result)) else: return [] @@ -254,12 +250,7 @@ async def get_stake_info_for_coldkey( if hex_bytes_result is None: return [] - try: - bytes_result = bytes.fromhex(hex_bytes_result[2:]) - except ValueError: - bytes_result = bytes.fromhex(hex_bytes_result) - - return StakeInfo.list_from_vec_u8(bytes_result) + return StakeInfo.list_from_vec_u8(hex_to_bytes(hex_bytes_result)) async def get_stake_for_coldkey_and_hotkey( self, hotkey_ss58: str, coldkey_ss58: str, block_hash: Optional[str] @@ -654,12 +645,7 @@ async def neurons_lite( if hex_bytes_result is None: return [] - try: - bytes_result = bytes.fromhex(hex_bytes_result[2:]) - except ValueError: - bytes_result = bytes.fromhex(hex_bytes_result) - - return NeuronInfoLite.list_from_vec_u8(bytes_result) + return NeuronInfoLite.list_from_vec_u8(hex_to_bytes(hex_bytes_result)) async def neuron_for_uid( self, uid: Optional[int], netuid: int, block_hash: Optional[str] = None @@ -988,12 +974,7 @@ async def get_subnet_hyperparameters( if hex_bytes_result is None: return [] - if hex_bytes_result.startswith("0x"): - bytes_result = bytes.fromhex(hex_bytes_result[2:]) - else: - bytes_result = bytes.fromhex(hex_bytes_result) - - return SubnetHyperparameters.from_vec_u8(bytes_result) + return SubnetHyperparameters.from_vec_u8(hex_to_bytes(hex_bytes_result)) async def get_vote_data( self, diff --git a/bittensor_cli/src/bittensor/utils.py b/bittensor_cli/src/bittensor/utils.py index a3954a85..69d26515 100644 --- a/bittensor_cli/src/bittensor/utils.py +++ b/bittensor_cli/src/bittensor/utils.py @@ -581,7 +581,7 @@ def decode_hex_identity_dict(info_dictionary) -> dict[str, Any]: def get_decoded(data: str) -> str: """Decodes a hex-encoded string.""" try: - return bytes.fromhex(data[2:]).decode() + return hex_to_bytes(data).decode() except UnicodeDecodeError: print(f"Could not decode: {key}: {item}") @@ -1016,3 +1016,14 @@ def unlock_key( if print_out: err_console.print(f":cross_mark: [red]{err_msg}[/red]") return UnlockStatus(False, err_msg) + + +def hex_to_bytes(hex_str: str) -> bytes: + """ + Converts a hex-encoded string into bytes. Handles 0x-prefixed and non-prefixed hex-encoded strings. + """ + if hex_str.startswith("0x"): + bytes_result = bytes.fromhex(hex_str[2:]) + else: + bytes_result = bytes.fromhex(hex_str) + return bytes_result diff --git a/bittensor_cli/src/commands/subnets.py b/bittensor_cli/src/commands/subnets.py index 1d4620b7..51ce3708 100644 --- a/bittensor_cli/src/commands/subnets.py +++ b/bittensor_cli/src/commands/subnets.py @@ -28,6 +28,7 @@ render_table, update_metadata_table, unlock_key, + hex_to_bytes, ) if TYPE_CHECKING: @@ -155,12 +156,8 @@ async def _get_all_subnets_info(): hex_bytes_result = await subtensor.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", method="get_subnets_info", params=[] ) - try: - bytes_result = bytes.fromhex(hex_bytes_result[2:]) - except ValueError: - bytes_result = bytes.fromhex(hex_bytes_result) - return SubnetInfo.list_from_vec_u8(bytes_result) + return SubnetInfo.list_from_vec_u8(hex_to_bytes(hex_bytes_result)) if not reuse_last: subnets: list[SubnetInfo] diff --git a/bittensor_cli/src/commands/wallets.py b/bittensor_cli/src/commands/wallets.py index 69188053..322b9538 100644 --- a/bittensor_cli/src/commands/wallets.py +++ b/bittensor_cli/src/commands/wallets.py @@ -15,23 +15,19 @@ from fuzzywuzzy import fuzz from rich import box from rich.align import Align -from rich.prompt import Confirm, Prompt +from rich.prompt import Confirm from rich.table import Column, Table from rich.tree import Tree from rich.padding import Padding from rich.prompt import IntPrompt -from scalecodec import ScaleBytes -import scalecodec import typer -from bittensor_cli.src import TYPE_REGISTRY from bittensor_cli.src.bittensor import utils from bittensor_cli.src.bittensor.balances import Balance from bittensor_cli.src.bittensor.chain_data import ( DelegateInfo, NeuronInfoLite, StakeInfo, - custom_rpc_type_registry, decode_account_id, ) from bittensor_cli.src.bittensor.extrinsics.registration import ( @@ -46,7 +42,6 @@ RAO_PER_TAO, console, convert_blocks_to_time, - decode_scale_bytes, err_console, print_error, print_verbose, @@ -56,6 +51,7 @@ validate_coldkey_presence, retry_prompt, unlock_key, + hex_to_bytes, ) @@ -1176,7 +1172,7 @@ def _process_neurons_for_netuids( :return: netuids mapped to decoded neurons """ all_results = [ - (netuid, NeuronInfoLite.list_from_vec_u8(bytes.fromhex(result[2:]))) + (netuid, NeuronInfoLite.list_from_vec_u8(hex_to_bytes(result))) if result else (netuid, []) for netuid, result in netuids_with_all_neurons_hex_bytes