bittensor.utils.mock.subtensor_mock

Contents

bittensor.utils.mock.subtensor_mock#

Attributes#

Classes#

AxonInfoDict

A Mapping is a generic container for associating key/value

InfoDict

A Mapping is a generic container for associating key/value

MockChainState

dict() -> new empty dictionary

MockMapResult

MockSubtensor

A Mock Subtensor class for running tests.

MockSubtensorState

dict() -> new empty dictionary

MockSubtensorValue

MockSystemState

dict() -> new empty dictionary

PrometheusInfoDict

A Mapping is a generic container for associating key/value

Module Contents#

class bittensor.utils.mock.subtensor_mock.AxonInfoDict#

Bases: InfoDict

A Mapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.

block: int#
classmethod default()#
ip: int#
ip_type: int#
placeholder1: int#
placeholder2: int#
port: int#
protocol: int#
version: int#
bittensor.utils.mock.subtensor_mock.BlockNumber#
class bittensor.utils.mock.subtensor_mock.InfoDict#

Bases: collections.abc.Mapping

A Mapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.

__getitem__(key)#
__iter__()#
__len__()#
__setitem__(key, value)#
classmethod default()#
Abstractmethod:

class bittensor.utils.mock.subtensor_mock.MockChainState#

Bases: TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Initialize self. See help(type(self)) for accurate signature.

SubtensorModule: MockSubtensorState#
System: MockSystemState#
class bittensor.utils.mock.subtensor_mock.MockMapResult(records=None)#
Parameters:

records (Optional[list[tuple[Union[Any, MockSubtensorValue], Union[Any, MockSubtensorValue]]]])

__iter__()#
_records#
records: list[tuple[MockSubtensorValue, MockSubtensorValue]] | None#
class bittensor.utils.mock.subtensor_mock.MockSubtensor(*args, **kwargs)#

Bases: bittensor.core.subtensor.Subtensor

A Mock Subtensor class for running tests. This should mock only methods that make queries to the chain. e.g. We mock Subtensor.query_subtensor instead of all query methods.

This class will also store a local (mock) state of the chain.

Initializes a Subtensor interface for interacting with the Bittensor blockchain.

Note

Currently subtensor defaults to the finney network. This will change in a future release.

We strongly encourage users to run their own local subtensor node whenever possible. This increases decentralization and resilience of the network. In a future release, local subtensor will become the default and the fallback to finney removed. Please plan ahead for this change. We will provide detailed instructions on how to run a local subtensor node in the documentation in a subsequent release.

Parameters:
  • network (Optional[str]) – The network name to connect to (e.g., finney, local). This can also be the chain endpoint (e.g., wss://entrypoint-finney.opentensor.ai:443) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.

  • config (Optional[bittensor.core.config.Config]) – Configuration object for the subtensor. If not provided, a default configuration is used.

  • _mock (bool) – If set to True, uses a mocked connection for testing purposes. Default is False.

  • log_verbose (bool) – Whether to enable verbose logging. If set to True, detailed log information about the connection and network operations will be provided. Default is True.

  • connection_timeout (int) – The maximum time in seconds to keep the connection alive. Default is 600.

  • websocket (websockets.sync.client.ClientConnection) – websockets sync (threading) client object connected to the network.

This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights.

static _convert_to_balance(balance)#
Parameters:

balance (Union[bittensor.utils.balance.Balance, float, int])

Return type:

bittensor.utils.balance.Balance

_get_axon_info(netuid, hotkey, block=None)#
Parameters:
  • netuid (int)

  • hotkey (str)

  • block (Optional[int])

Return type:

AxonInfoDict

static _get_most_recent_storage(storage, block_number=None)#
Parameters:
  • storage (dict[BlockNumber, Any])

  • block_number (Optional[int])

Return type:

Any

_get_prometheus_info(netuid, hotkey, block=None)#
Parameters:
  • netuid (int)

  • hotkey (str)

  • block (Optional[int])

Return type:

PrometheusInfoDict

_handle_type_default(name, params)#
Parameters:
Return type:

object

_neuron_subnet_exists(uid, netuid, block=None)#
Parameters:
  • uid (int)

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[bittensor.core.chain_data.NeuronInfo]

block_number: int#
chain_state: MockChainState#
close_code = None#
commit(wallet, netuid, data)#

Commits arbitrary data to the Bittensor network by publishing metadata.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the data.

  • netuid (int) – The unique identifier of the subnetwork.

  • data (str) – The data to be committed to the network.

Return type:

None

create_subnet(netuid)#
Parameters:

netuid (int)

Return type:

None

do_block_step()#
Return type:

None

do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
Parameters:
Return type:

tuple[bool, Optional[str]]

do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
Parameters:
Return type:

tuple[bool, Optional[str]]

do_set_weights(wallet, netuid, uids, vals, version_key, wait_for_inclusion=False, wait_for_finalization=True)#
Parameters:
  • wallet (bittensor_wallet.Wallet)

  • netuid (int)

  • uids (int)

  • vals (list[int])

  • version_key (int)

  • wait_for_inclusion (bool)

  • wait_for_finalization (bool)

Return type:

tuple[bool, Optional[str]]

do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)#
Parameters:
Return type:

tuple[bool, Optional[str], Optional[str]]

force_set_balance(ss58_address, balance=Balance(0))#
Returns:

(success, err_msg)

Return type:

tuple[bool, Optional[str]]

Parameters:
get_balance(address, block=None)#

Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.

Parameters:
  • address (str) – The Substrate address in ss58 format.

  • block (Optional[int]) – The blockchain block number at which to perform the query.

Returns:

The account balance at the specified block, represented as a Balance object.

Return type:

bittensor.utils.balance.Balance

This function is important for monitoring account holdings and managing financial transactions within the Bittensor ecosystem. It helps in assessing the economic status and capacity of network participants.

get_block_hash(block_id)#

Retrieves the hash of a specific block on the Bittensor blockchain. The block hash is a unique identifier representing the cryptographic hash of the block’s content, ensuring its integrity and immutability.

Parameters:

block_id (int) – The block number for which the hash is to be retrieved.

Returns:

The cryptographic hash of the specified block.

Return type:

str

The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.

get_commitment(netuid, uid, block=None)#

Retrieves the on-chain commitment for a specific neuron in the Bittensor network.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • uid (int) – The unique identifier of the neuron.

  • block (Optional[int]) – The block number to retrieve the commitment from. If None, the latest block is used. Default is None.

Returns:

The commitment data as a string.

Return type:

str

get_current_block()#

Returns the current block number on the Bittensor blockchain. This function provides the latest block number, indicating the most recent state of the blockchain.

Returns:

The current chain block number.

Return type:

int

Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on the blockchain. It serves as a reference point for network activities and data synchronization.

get_transfer_fee(wallet, dest, value)#

Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This function simulates the transfer to estimate the associated cost, taking into account the current network conditions and transaction complexity.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet from which the transfer is initiated.

  • dest (str) – The SS58 address of the destination account.

  • value (Union[bittensor.utils.balance.Balance, float, int]) – The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units.

Returns:

The estimated transaction fee for the transfer, represented as a Balance object.

Return type:

bittensor.utils.balance.Balance

Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the wallet has sufficient funds to cover both the transfer amount and the associated costs. This function provides a crucial tool for managing financial operations within the Bittensor network.

static min_required_stake()#

As the minimum required stake may change, this method allows us to dynamically update the amount in the mock without updating the tests

mock_substrate_interface#
mock_websocket#
neuron_for_uid(uid, netuid, block=None)#

Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron’s attributes, including its stake, rank, and operational status.

Parameters:
  • uid (Optional[int]) – The unique identifier of the neuron.

  • netuid (int) – The unique identifier of the subnet.

  • block (Optional[int]) – The blockchain block number for the query.

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

bittensor.core.chain_data.neuron_info.NeuronInfo

This function is crucial for analyzing individual neurons’ contributions and status within a specific subnet, offering insights into their roles in the network’s consensus and validation mechanisms.

neuron_for_uid_lite(uid, netuid, block=None)#
Parameters:
  • uid (int)

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[bittensor.core.chain_data.NeuronInfoLite]

neurons(netuid, block=None)#

Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet’s neuron population, including each neuron’s attributes and network interactions.

Parameters:
  • netuid (int) – The unique identifier of the subnet.

  • block (Optional[int]) – The blockchain block number for the query.

Returns:

A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.

Return type:

list[bittensor.core.chain_data.neuron_info.NeuronInfo]

Understanding the distribution and status of neurons within a subnet is key to comprehending the network’s decentralized structure and the dynamics of its consensus and governance processes.

neurons_lite(netuid, block=None)#

Retrieves a list of neurons in a ‘lite’ format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network participation.

Parameters:
  • netuid (int) – The unique identifier of the subnet.

  • block (Optional[int]) – The blockchain block number for the query.

Returns:

A list of simplified neuron information for the subnet.

Return type:

list[bittensor.core.chain_data.neuron_info_lite.NeuronInfoLite]

This function offers a quick overview of the neuron population within a subnet, facilitating efficient analysis of the network’s decentralized structure and neuron dynamics.

query_constant(module_name, constant_name, block=None)#

Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.

Parameters:
  • module_name (str) – The name of the module containing the constant.

  • constant_name (str) – The name of the constant to retrieve.

  • block (Optional[int]) – The blockchain block number at which to query the constant.

Returns:

The value of the constant if found, None otherwise.

Return type:

Optional[scalecodec.ScaleType]

Constants queried through this function can include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network’s operational parameters.

query_map_subtensor(name, block=None, params=None)#

Note: Double map requires one param

Parameters:
Return type:

Optional[MockMapResult]

query_subtensor(name, block=None, params=None)#

Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to retrieve specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific attributes.

Parameters:
  • name (str) – The name of the storage function to query.

  • block (Optional[int]) – The blockchain block number at which to perform the query.

  • params (Optional[list[object]]) – A list of parameters to pass to the query function.

Returns:

An object containing the requested data.

Return type:

query_response (scalecodec.ScaleType)

This query function is essential for accessing detailed information about the network and its neurons, providing valuable insights into the state and dynamics of the Bittensor ecosystem.

classmethod reset()#
Return type:

None

set_difficulty(netuid, difficulty)#
Parameters:
  • netuid (int)

  • difficulty (int)

Return type:

None

setup()#
Return type:

None

sudo_force_set_balance#
class bittensor.utils.mock.subtensor_mock.MockSubtensorState#

Bases: TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Initialize self. See help(type(self)) for accurate signature.

Active: dict[int, dict[BlockNumber, bool]]#
Delegates: dict[str, dict[int, float]]#
Difficulty: dict[int, dict[BlockNumber, int]]#
ImmunityPeriod: dict[int, dict[BlockNumber, int]]#
Kappa: dict[int, dict[BlockNumber, int]]#
NetworksAdded: dict[int, dict[BlockNumber, bool]]#
Rho: dict[int, dict[BlockNumber, int]]#
Stake: dict[str, dict[str, dict[int, int]]]#
ValidatorBatchSize: dict[int, dict[BlockNumber, int]]#
class bittensor.utils.mock.subtensor_mock.MockSubtensorValue#
value: Any | None#
class bittensor.utils.mock.subtensor_mock.MockSystemState#

Bases: TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Initialize self. See help(type(self)) for accurate signature.

Account: dict[str, dict[int, int]]#
class bittensor.utils.mock.subtensor_mock.PrometheusInfoDict#

Bases: InfoDict

A Mapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.

block: int#
classmethod default()#
ip: int#
ip_type: int#
port: int#
version: int#
bittensor.utils.mock.subtensor_mock.__GLOBAL_MOCK_STATE__#