Skip to content

Commit

Permalink
Merge pull request #244 from opentensor/feat/thewhaleking/use-hex-to-…
Browse files Browse the repository at this point in the history
…bytes-function

Use hex to bytes function
  • Loading branch information
thewhaleking authored Nov 14, 2024
2 parents 9d07839 + 88f645d commit 6ca679b
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 44 deletions.
7 changes: 3 additions & 4 deletions bittensor_cli/src/bittensor/async_substrate_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]]


Expand Down Expand Up @@ -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,
Expand Down
7 changes: 4 additions & 3 deletions bittensor_cli/src/bittensor/extrinsics/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
print_verbose,
print_error,
unlock_key,
hex_to_bytes,
)

if typing.TYPE_CHECKING:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down
29 changes: 5 additions & 24 deletions bittensor_cli/src/bittensor/subtensor_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
err_console,
decode_hex_identity_dict,
validate_chain_endpoint,
hex_to_bytes,
)


Expand Down Expand Up @@ -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 []

Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
13 changes: 12 additions & 1 deletion bittensor_cli/src/bittensor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Expand Down Expand Up @@ -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
7 changes: 2 additions & 5 deletions bittensor_cli/src/commands/subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
render_table,
update_metadata_table,
unlock_key,
hex_to_bytes,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -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]
Expand Down
10 changes: 3 additions & 7 deletions bittensor_cli/src/commands/wallets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -46,7 +42,6 @@
RAO_PER_TAO,
console,
convert_blocks_to_time,
decode_scale_bytes,
err_console,
print_error,
print_verbose,
Expand All @@ -56,6 +51,7 @@
validate_coldkey_presence,
retry_prompt,
unlock_key,
hex_to_bytes,
)


Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 6ca679b

Please sign in to comment.