bittensor.utils.mock.subtensor_mock

Contents

bittensor.utils.mock.subtensor_mock#

Attributes#

Classes#

AxonServeCallParams

Axon serve chain call parameters.

PrometheusServeCallParams

Prometheus serve chain call parameters.

InfoDict

A Mapping is a generic container for associating key/value

AxonInfoDict

A Mapping is a generic container for associating key/value

PrometheusInfoDict

A Mapping is a generic container for associating key/value

MockSubtensorValue

MockMapResult

MockSystemState

dict() -> new empty dictionary

MockSubtensorState

dict() -> new empty dictionary

MockChainState

dict() -> new empty dictionary

MockSubtensor

A Mock Subtensor class for running tests.

Module Contents#

bittensor.utils.mock.subtensor_mock.__GLOBAL_MOCK_STATE__#
class bittensor.utils.mock.subtensor_mock.AxonServeCallParams[source]#

Bases: TypedDict

Axon serve chain call parameters.

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

version: int#
ip: int#
port: int#
ip_type: int#
netuid: int#
class bittensor.utils.mock.subtensor_mock.PrometheusServeCallParams[source]#

Bases: TypedDict

Prometheus serve chain call parameters.

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

version: int#
ip: int#
port: int#
ip_type: int#
netuid: int#
bittensor.utils.mock.subtensor_mock.BlockNumber#
class bittensor.utils.mock.subtensor_mock.InfoDict[source]#

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__.

classmethod default()[source]#
Abstractmethod:

__getitem__(key)[source]#
__setitem__(key, value)[source]#
__iter__()[source]#
__len__()[source]#
class bittensor.utils.mock.subtensor_mock.AxonInfoDict[source]#

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#
version: int#
ip: int#
port: int#
ip_type: int#
protocol: int#
placeholder1: int#
placeholder2: int#
classmethod default()[source]#
class bittensor.utils.mock.subtensor_mock.PrometheusInfoDict[source]#

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#
version: int#
ip: int#
port: int#
ip_type: int#
classmethod default()[source]#
class bittensor.utils.mock.subtensor_mock.MockSubtensorValue[source]#
value: Any | None#
class bittensor.utils.mock.subtensor_mock.MockMapResult(records=None)[source]#
Parameters:

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

records: list[tuple[MockSubtensorValue, MockSubtensorValue]] | None#
_records#
__iter__()[source]#
class bittensor.utils.mock.subtensor_mock.MockSystemState[source]#

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.MockSubtensorState[source]#

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.

Rho: dict[int, dict[BlockNumber, int]]#
Kappa: dict[int, dict[BlockNumber, int]]#
Difficulty: dict[int, dict[BlockNumber, int]]#
ImmunityPeriod: dict[int, dict[BlockNumber, int]]#
ValidatorBatchSize: dict[int, dict[BlockNumber, int]]#
Active: dict[int, dict[BlockNumber, bool]]#
Stake: dict[str, dict[str, dict[int, int]]]#
Delegates: dict[str, dict[int, float]]#
NetworksAdded: dict[int, dict[BlockNumber, bool]]#
class bittensor.utils.mock.subtensor_mock.MockChainState[source]#

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.

System: MockSystemState#
SubtensorModule: MockSubtensorState#
class bittensor.utils.mock.subtensor_mock.MockSubtensor(*args, **kwargs)[source]#

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.

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.

chain_state: MockChainState#
block_number: int#
classmethod reset()[source]#
Return type:

None

setup()[source]#
Return type:

None

__dict__#
get_block_hash(block_id)[source]#

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.

create_subnet(netuid)[source]#
Parameters:

netuid (int)

Return type:

None

set_difficulty(netuid, difficulty)[source]#
Parameters:
  • netuid (int)

  • difficulty (int)

Return type:

None

static _convert_to_balance(balance)[source]#
Parameters:

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

Return type:

bittensor.utils.balance.Balance

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

(success, err_msg)

Return type:

tuple[bool, Optional[str]]

Parameters:
sudo_force_set_balance#
do_block_step()[source]#
Return type:

None

_handle_type_default(name, params)[source]#
Parameters:
Return type:

object

commit(wallet, netuid, data)[source]#

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

get_commitment(netuid, uid, block=None)[source]#

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

query_subtensor(name, block=None, params=[])[source]#

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.

query_map_subtensor(name, block=None, params=[])[source]#

Note: Double map requires one param

Parameters:
Return type:

Optional[MockMapResult]

query_constant(module_name, constant_name, block=None)[source]#

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.

get_current_block()[source]#

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_balance(address, block=None)[source]#

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.

neuron_for_uid(uid, netuid, block=None)[source]#

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.

neurons(netuid, block=None)[source]#

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.

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

  • block_number (Optional[int])

Return type:

Any

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

  • hotkey (str)

  • block (Optional[int])

Return type:

AxonInfoDict

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

  • hotkey (str)

  • block (Optional[int])

Return type:

PrometheusInfoDict

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

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[bittensor.core.chain_data.NeuronInfo]

neurons_lite(netuid, block=None)[source]#

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.

get_transfer_fee(wallet, dest, value)[source]#

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.

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

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

static min_required_stake()[source]#

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

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

tuple[bool, Optional[str]]

do_set_weights(wallet, netuid, uids, vals, version_key, wait_for_inclusion=False, wait_for_finalization=True)[source]#
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_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#
Parameters:
Return type:

tuple[bool, Optional[str]]