bittensor#
Subpackages#
Submodules#
Attributes#
Metagraph class that uses |
|
|
Creates an initialised AsyncSubtensor object. |
Exceptions#
This exception is raised when the request is blacklisted. |
|
Error for any chain connection related errors. |
|
Base error for any chain related errors. |
|
Error for any chain query related errors. |
|
Error for any chain transaction related errors. |
|
Error raised when an identity transaction fails. |
|
This exception is raised when the requested function fails on the server. Indicates a server error. |
|
In place of YAMLError |
|
This exception is raised when the request name is invalid. Usually indicates a broken URL. |
|
Error raised when metadata commitment transaction fails. |
|
Error raised when a nomination transaction fails. |
|
Error raised when a hotkey you are trying to stake to is not a delegate. |
|
Error raised when a neuron is not registered, and the transaction requires it to be. |
|
This exception is raised when the request is not verified. |
|
This exception is raised when the response headers cannot be updated. |
|
This exception is raised when the request priority is not met. |
|
Error raised when a neuron registration transaction fails. |
|
This exception is raised when the requested function cannot be executed. Indicates a server error. |
|
Error raised when a stake transaction fails. |
|
Common base class for all non-exit exceptions. |
|
This exception is raised when the request headers are unable to be parsed into the synapse type. |
|
Error raised when a transfer transaction fails. |
|
This exception is raised when the request name is not found in the Axon's forward_fns dictionary. |
|
Error raised when an unstake transaction fails. |
Classes#
Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls. |
|
Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls. |
|
The |
|
The AxonInfo class represents information about an axon endpoint in the bittensor network. This includes |
|
Represents the bittensor balance of the wallet, stored as rao (int). |
|
Implementation of the config class, which manages the configuration of different Bittensor modules. |
|
A Config with a set of default values. |
|
Dataclass for delegate information. For a lighter version of this class, see |
|
The Dendrite class represents the abstracted implementation of a network client module. |
|
Dataclass representing IP information. |
|
A Mock Subtensor class for running tests. |
|
Represents the metadata of a neuron including keys, UID, stake, rankings, and other attributes. |
|
NeuronInfoLite is a dataclass representing neuron metadata without weights and bonds. |
|
Base threadpool executor with a priority queue. |
|
Dataclass representing information related to Prometheus. |
|
This TypedDict represents the data structure for a proposal vote in the Senate. |
|
Dataclass for representing stake information linked to hotkey and coldkey pairs. |
|
The |
|
This class represents the hyperparameters for a subnet. |
|
Dataclass for subnet info. |
|
This class is not used within the bittensor package, but is actively used by the community. |
|
The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, |
|
Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes). |
|
Represents a Tensor object. |
|
TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process. |
Functions#
|
|
|
Creates an initialised AsyncSubtensor object. |
|
Enables or disables debug logging. |
|
Returns the explorer url for the given block hash and network. |
|
|
|
Enables or disables info logging. |
|
Converts a ss58 address to a bytes object. |
|
|
|
Converts a string to a boolean value. |
|
Enables or disables trace logging. |
|
Deprecated, kept for backwards compatibility. Use check_version() instead. |
|
Enables or disables warning logging. |
Package Contents#
- class bittensor.AsyncSubtensor(network=DEFAULT_NETWORK)#
Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls.
- Parameters:
network (str)
- async __aenter__()#
- async __aexit__(exc_type, exc_val, exc_tb)#
- __str__()#
- async blocks_since_last_update(netuid, uid)#
Returns the number of blocks since the last update for a specific UID in the subnetwork.
- async bonds(netuid, block_hash=None, reuse_block=False)#
Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.
- Parameters:
- Returns:
List of tuples mapping each neuron’s UID to its bonds with other neurons.
- Return type:
Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.
- async commit_reveal_enabled(netuid, block_hash=None)#
Check if commit-reveal mechanism is enabled for a given network at a specific block.
- Parameters:
- Returns:
Returns the integer value of the hyperparameter if available; otherwise, returns None.
- Return type:
(bool)
- async commit_weights(wallet, netuid, salt, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Commits a hash of the neuron’s weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron’s current weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the weights.
netuid (int) – The unique identifier of the subnet.
salt (list[int]) – list of randomly generated integers as salt to generated weighted hash.
uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being committed.
weights (np.ndarray) – NumPy array of weight values corresponding to each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to commit weights. Default is
5
.
- Returns:
True
if the weight commitment is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, enhancing transparency and accountability within the Bittensor network.
- async does_hotkey_exist(hotkey_ss58, block_hash=None, reuse_block=False)#
Returns true if the hotkey is known by the chain and there are accounts.
- Parameters:
- Returns:
True if the hotkey is known by the chain and there are accounts, False otherwise.
- Return type:
- async encode_params(call_definition, params)#
Returns a hex encoded string of the params using their types.
- async filter_netuids_by_registered_hotkeys(all_netuids, filter_for_netuids, all_hotkeys, block_hash=None, reuse_block=False)#
Filters a given list of all netuids for certain specified netuids and hotkeys
- Parameters:
all_netuids (Iterable[int]) – A list of netuids to filter.
filter_for_netuids (Iterable[int]) – A subset of all_netuids to filter from the main list
all_hotkeys (Iterable[Wallet]) – Hotkeys to filter from the main list
block_hash (str) – hash of the blockchain block number at which to perform the query.
reuse_block (bool) – whether to reuse the last-used blockchain hash when retrieving info.
- Returns:
The filtered list of netuids.
- Return type:
- async get_balance(*addresses, block_hash=None, reuse_block=False)#
Retrieves the balance for given coldkey(s)
- async get_block_hash(block_id=None)#
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:
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.
- async get_children(hotkey, netuid)#
This method retrieves the children of a given hotkey and netuid. It queries the SubtensorModule’s ChildKeys storage function to get the children and formats them before returning as a tuple.
- async 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:
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.
- async get_delegate_identities(block_hash=None, reuse_block=False)#
Fetches delegates identities from the chain and GitHub. Preference is given to chain data, and missing info is filled-in by the info from GitHub. At some point, we want to totally move away from fetching this info from GitHub, but chain data is still limited in that regard.
- async get_delegated(coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves a list of delegates and their associated stakes for a given coldkey. This function identifies the delegates that a specific account has staked tokens on.
- Parameters:
- Returns:
A list of tuples, each containing a delegate’s information and staked amount.
- Return type:
list[tuple[bittensor.core.chain_data.DelegateInfo, bittensor.utils.balance.Balance]]
This function is important for account holders to understand their stake allocations and their involvement in the network’s delegation and consensus mechanisms.
- async get_delegates(block_hash=None, reuse_block=False)#
Fetches all delegates on the chain
- Parameters:
- Returns:
List of DelegateInfo objects, or an empty list if there are no delegates.
- Return type:
- async get_existential_deposit(block_hash=None, reuse_block=False)#
Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped to conserve network resources.
- Parameters:
- Returns:
The existential deposit amount.
- Return type:
The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts.
- async get_hotkey_owner(hotkey_ss58, block_hash=None, reuse_block=False)#
Retrieves the owner of the given hotkey at a specific block hash. This function queries the blockchain for the owner of the provided hotkey. If the hotkey does not exist at the specified block hash, it returns None.
- Parameters:
- Returns:
The SS58 address of the owner if the hotkey exists, or None if it doesn’t.
- Return type:
Optional[str]
- async get_hyperparameter(param_name, netuid, block_hash=None, reuse_block=False)#
Retrieves a specified hyperparameter for a specific subnet.
- Parameters:
- Returns:
The value of the specified hyperparameter if the subnet exists, or None
- Return type:
Optional[Any]
- async get_netuids_for_hotkey(hotkey_ss58, block_hash=None, reuse_block=False)#
Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with the hotkey is active.
- Parameters:
- Returns:
A list of netuids where the neuron is a member.
- Return type:
- async get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block_hash=None, reuse_block=False)#
Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem.
- async get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves stake information associated with a specific coldkey and hotkey.
- Parameters:
- Returns:
Stake Balance for the given coldkey and hotkey
- Return type:
- async get_stake_info_for_coldkey(coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates.
- Parameters:
- Returns:
A list of StakeInfo objects detailing the stake allocations for the account.
- Return type:
Stake information is vital for account holders to assess their investment and participation in the network’s delegation and consensus processes.
- async get_subnet_burn_cost(block_hash=None, reuse_block=False)#
Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the amount of Tao that needs to be locked or burned to establish a new subnet.
- Parameters:
- Returns:
The burn cost for subnet registration.
- Return type:
The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling the proliferation of subnets and ensuring their commitment to the network’s long-term viability.
- async get_subnet_hyperparameters(netuid, block_hash=None, reuse_block=False)#
Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.
- Parameters:
- Returns:
The subnet’s hyperparameters, or None if not available.
- Return type:
Optional[Union[list, bittensor.core.chain_data.SubnetHyperparameters]]
Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network’s consensus and incentive mechanisms.
- async get_subnet_reveal_period_epochs(netuid, block_hash=None)#
Retrieve the SubnetRevealPeriodEpochs hyperparameter.
- async get_subnets(block_hash=None, reuse_block=False)#
Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.
- Parameters:
- Returns:
A list of subnet netuids.
- Return type:
This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into its diversity and scale.
- async get_total_stake_for_coldkey(*ss58_addresses, block_hash=None, reuse_block=False)#
Returns the total stake held on a coldkey.
- async get_total_stake_for_hotkey(*ss58_addresses, block_hash=None, reuse_block=False)#
Returns the total stake held on a hotkey.
- async get_total_subnets(block_hash=None, reuse_block=False)#
Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.
- Parameters:
- Returns:
The total number of subnets in the network.
- Return type:
Optional[str]
Understanding the total number of subnets is essential for assessing the network’s growth and the extent of its decentralized infrastructure.
- async 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:
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.
- async get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block_hash=None, reuse_block=False)#
Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.
- Parameters:
- Returns:
The UID of the neuron if it is registered on the subnet,
None
otherwise.- Return type:
Optional[int]
The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.
- async get_vote_data(proposal_hash, block_hash=None, reuse_block=False)#
Retrieves the voting data for a specific proposal on the Bittensor blockchain. This data includes information about how senate members have voted on the proposal.
- Parameters:
- Returns:
An object containing the proposal’s voting data, or None if not found.
- Return type:
Optional[ProposalVoteData]
This function is important for tracking and understanding the decision-making processes within the Bittensor network, particularly how proposals are received and acted upon by the governing body.
- async is_hotkey_delegate(hotkey_ss58, block_hash=None, reuse_block=False)#
Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if the neuron associated with the hotkey is part of the network’s delegation system.
- Parameters:
- Returns:
True if the hotkey is a delegate, False otherwise.
- Return type:
Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.
- async is_hotkey_registered(netuid, hotkey_ss58, block_hash=None, reuse_block=False)#
Checks to see if the hotkey is registered on a given netuid
- async is_hotkey_registered_any(hotkey_ss58, block_hash=None, reuse_block=False)#
Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on any subnet, False otherwise.- Return type:
This function is essential for determining the network-wide presence and participation of a neuron.
- async neuron_for_uid(uid, netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
Detailed information about the neuron if found, a null neuron otherwise
- Return type:
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.
- async neurons(netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
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.
- async neurons_lite(netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
A list of simplified neuron information for the subnet.
- Return type:
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.
- async pow_register(wallet, netuid, processors, update_interval, output_in_place, verbose, use_cuda, dev_id, threads_per_block)#
Register neuron.
- async query_identity(key, block_hash=None, reuse_block=False)#
Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves detailed identity information about a specific neuron, which is a crucial aspect of the network’s decentralized identity and governance system.
- Parameters:
- Returns:
An object containing the identity information of the neuron if found,
None
otherwise.- Return type:
The identity information can include various attributes such as the neuron’s stake, rank, and other network-specific details, providing insights into the neuron’s role and status within the Bittensor network.
Note
See the Bittensor CLI documentation for supported identity parameters.
- async query_runtime_api(runtime_api, method, params, block_hash=None, reuse_block=False)#
Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to interact with specific runtime methods and decode complex data types.
- Parameters:
runtime_api (str) – The name of the runtime API to query.
method (str) – The specific method within the runtime API to call.
params (Optional[Union[list[list[int]], dict[str, int]]]) – The parameters to pass to the method call.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The Scale Bytes encoded result from the runtime API call, or
None
if the call fails.- Return type:
Optional[str]
This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network’s runtime environment.
- async register(wallet, netuid, block_hash=None, wait_for_inclusion=True, wait_for_finalization=True)#
Register neuron by recycling some TAO.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance.
netuid (int) – Subnet uniq id.
block_hash (Optional[str]) – The hash of the blockchain block for the query.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.
- Returns:
True if registration was successful, otherwise False.
- Return type:
- async root_set_weights(wallet, netuids, weights)#
Set weights for root network.
- async set_weights(wallet, netuid, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Sets the inter-neuronal weights for the specified neuron. This process involves specifying the influence or trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor’s decentralized learning architecture.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron setting the weights.
netuid (int) – The unique identifier of the subnet.
uids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.
weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to set weights. Default is
5
.
- Returns:
True
if the setting of weights is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function is crucial in shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.
- async sign_and_send_extrinsic(call, wallet, wait_for_inclusion=True, wait_for_finalization=False)#
Helper method to sign and submit an extrinsic call to chain.
- Parameters:
call (scalecodec.types.GenericCall) – a prepared Call object
wallet (bittensor_wallet.Wallet) – the wallet whose coldkey will be used to sign the extrinsic
wait_for_inclusion (bool) – whether to wait until the extrinsic call is included on the chain
wait_for_finalization (bool) – whether to wait until the extrinsic call is finalized on the chain
- Returns:
(success, error message)
- Return type:
- async subnet_exists(netuid, block_hash=None, reuse_block=False)#
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
- Parameters:
- Returns:
True if the subnet exists, False otherwise.
- Return type:
This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network’s structure and composition.
- substrate#
- async transfer(wallet, destination, amount, transfer_all)#
Transfer token of amount to destination.
- Parameters:
- Returns:
True if the transferring was successful, otherwise False.
- Return type:
- async weights(netuid, block_hash=None, reuse_block=False)#
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron’s UID to the weights it assigns to other neurons, reflecting the network’s trust and value assignment mechanisms.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its assigned weights.
- Return type:
The weight distribution is a key factor in the network’s consensus algorithm and the ranking of neurons, influencing their influence and reward allocation within the subnet.
- class bittensor.AsyncSubtensor(network=DEFAULT_NETWORK)#
Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls.
- Parameters:
network (str)
- async __aenter__()#
- async __aexit__(exc_type, exc_val, exc_tb)#
- __str__()#
- async blocks_since_last_update(netuid, uid)#
Returns the number of blocks since the last update for a specific UID in the subnetwork.
- async bonds(netuid, block_hash=None, reuse_block=False)#
Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.
- Parameters:
- Returns:
List of tuples mapping each neuron’s UID to its bonds with other neurons.
- Return type:
Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.
- async commit_reveal_enabled(netuid, block_hash=None)#
Check if commit-reveal mechanism is enabled for a given network at a specific block.
- Parameters:
- Returns:
Returns the integer value of the hyperparameter if available; otherwise, returns None.
- Return type:
(bool)
- async commit_weights(wallet, netuid, salt, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Commits a hash of the neuron’s weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron’s current weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the weights.
netuid (int) – The unique identifier of the subnet.
salt (list[int]) – list of randomly generated integers as salt to generated weighted hash.
uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being committed.
weights (np.ndarray) – NumPy array of weight values corresponding to each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to commit weights. Default is
5
.
- Returns:
True
if the weight commitment is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, enhancing transparency and accountability within the Bittensor network.
- async does_hotkey_exist(hotkey_ss58, block_hash=None, reuse_block=False)#
Returns true if the hotkey is known by the chain and there are accounts.
- Parameters:
- Returns:
True if the hotkey is known by the chain and there are accounts, False otherwise.
- Return type:
- async encode_params(call_definition, params)#
Returns a hex encoded string of the params using their types.
- async filter_netuids_by_registered_hotkeys(all_netuids, filter_for_netuids, all_hotkeys, block_hash=None, reuse_block=False)#
Filters a given list of all netuids for certain specified netuids and hotkeys
- Parameters:
all_netuids (Iterable[int]) – A list of netuids to filter.
filter_for_netuids (Iterable[int]) – A subset of all_netuids to filter from the main list
all_hotkeys (Iterable[Wallet]) – Hotkeys to filter from the main list
block_hash (str) – hash of the blockchain block number at which to perform the query.
reuse_block (bool) – whether to reuse the last-used blockchain hash when retrieving info.
- Returns:
The filtered list of netuids.
- Return type:
- async get_balance(*addresses, block_hash=None, reuse_block=False)#
Retrieves the balance for given coldkey(s)
- async get_block_hash(block_id=None)#
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:
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.
- async get_children(hotkey, netuid)#
This method retrieves the children of a given hotkey and netuid. It queries the SubtensorModule’s ChildKeys storage function to get the children and formats them before returning as a tuple.
- async 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:
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.
- async get_delegate_identities(block_hash=None, reuse_block=False)#
Fetches delegates identities from the chain and GitHub. Preference is given to chain data, and missing info is filled-in by the info from GitHub. At some point, we want to totally move away from fetching this info from GitHub, but chain data is still limited in that regard.
- async get_delegated(coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves a list of delegates and their associated stakes for a given coldkey. This function identifies the delegates that a specific account has staked tokens on.
- Parameters:
- Returns:
A list of tuples, each containing a delegate’s information and staked amount.
- Return type:
list[tuple[bittensor.core.chain_data.DelegateInfo, bittensor.utils.balance.Balance]]
This function is important for account holders to understand their stake allocations and their involvement in the network’s delegation and consensus mechanisms.
- async get_delegates(block_hash=None, reuse_block=False)#
Fetches all delegates on the chain
- Parameters:
- Returns:
List of DelegateInfo objects, or an empty list if there are no delegates.
- Return type:
- async get_existential_deposit(block_hash=None, reuse_block=False)#
Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped to conserve network resources.
- Parameters:
- Returns:
The existential deposit amount.
- Return type:
The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts.
- async get_hotkey_owner(hotkey_ss58, block_hash=None, reuse_block=False)#
Retrieves the owner of the given hotkey at a specific block hash. This function queries the blockchain for the owner of the provided hotkey. If the hotkey does not exist at the specified block hash, it returns None.
- Parameters:
- Returns:
The SS58 address of the owner if the hotkey exists, or None if it doesn’t.
- Return type:
Optional[str]
- async get_hyperparameter(param_name, netuid, block_hash=None, reuse_block=False)#
Retrieves a specified hyperparameter for a specific subnet.
- Parameters:
- Returns:
The value of the specified hyperparameter if the subnet exists, or None
- Return type:
Optional[Any]
- async get_netuids_for_hotkey(hotkey_ss58, block_hash=None, reuse_block=False)#
Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with the hotkey is active.
- Parameters:
- Returns:
A list of netuids where the neuron is a member.
- Return type:
- async get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block_hash=None, reuse_block=False)#
Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem.
- async get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves stake information associated with a specific coldkey and hotkey.
- Parameters:
- Returns:
Stake Balance for the given coldkey and hotkey
- Return type:
- async get_stake_info_for_coldkey(coldkey_ss58, block_hash=None, reuse_block=False)#
Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates.
- Parameters:
- Returns:
A list of StakeInfo objects detailing the stake allocations for the account.
- Return type:
Stake information is vital for account holders to assess their investment and participation in the network’s delegation and consensus processes.
- async get_subnet_burn_cost(block_hash=None, reuse_block=False)#
Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the amount of Tao that needs to be locked or burned to establish a new subnet.
- Parameters:
- Returns:
The burn cost for subnet registration.
- Return type:
The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling the proliferation of subnets and ensuring their commitment to the network’s long-term viability.
- async get_subnet_hyperparameters(netuid, block_hash=None, reuse_block=False)#
Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.
- Parameters:
- Returns:
The subnet’s hyperparameters, or None if not available.
- Return type:
Optional[Union[list, bittensor.core.chain_data.SubnetHyperparameters]]
Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network’s consensus and incentive mechanisms.
- async get_subnet_reveal_period_epochs(netuid, block_hash=None)#
Retrieve the SubnetRevealPeriodEpochs hyperparameter.
- async get_subnets(block_hash=None, reuse_block=False)#
Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.
- Parameters:
- Returns:
A list of subnet netuids.
- Return type:
This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into its diversity and scale.
- async get_total_stake_for_coldkey(*ss58_addresses, block_hash=None, reuse_block=False)#
Returns the total stake held on a coldkey.
- async get_total_stake_for_hotkey(*ss58_addresses, block_hash=None, reuse_block=False)#
Returns the total stake held on a hotkey.
- async get_total_subnets(block_hash=None, reuse_block=False)#
Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.
- Parameters:
- Returns:
The total number of subnets in the network.
- Return type:
Optional[str]
Understanding the total number of subnets is essential for assessing the network’s growth and the extent of its decentralized infrastructure.
- async 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:
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.
- async get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block_hash=None, reuse_block=False)#
Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.
- Parameters:
- Returns:
The UID of the neuron if it is registered on the subnet,
None
otherwise.- Return type:
Optional[int]
The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.
- async get_vote_data(proposal_hash, block_hash=None, reuse_block=False)#
Retrieves the voting data for a specific proposal on the Bittensor blockchain. This data includes information about how senate members have voted on the proposal.
- Parameters:
- Returns:
An object containing the proposal’s voting data, or None if not found.
- Return type:
Optional[ProposalVoteData]
This function is important for tracking and understanding the decision-making processes within the Bittensor network, particularly how proposals are received and acted upon by the governing body.
- async is_hotkey_delegate(hotkey_ss58, block_hash=None, reuse_block=False)#
Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if the neuron associated with the hotkey is part of the network’s delegation system.
- Parameters:
- Returns:
True if the hotkey is a delegate, False otherwise.
- Return type:
Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.
- async is_hotkey_registered(netuid, hotkey_ss58, block_hash=None, reuse_block=False)#
Checks to see if the hotkey is registered on a given netuid
- async is_hotkey_registered_any(hotkey_ss58, block_hash=None, reuse_block=False)#
Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on any subnet, False otherwise.- Return type:
This function is essential for determining the network-wide presence and participation of a neuron.
- async neuron_for_uid(uid, netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
Detailed information about the neuron if found, a null neuron otherwise
- Return type:
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.
- async neurons(netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
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.
- async neurons_lite(netuid, block_hash=None, reuse_block=False)#
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:
- Returns:
A list of simplified neuron information for the subnet.
- Return type:
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.
- async pow_register(wallet, netuid, processors, update_interval, output_in_place, verbose, use_cuda, dev_id, threads_per_block)#
Register neuron.
- async query_identity(key, block_hash=None, reuse_block=False)#
Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves detailed identity information about a specific neuron, which is a crucial aspect of the network’s decentralized identity and governance system.
- Parameters:
- Returns:
An object containing the identity information of the neuron if found,
None
otherwise.- Return type:
The identity information can include various attributes such as the neuron’s stake, rank, and other network-specific details, providing insights into the neuron’s role and status within the Bittensor network.
Note
See the Bittensor CLI documentation for supported identity parameters.
- async query_runtime_api(runtime_api, method, params, block_hash=None, reuse_block=False)#
Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to interact with specific runtime methods and decode complex data types.
- Parameters:
runtime_api (str) – The name of the runtime API to query.
method (str) – The specific method within the runtime API to call.
params (Optional[Union[list[list[int]], dict[str, int]]]) – The parameters to pass to the method call.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The Scale Bytes encoded result from the runtime API call, or
None
if the call fails.- Return type:
Optional[str]
This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network’s runtime environment.
- async register(wallet, netuid, block_hash=None, wait_for_inclusion=True, wait_for_finalization=True)#
Register neuron by recycling some TAO.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance.
netuid (int) – Subnet uniq id.
block_hash (Optional[str]) – The hash of the blockchain block for the query.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.
- Returns:
True if registration was successful, otherwise False.
- Return type:
- async root_set_weights(wallet, netuids, weights)#
Set weights for root network.
- async set_weights(wallet, netuid, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Sets the inter-neuronal weights for the specified neuron. This process involves specifying the influence or trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor’s decentralized learning architecture.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron setting the weights.
netuid (int) – The unique identifier of the subnet.
uids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.
weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to set weights. Default is
5
.
- Returns:
True
if the setting of weights is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function is crucial in shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.
- async sign_and_send_extrinsic(call, wallet, wait_for_inclusion=True, wait_for_finalization=False)#
Helper method to sign and submit an extrinsic call to chain.
- Parameters:
call (scalecodec.types.GenericCall) – a prepared Call object
wallet (bittensor_wallet.Wallet) – the wallet whose coldkey will be used to sign the extrinsic
wait_for_inclusion (bool) – whether to wait until the extrinsic call is included on the chain
wait_for_finalization (bool) – whether to wait until the extrinsic call is finalized on the chain
- Returns:
(success, error message)
- Return type:
- async subnet_exists(netuid, block_hash=None, reuse_block=False)#
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
- Parameters:
- Returns:
True if the subnet exists, False otherwise.
- Return type:
This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network’s structure and composition.
- substrate#
- async transfer(wallet, destination, amount, transfer_all)#
Transfer token of amount to destination.
- Parameters:
- Returns:
True if the transferring was successful, otherwise False.
- Return type:
- async weights(netuid, block_hash=None, reuse_block=False)#
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron’s UID to the weights it assigns to other neurons, reflecting the network’s trust and value assignment mechanisms.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its assigned weights.
- Return type:
The weight distribution is a key factor in the network’s consensus algorithm and the ranking of neurons, influencing their influence and reward allocation within the subnet.
- class bittensor.Axon(wallet=None, config=None, port=None, ip=None, external_ip=None, external_port=None, max_workers=None)#
The
Axon
class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network.This class is responsible for managing incoming requests from other neurons and implements various mechanisms to ensure efficient and secure network interactions.
An axon relies on a FastAPI router to create endpoints for different message types. These endpoints are crucial for handling various request types that a neuron might receive. The class is designed to be flexible and customizable, allowing users to specify custom rules for forwarding, blacklisting, prioritizing, and verifying incoming requests. The class also includes internal mechanisms to manage a thread pool, supporting concurrent handling of requests with defined priority levels.
Methods in this class are equipped to deal with incoming requests from various scenarios in the network and serve as the server face for a neuron. It accepts multiple arguments, like wallet, configuration parameters, ip address, server binding port, external ip, external port and max workers. Key methods involve managing and operating the FastAPI application router, including the attachment and operation of endpoints.
Key Features:
FastAPI router integration for endpoint creation and management.
Customizable request handling including forwarding, blacklisting, and prioritization.
Verification of incoming requests against custom-defined functions.
Thread pool management for concurrent request handling.
Command-line argument support for user-friendly program interaction.
Example Usage:
import bittensor # Define your custom synapse class class MySynapse( bittensor.Synapse ): input: int = 1 output: int = None # Define a custom request forwarding function using your synapse class def forward( synapse: MySynapse ) -> MySynapse: # Apply custom logic to synapse and return it synapse.output = 2 return synapse # Define a custom request verification function def verify_my_synapse( synapse: MySynapse ): # Apply custom verification logic to synapse # Optionally raise Exception assert synapse.input == 1 ... # Define a custom request blacklist function def blacklist_my_synapse( synapse: MySynapse ) -> bool: # Apply custom blacklist return False ( if non blacklisted ) or True ( if blacklisted ) # Define a custom request priority function def prioritize_my_synapse( synapse: MySynapse ) -> float: # Apply custom priority return 1.0 # Initialize Axon object with a custom configuration my_axon = bittensor.Axon( config=my_config, wallet=my_wallet, port=9090, ip="192.0.2.0", external_ip="203.0.113.0", external_port=7070 ) # Attach the endpoint with the specified verification and forward functions. my_axon.attach( forward_fn = forward_my_synapse, verify_fn = verify_my_synapse, blacklist_fn = blacklist_my_synapse, priority_fn = prioritize_my_synapse ) # Serve and start your axon. my_axon.serve( netuid = ... subtensor = ... ).start() # If you have multiple forwarding functions, you can chain attach them. my_axon.attach( forward_fn = forward_my_synapse, verify_fn = verify_my_synapse, blacklist_fn = blacklist_my_synapse, priority_fn = prioritize_my_synapse ).attach( forward_fn = forward_my_synapse_2, verify_fn = verify_my_synapse_2, blacklist_fn = blacklist_my_synapse_2, priority_fn = prioritize_my_synapse_2 ).serve( netuid = ... subtensor = ... ).start()
- Parameters:
wallet (Optional[bittensor_wallet.Wallet]) – Wallet with hotkey and coldkeypub.
config (Optional[bittensor.core.config.Config]) – Configuration parameters for the axon.
port (Optional[int]) – Port for server binding.
ip (Optional[str]) – Binding IP address.
external_ip (Optional[str]) – External IP address to broadcast.
external_port (Optional[int]) – External port to broadcast.
max_workers (Optional[int]) – Number of active threads for request handling.
- Returns:
An instance of the axon class configured as per the provided arguments.
- Return type:
Note
This class is a core part of Bittensor’s decentralized network for machine intelligence, allowing neurons to communicate effectively and securely.
- Importance and Functionality
- Endpoint Registration
This method dynamically registers API endpoints based on the Synapse used, allowing the Axon to respond to specific types of requests and synapses.
- Customization of Request Handling
By attaching different functions, the Axon can customize how it handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable to various network scenarios.
- Security and Efficiency
The method contributes to both the security (via verification and blacklisting) and efficiency (via prioritization) of request handling, which are crucial in a decentralized network environment.
- Flexibility
The ability to define custom functions for different aspects of request handling provides great flexibility, allowing the Axon to be tailored to specific needs and use cases within the Bittensor network.
- Error Handling and Validation
The method ensures that the attached functions meet the required signatures, providing error handling to prevent runtime issues.
Creates a new bittensor.Axon object from passed arguments.
- Parameters:
config (
Optional[bittensor.core.config.Config]
) – bittensor.Axon.config()wallet (
Optional[bittensor_wallet.Wallet]
) – bittensor wallet with hotkey and coldkeypub.port (
Optional[int]
) – Binding port.ip (
Optional[str]
) – Binding ip.external_ip (
Optional[str]
) – The external ip of the server to broadcast to the network.external_port (
Optional[int]
) – The external port of the server to broadcast to the network.max_workers (
Optional[int]
) – Used to create the threadpool if not passed, specifies the number of active threads servicing requests.
- __del__()#
This magic method is called when the Axon object is about to be destroyed. It ensures that the Axon server shuts down properly.
- __repr__()#
Provides a machine-readable (unambiguous) representation of the Axon instance. It is made identical to __str__ in this case.
- Return type:
- classmethod add_args(parser, prefix=None)#
Adds AxonServer-specific command-line arguments to the argument parser.
- Parameters:
parser (argparse.ArgumentParser) – Argument parser to which the arguments will be added.
prefix (Optional[str]) – Prefix to add to the argument names. Defaults to None.
Note
Environment variables are used to define default values for the arguments.
- app#
- attach(forward_fn, blacklist_fn=None, priority_fn=None, verify_fn=None)#
Attaches custom functions to the Axon server for handling incoming requests. This method enables the
Axon
to define specific behaviors for request forwarding, verification, blacklisting, and prioritization, thereby customizing its interaction within the Bittensor network.Registers an API endpoint to the FastAPI application router. It uses the name of the first argument of the
forward_fn()
function as the endpoint name.The
attach()
method in the Bittensor framework’s axon class is a crucial function for registering API endpoints to the Axon’s FastAPI application router. This method allows the Axon server to define how it handles incoming requests by attaching functions for forwarding, verifying, blacklisting, and prioritizing requests. It’s a key part of customizing the server’s behavior and ensuring efficient and secure handling of requests within the Bittensor network.- Parameters:
forward_fn (Callable) – Function to be called when the API endpoint is accessed. It should have at least one argument.
blacklist_fn (Optional[Callable]) – Function to filter out undesired requests. It should take the same arguments as
forward_fn()
and return a boolean value. Defaults toNone
, meaning no blacklist filter will be used.priority_fn (Optional[Callable]) – Function to rank requests based on their priority. It should take the same arguments as
forward_fn()
and return a numerical value representing the request’s priority. Defaults toNone
, meaning no priority sorting will be applied.verify_fn (Optional[Callable]) – Function to verify requests. It should take the same arguments as
forward_fn()
and return a boolean value. IfNone
,self.default_verify()
function will be used.
- Return type:
Note
The methods
forward_fn()
,blacklist_fn()
,priority_fn()
, andverify_fn()
should be designed to receive the same parameters.- Raises:
AssertionError – If
forward_fn()
does not have the signature:forward( synapse: YourSynapse ) -> synapse
.AssertionError – If
blacklist_fn()
does not have the signature:blacklist( synapse: YourSynapse ) -> bool
.AssertionError – If
priority_fn()
does not have the signature:priority( synapse: YourSynapse ) -> float
.AssertionError – If
verify_fn()
does not have the signature:verify( synapse: YourSynapse ) -> None
.
- Returns:
Returns the instance of the AxonServer class for potential method chaining.
- Return type:
self
- Parameters:
forward_fn (Callable)
blacklist_fn (Optional[Callable])
priority_fn (Optional[Callable])
verify_fn (Optional[Callable])
Example Usage:
def forward_custom(synapse: MyCustomSynapse) -> MyCustomSynapse: # Custom logic for processing the request return synapse def blacklist_custom(synapse: MyCustomSynapse) -> tuple[bool, str]: return True, "Allowed!" def priority_custom(synapse: MyCustomSynapse) -> float: return 1.0 def verify_custom(synapse: MyCustomSynapse): # Custom logic for verifying the request pass my_axon = bittensor.Axon(...) my_axon.attach(forward_fn=forward_custom, verify_fn=verify_custom)
Note
The
attach()
method is fundamental in setting up the Axon server’s request handling capabilities, enabling it to participate effectively and securely in the Bittensor network. The flexibility offered by this method allows developers to tailor the Axon’s behavior to specific requirements and use cases.
- classmethod check_config(config)#
This method checks the configuration for the axon’s port and wallet.
- Parameters:
config (bittensor.core.config.Config) – The config object holding axon settings.
- Raises:
AssertionError – If the axon or external ports are not in range [1024, 65535]
- config#
- async default_verify(synapse)#
This method is used to verify the authenticity of a received message using a digital signature.
It ensures that the message was not tampered with and was sent by the expected sender.
The
default_verify()
method in the Bittensor framework is a critical security function within the Axon server. It is designed to authenticate incoming messages by verifying their digital signatures. This verification ensures the integrity of the message and confirms that it was indeed sent by the claimed sender. The method plays a pivotal role in maintaining the trustworthiness and reliability of the communication within the Bittensor network.- Key Features
- Security Assurance
The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access and data manipulation.
- Preventing Replay Attacks
The method checks for increasing nonce values, which is a vital step in preventing replay attacks. A replay attack involves an adversary reusing or delaying the transmission of a valid data transmission to deceive the receiver. The first time a nonce is seen, it is checked for freshness by ensuring it is within an acceptable delta time range.
- Authenticity and Integrity Checks
By verifying that the message’s digital signature matches its content, the method ensures the message’s authenticity (it comes from the claimed sender) and integrity (it hasn’t been altered during transmission).
- Trust in Communication
This method fosters trust in the network communication. Neurons (nodes in the Bittensor network) can confidently interact, knowing that the messages they receive are genuine and have not been tampered with.
- Cryptographic Techniques
The method’s reliance on asymmetric encryption techniques is a cornerstone of modern cryptographic security, ensuring that only entities with the correct cryptographic keys can participate in secure communication.
- Parameters:
synapse (bittensor.core.synapse.Synapse) – bittensor request synapse.
- Raises:
After successful verification, the nonce for the given endpoint key is updated.
Note
The verification process assumes the use of an asymmetric encryption algorithm, where the sender signs the message with their private key and the receiver verifies the signature using the sender’s public key.
- external_ip#
- external_port#
- fast_config#
- fast_server#
- forward_class_types: dict[str, list[inspect.Signature]]#
- full_address#
- classmethod help()#
Prints the help text (list of command-line arguments and their descriptions) to stdout.
- info()#
Returns the axon info object associated with this axon.
- Return type:
- ip#
- log_level#
- max_workers#
- middleware_cls#
- port#
- router#
- serve(netuid, subtensor=None, certificate=None)#
Serves the Axon on the specified subtensor connection using the configured wallet. This method registers the Axon with a specific subnet within the Bittensor network, identified by the
netuid
. It links the Axon to the broader network, allowing it to participate in the decentralized exchange of information.- Parameters:
netuid (int) – The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology.
subtensor (Optional[bittensor.core.subtensor.Subtensor]) – The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations.
certificate (Optional[bittensor.utils.Certificate])
- Returns:
The Axon instance that is now actively serving on the specified subtensor.
- Return type:
Example:
my_axon = bittensor.Axon(...) subtensor = bt.subtensor(network="local") # Local by default my_axon.serve(netuid=1, subtensor=subtensor) # Serves the axon on subnet with netuid 1
Note
The
serve
method is crucial for integrating the Axon into the Bittensor network, allowing it to start receiving and processing requests from other neurons.
- start()#
Starts the Axon server and its underlying FastAPI server thread, transitioning the state of the Axon instance to
started
. This method initiates the server’s ability to accept and process incoming network requests, making it an active participant in the Bittensor network.The start method triggers the FastAPI server associated with the Axon to begin listening for incoming requests. It is a crucial step in making the neuron represented by this Axon operational within the Bittensor network.
- Returns:
The Axon instance in the ‘started’ state.
- Return type:
Example:
my_axon = bittensor.Axon(...) ... # setup axon, attach functions, etc. my_axon.start() # Starts the axon server
Note
After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom logic.
- started = False#
- stop()#
Stops the Axon server and its underlying GRPC server thread, transitioning the state of the Axon instance to
stopped
. This method ceases the server’s ability to accept new network requests, effectively removing the neuron’s server-side presence in the Bittensor network.By stopping the FastAPI server, the Axon ceases to listen for incoming requests, and any existing connections are gracefully terminated. This function is typically used when the neuron is being shut down or needs to temporarily go offline.
- Returns:
The Axon instance in the ‘stopped’ state.
- Return type:
Example:
my_axon = bittensor.Axon(...) my_axon.start() ... my_axon.stop() # Stops the axon server
Note
It is advisable to ensure that all ongoing processes or requests are completed or properly handled before invoking this method.
- thread_pool#
- to_string()#
Provides a human-readable representation of the AxonInfo for this Axon.
- uuid#
- async verify_body_integrity(request)#
The
verify_body_integrity
method in the Bittensor framework is a key security function within the Axon server’s middleware. It is responsible for ensuring the integrity of the body of incoming HTTP requests.It asynchronously verifies the integrity of the body of a request by comparing the hash of required fields with the corresponding hashes provided in the request headers. This method is critical for ensuring that the incoming request payload has not been altered or tampered with during transmission, establishing a level of trust and security between the sender and receiver in the network.
- Parameters:
request (Request) – The incoming FastAPI request object containing both headers and the request body.
- Returns:
Returns the parsed body of the request as a dictionary if all the hash comparisons match, indicating that the body is intact and has not been tampered with.
- Return type:
- Raises:
JSONResponse – Raises a JSONResponse with a 400 status code if any of the hash comparisons fail, indicating a potential integrity issue with the incoming request payload. The response includes the detailed error message specifying which field has a hash mismatch.
This method performs several key functions:
Decoding and loading the request body for inspection.
Gathering required field names for hash comparison from the Axon configuration.
Loading and parsing the request body into a dictionary.
Reconstructing the Synapse object and recomputing the hash for verification and logging.
Comparing the recomputed hash with the hash provided in the request headers for verification.
Note
The integrity verification is an essential step in ensuring the security of the data exchange within the Bittensor network. It helps prevent tampering and manipulation of data during transit, thereby maintaining the reliability and trust in the network communication.
- wallet#
- class bittensor.AxonInfo#
The AxonInfo class represents information about an axon endpoint in the bittensor network. This includes properties such as IP address, ports, and relevant keys.
- Variables:
version (int) – The version of the axon endpoint.
ip (str) – The IP address of the axon endpoint.
port (int) – The port number the axon endpoint uses.
ip_type (int) – The type of IP protocol (e.g., IPv4 or IPv6).
hotkey (str) – The hotkey associated with the axon endpoint.
coldkey (str) – The coldkey associated with the axon endpoint.
protocol (int) – The protocol version (default is 4).
placeholder1 (int) – Reserved field (default is 0).
placeholder2 (int) – Reserved field (default is 0).
- __repr__()#
- __str__()#
- classmethod from_neuron_info(neuron_info)#
Converts a dictionary to an AxonInfo object.
- classmethod from_parameter_dict(parameter_dict)#
Returns an axon_info object from a torch parameter_dict or a parameter dict.
- classmethod from_string(json_string)#
Creates an AxonInfo object from its string representation using JSON.
- Parameters:
json_string (str) – The JSON string representation of the AxonInfo object.
- Returns:
An instance of AxonInfo created from the JSON string. If decoding fails, returns a default AxonInfo object with default values.
- Return type:
- Raises:
json.JSONDecodeError – If there is an error in decoding the JSON string.
TypeError – If there is a type error when creating the AxonInfo object.
ValueError – If there is a value error when creating the AxonInfo object.
- to_parameter_dict()#
Returns a torch tensor or dict of the subnet info, depending on the USE_TORCH flag set.
- bittensor.BLOCKTIME = 12#
- class bittensor.Balance(balance)#
Represents the bittensor balance of the wallet, stored as rao (int). This class provides a way to interact with balances in two different units: rao and tao. It provides methods to convert between these units, as well as to perform arithmetic and comparison operations.
- Variables:
- Parameters:
Initialize a Balance object. If balance is an int, it’s assumed to be in rao. If balance is a float, it’s assumed to be in tao.
- Parameters:
balance (Union[int, float]) – The initial balance, in either rao (if an int) or tao (if a float).
- __abs__()#
- __float__()#
Convert the Balance object to a float. The resulting value is in tao.
- __int__()#
Convert the Balance object to an int. The resulting value is in rao.
- __neg__()#
- __pos__()#
- __repr__()#
- __rich__()#
- __rich_rao__()#
- __str__()#
Returns the Balance object as a string in the format “symbolvalue”, where the value is in tao.
- __str_rao__()#
- static from_float(amount)#
Given tao, return
Balance()
object with rao(int
) and tao(float
), where rao = int(tao*pow(10,9)) :param amount: The amount in tao. :type amount: float- Returns:
A Balance object representing the given amount.
- Parameters:
amount (float)
- static from_rao(amount)#
Given rao, return Balance object with rao(
int
) and tao(float
), where rao = int(tao*pow(10,9))- Parameters:
amount (int) – The amount in rao.
- Returns:
A Balance object representing the given amount.
- static from_tao(amount)#
Given tao, return Balance object with rao(
int
) and tao(float
), where rao = int(tao*pow(10,9))- Parameters:
amount (float) – The amount in tao.
- Returns:
A Balance object representing the given amount.
- property tao#
- exception bittensor.BlacklistedException(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the request is blacklisted.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.ChainConnectionError#
Bases:
ChainError
Error for any chain connection related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainError#
Bases:
BaseException
Base error for any chain related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainQueryError#
Bases:
ChainError
Error for any chain query related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainTransactionError#
Bases:
ChainError
Error for any chain transaction related errors.
Initialize self. See help(type(self)) for accurate signature.
- class bittensor.Config(parser=None, args=None, strict=False, default=None)#
Bases:
munch.DefaultMunch
Implementation of the config class, which manages the configuration of different Bittensor modules.
Translates the passed parser into a nested Bittensor config.
- Parameters:
parser (argparse.ArgumentParser) – Command line parser object.
strict (bool) – If
true
, the command line arguments are strictly parsed.default (Optional[Any]) – Default value for the Config. Defaults to
None
. This default will be returned for attributes that are undefined.
- Returns:
Nested config object created from parser arguments.
- Return type:
config (bittensor.core.config.Config)
Construct a new DefaultMunch. Like collections.defaultdict, the first argument is the default value; subsequent arguments are the same as those for dict.
- __check_for_missing_required_args(parser, args)#
- Parameters:
parser (argparse.ArgumentParser)
- Return type:
- static __get_required_args_from_parser(parser)#
- Parameters:
parser (argparse.ArgumentParser)
- Return type:
- static __parse_args__(args, parser=None, strict=False)#
Parses the passed args use the passed parser.
- Parameters:
parser (argparse.ArgumentParser) – Command line parser object.
strict (bool) – If
true
, the command line arguments are strictly parsed.
- Returns:
Namespace object created from parser arguments.
- Return type:
Namespace
- __repr__()#
Invertible* string-form of a Munch.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!') >>> print (repr(b)) Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42}) >>> eval(repr(b)) Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})}) >>> print (repr(with_spaces)) Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})}) >>> eval(repr(with_spaces)) Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
(*) Invertible so long as collection contents are each repr-invertible.
- Return type:
- static __split_params__(params, _config)#
- Parameters:
params (argparse.Namespace)
_config (Config)
- _config#
- classmethod _merge(a, b)#
Merge two configurations recursively. If there is a conflict, the value from the second configuration will take precedence.
- static _remove_private_keys(d)#
- all_default_args#
- config_params#
- default_param_args#
- default_params#
- defaults_as_suppress#
- is_set(param_name)#
Returns a boolean indicating whether the parameter has been set or is still the default.
- merge(b)#
Merges the current config with another config.
- Parameters:
b (bittensor.core.config.Config) – Another config to merge.
- classmethod merge_all(configs)#
Merge all configs in the list into one config. If there is a conflict, the value from the last configuration in the list will take precedence.
- Parameters:
configs (list[bittensor.core.config.Config]) – List of configs to be merged.
- Returns:
Merged config object.
- Return type:
config (bittensor.core.config.Config)
- missing_required_args#
- params#
- params_no_defaults#
- parser_no_defaults#
- strict#
- update_with_kwargs(kwargs)#
Add config to self
- bittensor.DEFAULTS#
- bittensor.DEFAULT_NETWORK#
- class bittensor.DefaultConfig(parser=None, args=None, strict=False, default=None)#
Bases:
Config
A Config with a set of default values.
Construct a new DefaultMunch. Like collections.defaultdict, the first argument is the default value; subsequent arguments are the same as those for dict.
- Parameters:
parser (argparse.ArgumentParser)
strict (bool)
default (Optional[Any])
- classmethod default()#
- Abstractmethod:
- Return type:
T
Get default config.
- class bittensor.DelegateInfo#
Dataclass for delegate information. For a lighter version of this class, see
DelegateInfoLite
.- Parameters:
hotkey_ss58 (str) – Hotkey of the delegate for which the information is being fetched.
total_stake (int) – Total stake of the delegate.
nominators (list[tuple[str, int]]) – List of nominators of the delegate and their stake.
take (float) – Take of the delegate as a percentage.
owner_ss58 (str) – Coldkey of the owner.
registrations (list[int]) – List of subnets that the delegate is registered on.
validator_permits (list[int]) – List of subnets that the delegate is allowed to validate on.
return_per_1000 (int) – Return per 1000 TAO, for the delegate over a day.
total_daily_return (int) – Total daily return of the delegate.
- classmethod from_vec_u8(vec_u8)#
- Parameters:
vec_u8 (bytes)
- Return type:
Optional[DelegateInfo]
- nominators: list[tuple[str, bittensor.utils.balance.Balance]]#
- return_per_1000: bittensor.utils.balance.Balance#
- total_daily_return: bittensor.utils.balance.Balance#
- total_stake: bittensor.utils.balance.Balance#
- class bittensor.Dendrite(wallet=None)#
Bases:
DendriteMixin
,BaseModel
The Dendrite class represents the abstracted implementation of a network client module.
In the brain analogy, dendrites receive signals from other neurons (in this case, network servers or axons), and the Dendrite class here is designed to send requests to those endpoint to receive inputs.
This class includes a wallet or keypair used for signing messages, and methods for making HTTP requests to the network servers. It also provides functionalities such as logging network requests and processing server responses.
- Parameters:
keypair (Option[Union[bittensor_wallet.Wallet, substrateinterface.Keypair]]) – The wallet or keypair used for signing messages.
external_ip (str) – The external IP address of the local system.
synapse_history (list) – A list of Synapse objects representing the historical responses.
wallet (Optional[Union[bittensor_wallet.Wallet, bittensor_wallet.Keypair]])
- __repr__()#
Returns a string representation of the Dendrite object, acting as a fallback for __str__().
- Return type:
- query(self, *args, **kwargs) Synapse | list[Synapse] #
Makes synchronous requests to one or multiple target Axons and returns responses.
- Return type:
list[Union[AsyncGenerator[Any, Any], bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]]
- forward(self, axons, synapse=Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) Synapse #
Asynchronously sends requests to one or multiple Axons and collates their responses.
- Parameters:
axons (Union[list[Union[bittensor.core.chain_data.AxonInfo, bittensor.core.axon.Axon]], Union[bittensor.core.chain_data.AxonInfo, bittensor.core.axon.Axon]])
synapse (bittensor.core.synapse.Synapse)
timeout (float)
deserialize (bool)
run_async (bool)
streaming (bool)
- Return type:
list[Union[AsyncGenerator[Any, Any], bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]]
- call(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) Synapse #
Asynchronously sends a request to a specified Axon and processes the response.
- Parameters:
target_axon (Union[bittensor.core.chain_data.AxonInfo, bittensor.core.axon.Axon])
synapse (bittensor.core.synapse.Synapse)
timeout (float)
deserialize (bool)
- Return type:
- call_stream(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) AsyncGenerator[Synapse, None] #
Sends a request to a specified Axon and yields an AsyncGenerator that contains streaming response chunks before finally yielding the filled Synapse as the final element.
- Parameters:
target_axon (Union[bittensor.core.chain_data.AxonInfo, bittensor.core.axon.Axon])
synapse (bittensor.core.stream.StreamingSynapse)
timeout (float)
deserialize (bool)
- Return type:
AsyncGenerator[Any, Any]
- preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) Synapse #
Preprocesses the synapse for making a request, including building headers and signing.
- Parameters:
target_axon_info (bittensor.core.chain_data.AxonInfo)
synapse (bittensor.core.synapse.Synapse)
timeout (float)
- Return type:
- process_server_response(self, server_response, json_response, local_synapse)#
Processes the server response, updates the local synapse state, and merges headers.
- Parameters:
server_response (aiohttp.ClientResponse)
json_response (dict)
local_synapse (bittensor.core.synapse.Synapse)
- close_session(self)#
Synchronously closes the internal aiohttp client session.
- aclose_session(self)#
Asynchronously closes the internal aiohttp client session.
Note
When working with async aiohttp client sessions, it is recommended to use a context manager.
Example with a context manager:
async with dendrite(wallet = bittensor_wallet.Wallet()) as d: print(d) d( <axon> ) # ping axon d( [<axons>] ) # ping multiple d( Axon(), Synapse )
However, you are able to safely call
dendrite.query()
without a context manager in a synchronous setting.Example without a context manager:
d = dendrite(wallet = bittensor_wallet.Wallet() ) print(d) d( <axon> ) # ping axon d( [<axons>] ) # ping multiple d( bittensor.core.axon.Axon, bittensor.core.synapse.Synapse )
Initializes the Dendrite object, setting up essential properties.
- Parameters:
wallet (Optional[Union[bittensor_wallet.Wallet, substrateinterface.Keypair]]) – The user’s wallet or keypair used for signing messages. Defaults to
None
, in which case a newbittensor_wallet.Wallet().hotkey()
is generated and used.
- class bittensor.IPInfo#
Dataclass representing IP information.
- Variables:
- encode()#
Returns a dictionary of the IPInfo object that can be encoded.
- classmethod fix_decoded_values(decoded)#
Returns a SubnetInfo object from a decoded IPInfo dictionary.
- classmethod from_parameter_dict(parameter_dict)#
Creates a IPInfo instance from a parameter dictionary.
- classmethod from_vec_u8(vec_u8)#
Returns a IPInfo object from a
vec_u8
.
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of IPInfo objects from a
vec_u8
.
- exception bittensor.IdentityError#
Bases:
ChainTransactionError
Error raised when an identity transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.InternalServerError(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the requested function fails on the server. Indicates a server error.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.InvalidConfigFile#
Bases:
Exception
In place of YAMLError
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.InvalidRequestNameError#
Bases:
Exception
This exception is raised when the request name is invalid. Usually indicates a broken URL.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.MetadataError#
Bases:
ChainTransactionError
Error raised when metadata commitment transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- bittensor.Metagraph#
Metagraph class that uses
TorchMetaGraph
if PyTorch is available; otherwise, it falls back toNonTorchMetagraph
.With PyTorch: When use_torch() returns True, Metagraph is set to
TorchMetaGraph
, which utilizes PyTorch functionalities.Without PyTorch: When use_torch() returns False, Metagraph is set to
NonTorchMetagraph
, which does not rely on PyTorch.
- class bittensor.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 isFalse
.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 isTrue
.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:
- _get_axon_info(netuid, hotkey, block=None)#
- Parameters:
- Return type:
- static _get_most_recent_storage(storage, block_number=None)#
- _get_prometheus_info(netuid, hotkey, block=None)#
- Parameters:
- Return type:
- _handle_type_default(name, params)#
- _neuron_subnet_exists(uid, netuid, block=None)#
- Parameters:
- Return type:
Optional[bittensor.core.chain_data.NeuronInfo]
- chain_state: MockChainState#
- close_code = None#
- commit(wallet, netuid, data)#
Commits arbitrary data to the Bittensor network by publishing metadata.
- do_block_step()#
- Return type:
None
- do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
- do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
- do_set_weights(wallet, netuid, uids, vals, version_key, wait_for_inclusion=False, wait_for_finalization=True)#
- do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)#
- force_set_balance(ss58_address, balance=Balance(0))#
- 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:
- Returns:
The account balance at the specified block, represented as a Balance object.
- Return type:
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:
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:
- Returns:
The commitment data as a string.
- Return type:
- 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:
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:
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:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
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:
- 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:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
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:
- 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:
- 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:
- 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
- setup()#
- Return type:
None
- sudo_force_set_balance#
- class bittensor.NeuronInfo#
Represents the metadata of a neuron including keys, UID, stake, rankings, and other attributes.
- Variables:
hotkey (str) – The hotkey associated with the neuron.
coldkey (str) – The coldkey associated with the neuron.
uid (int) – The unique identifier for the neuron.
netuid (int) – The network unique identifier for the neuron.
active (int) – The active status of the neuron.
stake (Balance) – The balance staked to this neuron.
stake_dict (dict[str, Balance]) – A dictionary mapping coldkey to the amount staked.
total_stake (Balance) – The total amount of stake.
rank (float) – The rank score of the neuron.
emission (float) – The emission rate.
incentive (float) – The incentive value.
consensus (float) – The consensus score.
trust (float) – The trust score.
validator_trust (float) – The validation trust score.
dividends (float) – The dividends value.
last_update (int) – The timestamp of the last update.
validator_permit (bool) – Validator permit status.
weights (list[list[int]]) – List of weights associated with the neuron.
bonds (list[list[int]]) – List of bonds associated with the neuron.
pruning_score (int) – The pruning score of the neuron.
prometheus_info (Optional[PrometheusInfo]) – Information related to Prometheus.
axon_info (Optional[AxonInfo]) – Information related to Axon.
is_null (bool) – Indicator if this is a null neuron.
- axon_info: bittensor.core.chain_data.axon_info.AxonInfo | None = None#
- classmethod from_vec_u8(vec_u8)#
Instantiates NeuronInfo from a byte vector.
- Parameters:
vec_u8 (bytes)
- Return type:
- classmethod from_weights_bonds_and_neuron_lite(neuron_lite, weights_as_dict, bonds_as_dict)#
Creates an instance of NeuronInfo from NeuronInfoLite and dictionaries of weights and bonds.
- Parameters:
neuron_lite (NeuronInfoLite) – A lite version of the neuron containing basic attributes.
weights_as_dict (dict[int, list[tuple[int, int]]]) – A dictionary where the key is the UID and the value is a list of weight tuples associated with the neuron.
bonds_as_dict (dict[int, list[tuple[int, int]]]) – A dictionary where the key is the UID and the value is a list of bond tuples associated with the neuron.
- Returns:
An instance of NeuronInfo populated with the provided weights and bonds.
- Return type:
- static get_null_neuron()#
Returns a null NeuronInfo instance.
- Return type:
- prometheus_info: bittensor.core.chain_data.prometheus_info.PrometheusInfo | None = None#
- stake_dict: dict[str, bittensor.utils.balance.Balance]#
- total_stake: bittensor.utils.balance.Balance#
- class bittensor.NeuronInfoLite#
NeuronInfoLite is a dataclass representing neuron metadata without weights and bonds.
- Variables:
hotkey (str) – The hotkey string for the neuron.
coldkey (str) – The coldkey string for the neuron.
uid (int) – A unique identifier for the neuron.
netuid (int) – Network unique identifier for the neuron.
active (int) – Indicates whether the neuron is active.
stake (Balance) – The stake amount associated with the neuron.
stake_dict (dict) – Mapping of coldkey to the amount staked to this Neuron.
total_stake (Balance) – Total amount of the stake.
rank (float) – The rank of the neuron.
emission (float) – The emission value of the neuron.
incentive (float) – The incentive value of the neuron.
consensus (float) – The consensus value of the neuron.
trust (float) – Trust value of the neuron.
validator_trust (float) – Validator trust value of the neuron.
dividends (float) – Dividends associated with the neuron.
last_update (int) – Timestamp of the last update.
validator_permit (bool) – Indicates if the neuron has a validator permit.
prometheus_info (Optional[PrometheusInfo]) – Prometheus information associated with the neuron.
axon_info (Optional[AxonInfo]) – Axon information associated with the neuron.
pruning_score (int) – The pruning score of the neuron.
is_null (bool) – Indicates whether the neuron is null.
- get_null_neuron()#
Returns a NeuronInfoLite object representing a null neuron.
- Return type:
- list_from_vec_u8()#
Decodes a bytes object into a list of NeuronInfoLite instances.
- Parameters:
vec_u8 (bytes)
- Return type:
- axon_info: bittensor.core.chain_data.axon_info.AxonInfo | None#
- static get_null_neuron()#
Returns a null NeuronInfoLite instance.
- Return type:
- classmethod list_from_vec_u8(vec_u8)#
Decodes a bytes object into a list of NeuronInfoLite instances.
- Parameters:
vec_u8 (bytes) – The bytes object to decode into NeuronInfoLite instances.
- Returns:
A list of NeuronInfoLite instances decoded from the provided bytes object.
- Return type:
- prometheus_info: bittensor.core.chain_data.prometheus_info.PrometheusInfo | None#
- stake_dict: dict[str, bittensor.utils.balance.Balance]#
- total_stake: bittensor.utils.balance.Balance#
- exception bittensor.NominationError#
Bases:
ChainTransactionError
Error raised when a nomination transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.NotDelegateError#
Bases:
StakeError
Error raised when a hotkey you are trying to stake to is not a delegate.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.NotRegisteredError#
Bases:
ChainTransactionError
Error raised when a neuron is not registered, and the transaction requires it to be.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.NotVerifiedException(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the request is not verified.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.PostProcessException(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the response headers cannot be updated.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.PriorityException(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the request priority is not met.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- class bittensor.PriorityThreadPoolExecutor(maxsize=-1, max_workers=None, thread_name_prefix='', initializer=None, initargs=())#
Bases:
concurrent.futures._base.Executor
Base threadpool executor with a priority queue.
Initializes a new ThreadPoolExecutor instance.
- Parameters:
max_workers – The maximum number of threads that can be used to execute the given calls.
thread_name_prefix – An optional name prefix to give our threads.
initializer – An callable used to initialize worker threads.
initargs – A tuple of arguments to pass to the initializer.
- _adjust_thread_count()#
- _broken = False#
- _counter#
- _idle_semaphore#
- _initargs#
- _initializer#
- _initializer_failed()#
- _max_workers#
- _shutdown = False#
- _shutdown_lock#
- _thread_name_prefix#
- _threads#
- _work_queue#
- classmethod add_args(parser, prefix=None)#
Accept specific arguments from parser
- Parameters:
parser (argparse.ArgumentParser)
prefix (str)
- classmethod config()#
Get config from the argument parser.
Return:
bittensor.Config()
object.- Return type:
- property is_empty#
- shutdown(wait=True)#
Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Parameters:
wait – If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
cancel_futures – If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.
- submit(fn, *args, **kwargs)#
Submits a callable to be executed with the given arguments.
Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable.
- Returns:
A Future representing the given call.
- Parameters:
fn (Callable)
- Return type:
concurrent.futures._base.Future
- class bittensor.PrometheusInfo#
Dataclass representing information related to Prometheus.
- Variables:
- bittensor.ProposalCallData#
- class bittensor.ProposalVoteData#
Bases:
TypedDict
This TypedDict represents the data structure for a proposal vote in the Senate.
- Variables:
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.RegistrationError#
Bases:
ChainTransactionError
Error raised when a neuron registration transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.RunException(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the requested function cannot be executed. Indicates a server error.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.StakeError#
Bases:
ChainTransactionError
Error raised when a stake transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- class bittensor.StakeInfo#
Dataclass for representing stake information linked to hotkey and coldkey pairs.
- Variables:
- classmethod fix_decoded_values(decoded)#
Fixes the decoded values.
- Parameters:
decoded (Any)
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a StakeInfo object from a
vec_u8
.
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of StakeInfo objects from a
vec_u8
.
- classmethod list_of_tuple_from_vec_u8(vec_u8)#
Returns a list of StakeInfo objects from a
vec_u8
.
- class bittensor.StreamingSynapse(/, **data)#
Bases:
bittensor.core.synapse.Synapse
,abc.ABC
The
StreamingSynapse()
class is designed to be subclassed for handling streaming responses in the Bittensor network. It provides abstract methods that must be implemented by the subclass to deserialize, process streaming responses, and extract JSON data. It also includes a method to create a streaming response object.Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class BTStreamingResponse(model, *, synapse=None, **kwargs)#
Bases:
starlette.responses.StreamingResponse
BTStreamingResponse()
is a specialized subclass of the Starlette StreamingResponse designed to handle the streaming of tokens within the Bittensor network. It is used internally by the StreamingSynapse class to manage the response streaming process, including sending headers and calling the token streamer provided by the subclass.This class is not intended to be directly instantiated or modified by developers subclassing StreamingSynapse. Instead, it is used by the
create_streaming_response()
method to create a response object based on the token streamer provided by the subclass.Initializes the BTStreamingResponse with the given token streamer model.
- Parameters:
model (bittensor.core.stream.BTStreamingResponseModel) – A BTStreamingResponseModel instance containing the token streamer callable, which is responsible for generating the content of the response.
synapse (bittensor.core.stream.StreamingSynapse) – The response Synapse to be used to update the response headers etc.
**kwargs – Additional keyword arguments passed to the parent StreamingResponse class.
- async __call__(scope, receive, send)#
Asynchronously calls the
stream_response method()
, allowing theBTStreamingResponse()
object to be used as an ASGI application.This method is part of the ASGI interface and is called by the ASGI server to handle the request and send the response. It delegates to the
stream_response()
method to perform the actual streaming process.- Parameters:
scope (starlette.types.Scope) – The scope of the request, containing information about the client, server, and request itself.
receive (starlette.types.Receive) – A callable to receive the request, provided by the ASGI server.
send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.
- async stream_response(send)#
Asynchronously streams the response by sending headers and calling the token streamer.
This method is responsible for initiating the response by sending the appropriate headers, including the content type for event-streaming. It then calls the token streamer to generate the content and sends the response body to the client.
- Parameters:
send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.
- synapse#
- token_streamer#
- create_streaming_response(token_streamer)#
Creates a streaming response using the provided token streamer. This method can be used by the subclass to create a response object that can be sent back to the client. The token streamer should be implemented to generate the content of the response according to the specific requirements of the subclass.
- Parameters:
token_streamer (Callable[[starlette.types.Send], Awaitable[None]]) – A callable that takes a send function and returns an awaitable. It’s responsible for generating the content of the response.
- Returns:
The streaming response object, ready to be sent to the client.
- Return type:
BTStreamingResponse (bittensor.core.stream.StreamingSynapse.BTStreamingResponse)
- abstract extract_response_json(response)#
Abstract method that must be implemented by the subclass. This method should provide logic to extract JSON data from the response, including headers and content. It is called after the response has been processed and is responsible for retrieving structured data that can be used by the application.
- Parameters:
response (aiohttp.ClientResponse) – The response object from which to extract JSON data.
- Return type:
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- abstract process_streaming_response(response)#
- Async:
- Parameters:
response (aiohttp.ClientResponse)
Abstract method that must be implemented by the subclass. This method should provide logic to handle the streaming response, such as parsing and accumulating data. It is called as the response is being streamed from the network, and should be implemented to handle the specific streaming data format and requirements of the subclass.
- Parameters:
response (aiohttp.ClientResponse) – The response object to be processed, typically containing chunks of data.
- class bittensor.SubnetHyperparameters#
This class represents the hyperparameters for a subnet.
- Variables:
rho (int) – The rate of decay of some value.
kappa (int) – A constant multiplier used in calculations.
immunity_period (int) – The period during which immunity is active.
min_allowed_weights (int) – Minimum allowed weights.
max_weight_limit (float) – Maximum weight limit.
tempo (int) – The tempo or rate of operation.
min_difficulty (int) – Minimum difficulty for some operations.
max_difficulty (int) – Maximum difficulty for some operations.
weights_version (int) – The version number of the weights used.
weights_rate_limit (int) – Rate limit for processing weights.
adjustment_interval (int) – Interval at which adjustments are made.
activity_cutoff (int) – Activity cutoff threshold.
registration_allowed (bool) – Indicates if registration is allowed.
target_regs_per_interval (int) – Target number of registrations per interval.
min_burn (int) – Minimum burn value.
max_burn (int) – Maximum burn value.
bonds_moving_avg (int) – Moving average of bonds.
max_regs_per_block (int) – Maximum number of registrations per block.
serving_rate_limit (int) – Limit on the rate of service.
max_validators (int) – Maximum number of validators.
adjustment_alpha (int) – Alpha value for adjustments.
difficulty (int) – Difficulty level.
commit_reveal_weights_interval (int) – Interval for commit-reveal weights.
commit_reveal_weights_enabled (bool) – Flag indicating if commit-reveal weights are enabled.
alpha_high (int) – High value of alpha.
alpha_low (int) – Low value of alpha.
liquid_alpha_enabled (bool) – Flag indicating if liquid alpha is enabled.
- classmethod from_vec_u8(vec_u8)#
Create a SubnetHyperparameters instance from a vector of bytes.
This method decodes the given vector of bytes using the bt_decode module and creates a new instance of SubnetHyperparameters with the decoded values.
- Parameters:
vec_u8 (bytes) – A vector of bytes to decode into SubnetHyperparameters.
- Returns:
An instance of SubnetHyperparameters if decoding is successful, None otherwise.
- Return type:
Optional[SubnetHyperparameters]
- class bittensor.SubnetInfo#
Dataclass for subnet info.
- class bittensor.SubnetsAPI(wallet)#
Bases:
abc.ABC
This class is not used within the bittensor package, but is actively used by the community.
- Parameters:
wallet (bittensor_wallet.Wallet)
- async __call__(*args, **kwargs)#
- dendrite#
- abstract prepare_synapse(*args, **kwargs)#
Prepare the synapse-specific payload.
- Return type:
Any
- abstract process_responses(responses)#
Process the responses from the network.
- Parameters:
responses (list[Union[bittensor.core.synapse.Synapse, Any]])
- Return type:
Any
- async query_api(axons, deserialize=False, timeout=12, **kwargs)#
Queries the API nodes of a subnet using the given synapse and bespoke query function.
- Parameters:
- Returns:
The result of the process_responses_fn.
- Return type:
Any
- wallet#
- class bittensor.Subtensor(network=None, config=None, _mock=False, log_verbose=False, connection_timeout=600, websocket=None)#
The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, facilitating a range of operations essential for the decentralized machine learning network.
This class enables neurons (network participants) to engage in activities such as registering on the network, managing staked weights, setting inter-neuronal weights, and participating in consensus mechanisms.
The Bittensor network operates on a digital ledger where each neuron holds stakes (S) and learns a set of inter-peer weights (W). These weights, set by the neurons themselves, play a critical role in determining the ranking and incentive mechanisms within the network. Higher-ranked neurons, as determined by their contributions and trust within the network, receive more incentives.
The Subtensor class connects to various Bittensor networks like the main
finney
network or local test networks, providing a gateway to the blockchain layer of Bittensor. It leverages a staked weighted trust system and consensus to ensure fair and distributed incentive mechanisms, where incentives (I) are primarily allocated to neurons that are trusted by the majority of the network.Additionally, Bittensor introduces a speculation-based reward mechanism in the form of bonds (B), allowing neurons to accumulate bonds in other neurons, speculating on their future value. This mechanism aligns with market-based speculation, incentivizing neurons to make judicious decisions in their inter-neuronal investments.
Example Usage:
from bittensor.core.subtensor import Subtensor # Connect to the main Bittensor network (Finney). finney_subtensor = Subtensor(network='finney') # Close websocket connection with the Bittensor network. finney_subtensor.close() # Register a new neuron on the network. wallet = bittensor_wallet.Wallet(...) # Assuming a wallet instance is created. netuid = 1 success = finney_subtensor.register(wallet=wallet, netuid=netuid) # Set inter-neuronal weights for collaborative learning. success = finney_subtensor.set_weights(wallet=wallet, netuid=netuid, uids=[...], weights=[...]) # Get the metagraph for a specific subnet using given subtensor connection metagraph = finney_subtensor.metagraph(netuid=netuid)
By facilitating these operations, the Subtensor class is instrumental in maintaining the decentralized intelligence and dynamic learning environment of the Bittensor network, as envisioned in its foundational principles and mechanisms described in the NeurIPS paper. paper.
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 isFalse
.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 isTrue
.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.
- _config#
- _connection_timeout#
- _do_serve_axon#
- _encode_params(call_definition, params)#
Returns a hex encoded string of the params using their types.
- _get_hyperparameter(param_name, netuid, block=None)#
Retrieves a specified hyperparameter for a specific subnet.
- Parameters:
- Returns:
The value of the specified hyperparameter if the subnet exists,
None
otherwise.- Return type:
- _get_substrate(force=False)#
Establishes a connection to the Substrate node using configured parameters.
- Parameters:
force (bool) – forces a reconnection if this flag is set
- classmethod add_args(parser, prefix=None)#
Adds command-line arguments to the provided ArgumentParser for configuring the Subtensor settings.
- Parameters:
parser (argparse.ArgumentParser) – The ArgumentParser object to which the Subtensor arguments will be added.
prefix (Optional[str]) – An optional prefix for the argument names. If provided, the prefix is prepended to each argument name.
- Arguments added:
–subtensor.network: The Subtensor network flag. Possible values are ‘finney’, ‘test’, ‘archive’, and ‘local’. Overrides the chain endpoint if set. –subtensor.chain_endpoint: The Subtensor chain endpoint flag. If set, it overrides the network flag. –subtensor._mock: If true, uses a mocked connection to the chain.
Example
parser = argparse.ArgumentParser() Subtensor.add_args(parser)
- add_stake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False)#
Adds the specified amount of stake to a neuron identified by the hotkey
SS58
address. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives.- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to be used for staking.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey associated with the neuron.amount (Union[Balance, float]) – The amount of TAO to stake.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
True
if the staking is successful, False otherwise.- Return type:
This function enables neurons to increase their stake in the network, enhancing their influence and potential rewards in line with Bittensor’s consensus and reward mechanisms.
- add_stake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False)#
Adds stakes to multiple neurons identified by their hotkey SS58 addresses. This bulk operation allows for efficient staking across different neurons from a single wallet.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used for staking.
hotkey_ss58s (list[str]) – List of
SS58
addresses of hotkeys to stake to.amounts (list[Union[Balance, float]]) – Corresponding amounts of TAO to stake for each hotkey.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
True
if the staking is successful for all specified neurons, False otherwise.- Return type:
This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative nature of the Bittensor network.
- property block: int#
Returns current chain block.
- Returns:
Current chain block.
- Return type:
block (int)
- blocks_since_last_update(netuid, uid)#
Returns the number of blocks since the last update for a specific UID in the subnetwork.
- bonds(netuid, block=None)#
Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its bonds with other neurons.
- Return type:
Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.
- burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True)#
Registers a neuron on the Bittensor network by recycling TAO. This method of registration involves recycling TAO tokens, allowing them to be re-mined by performing work on the network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.
netuid (int) – The unique identifier of the subnet.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block. Defaults to False.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain. Defaults to True.
- Returns:
True
if the registration is successful, False otherwise.- Return type:
- close()#
Cleans up resources for this subtensor instance like active websocket connection and active extensions.
- commit(wallet, netuid, data)#
Commits arbitrary data to the Bittensor network by publishing metadata.
- commit_reveal_enabled(netuid, block=None)#
Check if commit-reveal mechanism is enabled for a given network at a specific block.
- Parameters:
- Returns:
Returns the integer value of the hyperparameter if available; otherwise, returns None.
- Return type:
(Optional[bool])
- commit_weights(wallet, netuid, salt, uids, weights, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Commits a hash of the neuron’s weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron’s current weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the weights.
netuid (int) – The unique identifier of the subnet.
salt (list[int]) – list of randomly generated integers as salt to generated weighted hash.
uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being committed.
weights (np.ndarray) – NumPy array of weight values corresponding to each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to commit weights. Default is
5
.
- Returns:
True
if the weight commitment is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, enhancing transparency and accountability within the Bittensor network.
- static config()#
Creates and returns a Bittensor configuration object.
- Returns:
A Bittensor configuration object configured with arguments added by the subtensor.add_args method.
- Return type:
config (bittensor.core.config.Config)
- static determine_chain_endpoint_and_network(network)#
Determines the chain endpoint and network from the passed network or chain_endpoint.
- Parameters:
network (str) – The network flag. The choices are:
finney
(main network),archive
(archive network +300 blocks),local
(local running network),test
(test network).- Returns:
The network and chain endpoint flag. If passed, overrides the
network
argument.- Return type:
- difficulty(netuid, block=None)#
Retrieves the ‘Difficulty’ hyperparameter for a specified subnet in the Bittensor network.
This parameter is instrumental in determining the computational challenge required for neurons to participate in consensus and validation processes.
- Parameters:
- Returns:
The value of the ‘Difficulty’ hyperparameter if the subnet exists,
None
otherwise.- Return type:
Optional[int]
The ‘Difficulty’ parameter directly impacts the network’s security and integrity by setting the computational effort required for validating transactions and participating in the network’s consensus mechanism.
- does_hotkey_exist(hotkey_ss58, block=None)#
Returns true if the hotkey is known by the chain and there are accounts.
- get_all_subnets_info(block=None)#
Retrieves detailed information about all subnets within the Bittensor network. This function provides comprehensive data on each subnet, including its characteristics and operational parameters.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
A list of SubnetInfo objects, each containing detailed information about a subnet.
- Return type:
Gaining insights into the subnets’ details assists in understanding the network’s composition, the roles of different subnets, and their unique features.
- 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:
- Returns:
The account balance at the specified block, represented as a Balance object.
- Return type:
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:
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:
- Returns:
The commitment data as a string.
- Return type:
- 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:
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_current_weight_commit_info(netuid, block=None)#
Retrieves CRV3 weight commit information for a specific subnet.
- Parameters:
- Returns:
- A list of commit details, where each entry is a dictionary with keys ‘who’,
’serialized_commit’, and ‘reveal_round’, or an empty list if no data is found.
- Return type:
- get_delegate_by_hotkey(hotkey_ss58, block=None)#
Retrieves detailed information about a delegate neuron based on its hotkey. This function provides a comprehensive view of the delegate’s status, including its stakes, nominators, and reward distribution.
- Parameters:
- Returns:
Detailed information about the delegate neuron,
None
if not found.- Return type:
Optional[DelegateInfo]
This function is essential for understanding the roles and influence of delegate neurons within the Bittensor network’s consensus and governance structures.
- get_delegate_take(hotkey_ss58, block=None)#
Retrieves the delegate ‘take’ percentage for a neuron identified by its hotkey. The ‘take’ represents the percentage of rewards that the delegate claims from its nominators’ stakes.
- Parameters:
- Returns:
The delegate take percentage, None if not available.
- Return type:
Optional[float]
The delegate take is a critical parameter in the network’s incentive structure, influencing the distribution of rewards among neurons and their nominators.
- get_delegates(block=None)#
Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.
Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
A list of DelegateInfo objects detailing each delegate’s characteristics.
- Return type:
- get_existential_deposit(block=None)#
Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped to conserve network resources.
- Parameters:
block (Optional[int]) – Block number at which to query the deposit amount. If
None
, the current block is used.- Returns:
The existential deposit amount, or
None
if the query fails.- Return type:
Optional[bittensor.utils.balance.Balance]
The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts.
- get_hotkey_owner(hotkey_ss58, block=None)#
Returns the coldkey owner of the passed hotkey.
- Parameters:
- Returns:
The SS58 address of the coldkey owner, or
None
if the hotkey does not exist or the owner is not found.- Return type:
Optional[str]
- get_minimum_required_stake()#
Returns the minimum required stake for nominators in the Subtensor network.
This method retries the substrate call up to three times with exponential backoff in case of failures.
- get_netuids_for_hotkey(hotkey_ss58, block=None)#
Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with the hotkey is active.
- get_neuron_certificate(hotkey, netuid, block=None)#
Retrieves the TLS certificate for a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network.
- Parameters:
- Returns:
the certificate of the neuron if found,
None
otherwise.- Return type:
Optional[Certificate]
This function is used for certificate discovery for setting up mutual tls communication between neurons
- get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None)#
Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem.
- get_prometheus_info(netuid, hotkey_ss58, block=None)#
Returns the prometheus information for this hotkey account.
- Parameters:
- Returns:
A PrometheusInfo object containing the prometheus information, or
None
if the prometheus information is not found.- Return type:
Optional[bittensor.core.chain_data.prometheus_info.PrometheusInfo]
- get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block=None)#
Returns the stake under a coldkey - hotkey pairing.
- Parameters:
- Returns:
The stake under the coldkey - hotkey pairing, or
None
if the pairing does not exist or the stake is not found.- Return type:
Optional[Balance]
- get_subnet_burn_cost(block=None)#
Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the amount of Tao that needs to be locked or burned to establish a new subnet.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
The burn cost for subnet registration.
- Return type:
The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling the proliferation of subnets and ensuring their commitment to the network’s long-term viability.
- get_subnet_hyperparameters(netuid, block=None)#
Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.
- Parameters:
- Returns:
The subnet’s hyperparameters, or
None
if not available.- Return type:
Optional[bittensor.core.chain_data.subnet_hyperparameters.SubnetHyperparameters]
Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network’s consensus and incentive mechanisms.
- get_subnet_reveal_period_epochs(netuid, block=None)#
Retrieve the SubnetRevealPeriodEpochs hyperparameter.
- get_subnets(block=None)#
Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
A list of network UIDs representing each active subnet.
- Return type:
This function is valuable for understanding the network’s structure and the diversity of subnets available for neuron participation and collaboration.
- get_total_stake_for_coldkey(ss58_address, block=None)#
Retrieves the total stake held by a coldkey across all associated hotkeys, including delegated stakes.
- get_total_stake_for_hotkey(ss58_address, block=None)#
Retrieves the total stake associated with a hotkey.
- get_total_subnets(block=None)#
Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
The total number of subnets in the network.
- Return type:
Optional[int]
Understanding the total number of subnets is essential for assessing the network’s growth and the extent of its decentralized infrastructure.
- 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:
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.
- get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None)#
Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.
- Parameters:
- Returns:
The UID of the neuron if it is registered on the subnet,
None
otherwise.- Return type:
Optional[int]
The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.
- classmethod help()#
Print help to stdout.
- immunity_period(netuid, block=None)#
Retrieves the ‘ImmunityPeriod’ hyperparameter for a specific subnet. This parameter defines the duration during which new neurons are protected from certain network penalties or restrictions.
- Parameters:
- Returns:
The value of the ‘ImmunityPeriod’ hyperparameter if the subnet exists,
None
otherwise.- Return type:
Optional[int]
The ‘ImmunityPeriod’ is a critical aspect of the network’s governance system, ensuring that new participants have a grace period to establish themselves and contribute to the network without facing immediate punitive actions.
- is_hotkey_delegate(hotkey_ss58, block=None)#
Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if the neuron associated with the hotkey is part of the network’s delegation system.
- Parameters:
- Returns:
True
if the hotkey is a delegate,False
otherwise.- Return type:
Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.
- is_hotkey_registered(hotkey_ss58, netuid=None, block=None)#
Determines whether a given hotkey (public key) is registered in the Bittensor network, either globally across any subnet or specifically on a specified subnet. This function checks the registration status of a neuron identified by its hotkey, which is crucial for validating its participation and activities within the network.
- Parameters:
- Returns:
True
if the hotkey is registered in the specified context (either any subnet or a specific subnet),False
otherwise.- Return type:
This function is important for verifying the active status of neurons in the Bittensor network. It aids in understanding whether a neuron is eligible to participate in network processes such as consensus, validation, and incentive distribution based on its registration status.
- is_hotkey_registered_any(hotkey_ss58, block=None)#
Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on any subnet, False otherwise.- Return type:
This function is essential for determining the network-wide presence and participation of a neuron.
- is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None)#
Checks if a neuron’s hotkey is registered on a specific subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on the specified subnet, False otherwise.- Return type:
This function helps in assessing the participation of a neuron in a particular subnet, indicating its specific area of operation or influence within the network.
- last_drand_round()#
Retrieves the last drand round emitted in bittensor. This corresponds when committed weights will be revealed.
- Returns:
The latest Drand round emitted in bittensor.
- Return type:
- log_verbose#
- max_weight_limit(netuid, block=None)#
Returns network MaxWeightsLimit hyperparameter.
- Parameters:
- Returns:
The value of the MaxWeightsLimit hyperparameter, or
None
if the subnetwork does not exist or the parameter is not found.- Return type:
Optional[float]
- metagraph(netuid, lite=True, block=None)#
Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the network’s structure, including neuron connections and interactions.
- Parameters:
- Returns:
The metagraph representing the subnet’s structure and neuron relationships.
- Return type:
bittensor.core.metagraph.Metagraph
The metagraph is an essential tool for understanding the topology and dynamics of the Bittensor network’s decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes.
- min_allowed_weights(netuid, block=None)#
Returns network MinAllowedWeights hyperparameter.
- Parameters:
- Returns:
The value of the MinAllowedWeights hyperparameter, or
None
if the subnetwork does not exist or the parameter is not found.- Return type:
Optional[int]
- 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:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
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)#
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:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
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:
- 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:
- 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(module, name, block=None, params=None)#
Queries map storage from any module on the Bittensor blockchain. This function retrieves data structures that represent key-value mappings, essential for accessing complex and structured data within the blockchain modules.
- Parameters:
module (str) – The name of the module from which to query the map storage.
name (str) – The specific storage function within the module to query.
block (Optional[int]) – The blockchain block number at which to perform the query.
params (Optional[list[object]]) – Parameters to be passed to the query.
- Returns:
A data structure representing the map storage if found,
None
otherwise.- Return type:
result (substrateinterface.base.QueryMapResult)
This function is particularly useful for retrieving detailed and structured data from various blockchain modules, offering insights into the network’s state and the relationships between its different components.
- query_map_subtensor(name, block=None, params=None)#
Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve a map-like data structure, which can include various neuron-specific details or network-wide attributes.
- Parameters:
- Returns:
An object containing the map-like data structure, or
None
if not found.- Return type:
QueryMapResult (substrateinterface.base.QueryMapResult)
This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as inter-neuronal connections and stake distributions.
- query_module(module, name, block=None, params=None)#
Queries any module storage on the Bittensor blockchain with the specified parameters and block number. This function is a generic query interface that allows for flexible and diverse data retrieval from various blockchain modules.
- Parameters:
- Returns:
An object containing the requested data if found,
None
otherwise.- Return type:
Optional[scalecodec.ScaleType]
This versatile query function is key to accessing a wide range of data and insights from different parts of the Bittensor blockchain, enhancing the understanding and analysis of the network’s state and dynamics.
- query_runtime_api(runtime_api, method, params, block=None)#
Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to interact with specific runtime methods and decode complex data types.
- Parameters:
runtime_api (str) – The name of the runtime API to query.
method (str) – The specific method within the runtime API to call.
params (Optional[list[ParamWithTypes]]) – The parameters to pass to the method call.
block (Optional[int]) – The blockchain block number at which to perform the query.
- Returns:
The Scale Bytes encoded result from the runtime API call, or
None
if the call fails.- Return type:
Optional[str]
This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network’s runtime environment.
- 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:
- 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.
- recycle(netuid, block=None)#
Retrieves the ‘Burn’ hyperparameter for a specified subnet. The ‘Burn’ parameter represents the amount of Tao that is effectively recycled within the Bittensor network.
- Parameters:
- Returns:
The value of the ‘Burn’ hyperparameter if the subnet exists, None otherwise.
- Return type:
Optional[Balance]
Understanding the ‘Burn’ rate is essential for analyzing the network registration usage, particularly how it is correlated with user activity and the overall cost of participation in a given subnet.
- register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, max_allowed_attempts=3, output_in_place=True, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False)#
Registers a neuron on the Bittensor network using the provided wallet.
Registration is a critical step for a neuron to become an active participant in the network, enabling it to stake, set weights, and receive incentives.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.
netuid (int) – The unique identifier of the subnet.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Defaults to False.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to True.
max_allowed_attempts (int) – Maximum number of attempts to register the wallet.
output_in_place (bool) – If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines. Defaults to True.
cuda (bool) – If
true
, the wallet should be registered using CUDA device(s). Defaults to False.dev_id (Union[List[int], int]) – The CUDA device id to use, or a list of device ids. Defaults to 0 (zero).
tpb (int) – The number of threads per block (CUDA). Default to 256.
num_processes (Optional[int]) – The number of processes to use to register. Default to None.
update_interval (Optional[int]) – The number of nonces to solve between updates. Default to None.
log_verbose (bool) – If
true
, the registration process will log more information. Default to False.
- Returns:
True
if the registration is successful, False otherwise.- Return type:
This function facilitates the entry of new neurons into the network, supporting the decentralized growth and scalability of the Bittensor ecosystem.
- reveal_weights(wallet, netuid, uids, weights, salt, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the neuron’s previously committed weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron revealing the weights.
netuid (int) – The unique identifier of the subnet.
uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being revealed.
weights (np.ndarray) – NumPy array of weight values corresponding to each UID.
salt (np.ndarray) – NumPy array of salt values corresponding to the hash function.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to reveal weights. Default is
5
.
- Returns:
True
if the weight revelation is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function allows neurons to reveal their previously committed weight distribution, ensuring transparency and accountability within the Bittensor network.
- root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True)#
Registers the neuron associated with the wallet on the root network. This process is integral for participating in the highest layer of decision-making and governance within the Bittensor network.
- Parameters:
wallet (bittensor_wallet.wallet) – The wallet associated with the neuron to be registered on the root network.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Defaults to False.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to True.
- Returns:
True
if the registration on the root network is successful, False otherwise.- Return type:
This function enables neurons to engage in the most critical and influential aspects of the network’s governance, signifying a high level of commitment and responsibility in the Bittensor ecosystem.
- root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=False, wait_for_finalization=False)#
Sets the weights for neurons on the root network. This action is crucial for defining the influence and interactions of neurons at the root level of the Bittensor network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron setting the weights.
netuids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs for which weights are being set.
weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int, optional) – Version key for compatibility with the network. Default is
0
.wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block. Defaults to
False
.wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain. Defaults to
False
.
- Returns:
True
if the setting of root-level weights is successful, False otherwise.- Return type:
This function plays a pivotal role in shaping the root network’s collective intelligence and decision-making processes, reflecting the principles of decentralized governance and collaborative learning in Bittensor.
- serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True, certificate=None)#
Registers an
Axon
serving endpoint on the Bittensor network for a specific neuron. This function is used to set up the Axon, a key component of a neuron that handles incoming queries and data processing tasks.- Parameters:
netuid (int) – The unique identifier of the subnetwork.
axon (bittensor.core.axon.Axon) – The Axon instance to be registered for serving.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
True
.certificate (Optional[bittensor.utils.Certificate])
- Returns:
True
if the Axon serve registration is successful, False otherwise.- Return type:
By registering an Axon, the neuron becomes an active part of the network’s distributed computing infrastructure, contributing to the collective intelligence of Bittensor.
- set_weights(wallet, netuid, uids, weights, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)#
Sets the inter-neuronal weights for the specified neuron. This process involves specifying the influence or trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor’s decentralized learning architecture.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron setting the weights.
netuid (int) – The unique identifier of the subnet.
uids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.
weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int) – Version key for compatibility with the network. Default is
int representation of Bittensor version.
.wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
False
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.max_retries (int) – The number of maximum attempts to set weights. Default is
5
.
- Returns:
True
if the setting of weights is successful, False otherwise. And msg, a string value describing the success or potential error.- Return type:
This function is crucial in shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.
- static setup_config(network, config)#
Sets up and returns the configuration for the Subtensor network and endpoint.
This method determines the appropriate network and chain endpoint based on the provided network string or configuration object. It evaluates the network and endpoint in the following order of precedence: 1. Provided network string. 2. Configured chain endpoint in the config object. 3. Configured network in the config object. 4. Default chain endpoint. 5. Default network.
- Parameters:
network (Optional[str]) – The name of the Subtensor network. If None, the network and endpoint will be determined from the config object.
config (bittensor.core.config.Config) – The configuration object containing the network and chain endpoint settings.
- Returns:
A tuple containing the formatted WebSocket endpoint URL and the evaluated network name.
- Return type:
- state_call(method, data, block=None)#
Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain’s state. This function is typically used for advanced queries that require specific method calls and data inputs.
- Parameters:
- Returns:
The result of the rpc call.
- Return type:
result (dict[Any, Any])
The state call function provides a more direct and flexible way of querying blockchain data, useful for specific use cases where standard queries are insufficient.
- subnet_exists(netuid, block=None)#
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
- Parameters:
- Returns:
True
if the subnet exists, False otherwise.- Return type:
This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network’s structure and composition.
- subnetwork_n(netuid, block=None)#
Returns network SubnetworkN hyperparameter.
- Parameters:
- Returns:
The value of the SubnetworkN hyperparameter, or
None
if the subnetwork does not exist or the parameter is not found.- Return type:
Optional[int]
- substrate: substrateinterface.base.SubstrateInterface = None#
- tempo(netuid, block=None)#
Returns network Tempo hyperparameter.
- Parameters:
- Returns:
The value of the Tempo hyperparameter, or
None
if the subnetwork does not exist or the parameter is not found.- Return type:
Optional[int]
- transfer(wallet, dest, amount, wait_for_inclusion=True, wait_for_finalization=False)#
Executes a transfer of funds from the provided wallet to the specified destination address. This function is used to move TAO tokens within the Bittensor network, facilitating transactions between neurons.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet from which funds are being transferred.
dest (str) – The destination public key address.
amount (Union[bittensor.utils.balance.Balance, float]) – The amount of TAO to be transferred.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Default is
True
.wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is
False
.
- Returns:
True
if the transfer is successful, False otherwise.- Return type:
transfer_extrinsic (bool)
This function is essential for the fluid movement of tokens in the network, supporting various economic activities such as staking, delegation, and reward distribution.
- tx_rate_limit(block=None)#
Retrieves the transaction rate limit for the Bittensor network as of a specific blockchain block. This rate limit sets the maximum number of transactions that can be processed within a given time frame.
- Parameters:
block (Optional[int]) – The blockchain block number at which to perform the query.
- Returns:
The transaction rate limit of the network, None if not available.
- Return type:
Optional[int]
The transaction rate limit is an essential parameter for ensuring the stability and scalability of the Bittensor network. It helps in managing network load and preventing congestion, thereby maintaining efficient and timely transaction processing.
- unstake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False)#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor_wallet.wallet) – The wallet associated with the neuron from which the stake is being removed.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey account to unstake from.amount (Union[Balance, float]) – The amount of TAO to unstake. If not specified, unstakes all.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
True
if the unstaking process is successful, False otherwise.- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
- unstake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False)#
Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts efficiently. This function is useful for managing the distribution of stakes across multiple neurons.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet linked to the coldkey from which the stakes are being withdrawn.
hotkey_ss58s (List[str]) – A list of hotkey
SS58
addresses to unstake from.amounts (List[Union[Balance, float]]) – The amounts of TAO to unstake from each hotkey. If not provided, unstakes all available stakes.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
True
if the batch unstaking is successful, False otherwise.- Return type:
This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake management aspect of the Bittensor network.
- websocket#
- weights(netuid, block=None)#
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron’s UID to the weights it assigns to other neurons, reflecting the network’s trust and value assignment mechanisms.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its assigned weights.
- Return type:
The weight distribution is a key factor in the network’s consensus algorithm and the ranking of neurons, influencing their influence and reward allocation within the subnet.
- weights_rate_limit(netuid)#
Returns network WeightsSetRateLimit hyperparameter.
- class bittensor.Synapse(/, **data)#
Bases:
pydantic.BaseModel
Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes).
Synapses ensure the format and correctness of transmission tensors according to the Bittensor protocol. Each Synapse type is tailored for a specific machine learning (ML) task, following unique compression and communication processes. This helps maintain sanitized, correct, and useful information flow across the network.
The Synapse class encompasses essential network properties such as HTTP route names, timeouts, request sizes, and terminal information. It also includes methods for serialization, deserialization, attribute setting, and hash computation, ensuring secure and efficient data exchange in the network.
The class includes Pydantic validators and root validators to enforce data integrity and format. Additionally, properties like
is_success
,is_failure
,is_timeout
, etc., provide convenient status checks based on dendrite responses.Think of Bittensor Synapses as glorified pydantic wrappers that have been designed to be used in a distributed network. They provide a standardized way to communicate between neurons, and are the primary mechanism for communication between neurons in Bittensor.
Key Features:
- HTTP Route Name (
name
attribute): Enables the identification and proper routing of requests within the network. Essential for users defining custom routes for specific machine learning tasks.
- HTTP Route Name (
- Query Timeout (
timeout
attribute): Determines the maximum duration allowed for a query, ensuring timely responses and network efficiency. Crucial for users to manage network latency and response times, particularly in time-sensitive applications.
- Query Timeout (
- Request Sizes (
total_size
,header_size
attributes): Keeps track of the size of request bodies and headers, ensuring efficient data transmission without overloading the network. Important for users to monitor and optimize the data payload, especially in bandwidth-constrained environments.
- Request Sizes (
- Terminal Information (
dendrite
,axon
attributes): Stores information about the dendrite (receiving end) and axon (sending end), facilitating communication between nodes. Users can access detailed information about the communication endpoints, aiding in debugging and network analysis.
- Terminal Information (
- Body Hash Computation (
computed_body_hash
,required_hash_fields
): Ensures data integrity and security by computing hashes of transmitted data. Provides users with a mechanism to verify data integrity and detect any tampering during transmission. It is recommended that names of fields in required_hash_fields are listed in the order they are defined in the class.
- Body Hash Computation (
- Serialization and Deserialization Methods:
Facilitates the conversion of Synapse objects to and from a format suitable for network transmission. Essential for users who need to customize data formats for specific machine learning models or tasks.
- Status Check Properties (
is_success
,is_failure
,is_timeout
, etc.): Provides quick and easy methods to check the status of a request, improving error handling and response management. Users can efficiently handle different outcomes of network requests, enhancing the robustness of their applications.
- Status Check Properties (
Example usage:
# Creating a Synapse instance with default values from bittensor.core.synapse import Synapse synapse = Synapse() # Setting properties and input synapse.timeout = 15.0 synapse.name = "MySynapse" # Not setting fields that are not defined in your synapse class will result in an error, e.g.: synapse.dummy_input = 1 # This will raise an error because dummy_input is not defined in the Synapse class # Get a dictionary of headers and body from the synapse instance synapse_dict = synapse.model_dump_json() # Get a dictionary of headers from the synapse instance headers = synapse.to_headers() # Reconstruct the synapse from headers using the classmethod 'from_headers' synapse = Synapse.from_headers(headers) # Deserialize synapse after receiving it over the network, controlled by `deserialize` method deserialized_synapse = synapse.deserialize() # Checking the status of the request if synapse.is_success: print("Request succeeded") # Checking and setting the status of the request print(synapse.axon.status_code) synapse.axon.status_code = 408 # Timeout
- Parameters:
name (str) – HTTP route name, set on
axon.attach()
.timeout (float) – Total query length, set by the dendrite terminal.
total_size (int) – Total size of request body in bytes.
header_size (int) – Size of request header in bytes.
dendrite (
TerminalInfo()
) – Information about the dendrite terminal.axon (
TerminalInfo()
) – Information about the axon terminal.computed_body_hash (str) – Computed hash of the request body.
required_hash_fields (list[str]) – Fields required to compute the body hash.
data (Any)
- __setattr__()#
Override method to make
required_hash_fields
read-only.- Parameters:
name (str)
value (Any)
- parse_headers_to_inputs()#
Parses headers to construct an inputs dictionary.
- from_headers()#
Creates an instance from a headers dictionary.
This class is a cornerstone in the Bittensor framework, providing the necessary tools for secure, efficient, and standardized communication in a decentralized environment.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- __setattr__(name, value)#
Override the
__setattr__()
method to make therequired_hash_fields
property read-only.This is a security mechanism such that the
required_hash_fields
property cannot be overridden by the user or malicious code.- Parameters:
name (str)
value (Any)
- _extract_header_size#
- _extract_timeout#
- _extract_total_size#
- axon: TerminalInfo | None#
- property body_hash: str#
Computes a SHA3-256 hash of the serialized body of the Synapse instance.
This hash is used to ensure the data integrity and security of the Synapse instance when it’s transmitted across the network. It is a crucial feature for verifying that the data received is the same as the data sent.
Process:
Iterates over each required field as specified in
required_hash_fields
.Concatenates the string representation of these fields.
Applies SHA3-256 hashing to the concatenated string to produce a unique fingerprint of the data.
Example:
synapse = Synapse(name="ExampleRoute", timeout=10) hash_value = synapse.body_hash # hash_value is the SHA3-256 hash of the serialized body of the Synapse instance
- Returns:
The SHA3-256 hash as a hexadecimal string, providing a fingerprint of the Synapse instance’s data for integrity checks.
- Return type:
- dendrite: TerminalInfo | None#
- deserialize()#
Deserializes the Synapse object.
This method is intended to be overridden by subclasses for custom deserialization logic. In the context of the Synapse superclass, this method simply returns the instance itself. When inheriting from this class, subclasses should provide their own implementation for deserialization if specific deserialization behavior is desired.
By default, if a subclass does not provide its own implementation of this method, the Synapse’s deserialize method will be used, returning the object instance as-is.
In its default form, this method simply returns the instance of the Synapse itself without any modifications. Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting serialized data back into complex object types or performing additional data integrity checks.
Example:
class CustomSynapse(Synapse): additional_data: str def deserialize(self) -> "CustomSynapse": # Custom deserialization logic # For example, decoding a base64 encoded string in 'additional_data' if self.additional_data: self.additional_data = base64.b64decode(self.additional_data).decode('utf-8') return self serialized_data = '{"additional_data": "SGVsbG8gV29ybGQ="}' # Base64 for 'Hello World' custom_synapse = CustomSynapse.model_validate_json(serialized_data) deserialized_synapse = custom_synapse.deserialize() # deserialized_synapse.additional_data would now be 'Hello World'
- Returns:
The deserialized Synapse object. In this default implementation, it returns the object itself.
- Return type:
- property failed_verification: bool#
Checks if the dendrite’s status code indicates failed verification.
This method returns
True
if the status code of the dendrite is401
, which is the HTTP status code for unauthorized access.- Returns:
True
if dendrite’s status code is401
,False
otherwise.- Return type:
- classmethod from_headers(headers)#
Constructs a new Synapse instance from a given headers dictionary, enabling the re-creation of the Synapse’s state as it was prior to network transmission.
This method is a key part of the deserialization process in the Bittensor network, allowing nodes to accurately reconstruct Synapse objects from received data.
Example:
received_headers = { 'bt_header_axon_address': '127.0.0.1', 'bt_header_dendrite_port': '8080', # Other headers... } synapse = Synapse.from_headers(received_headers) # synapse is a new Synapse instance reconstructed from the received headers
- Parameters:
headers (dict) – The dictionary of headers containing serialized Synapse information.
- Returns:
A new instance of Synapse, reconstructed from the parsed header information, replicating the original instance’s state.
- Return type:
- get_required_fields()#
Get the required fields from the model’s JSON schema.
- get_total_size()#
Get the total size of the current object.
This method first calculates the size of the current object, then assigns it to the instance variable
self.total_size()
and finally returns this value.- Returns:
The total size of the current object.
- Return type:
- property is_blacklist: bool#
Checks if the dendrite’s status code indicates a blacklisted request.
This method returns
True
if the status code of the dendrite is403
, which is the HTTP status code for a forbidden request.- Returns:
True
if dendrite’s status code is403
,False
otherwise.- Return type:
- property is_failure: bool#
Checks if the dendrite’s status code indicates failure.
This method returns
True
if the status code of the dendrite is not200
, which would mean the HTTP request was not successful.- Returns:
True
if dendrite’s status code is not200
,False
otherwise.- Return type:
- property is_success: bool#
Checks if the dendrite’s status code indicates success.
This method returns
True
if the status code of the dendrite is200
, which typically represents a successful HTTP request.- Returns:
True
if dendrite’s status code is200
,False
otherwise.- Return type:
- property is_timeout: bool#
Checks if the dendrite’s status code indicates a timeout.
This method returns
True
if the status code of the dendrite is408
, which is the HTTP status code for a request timeout.- Returns:
True
if dendrite’s status code is408
,False
otherwise.- Return type:
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod parse_headers_to_inputs(headers)#
Interprets and transforms a given dictionary of headers into a structured dictionary, facilitating the reconstruction of Synapse objects.
This method is essential for parsing network-transmitted data back into a Synapse instance, ensuring data consistency and integrity.
Process:
Separates headers into categories based on prefixes (
axon
,dendrite
, etc.).Decodes and deserializes
input_obj
headers into their original objects.Assigns simple fields directly from the headers to the input dictionary.
Example:
received_headers = { 'bt_header_axon_address': '127.0.0.1', 'bt_header_dendrite_port': '8080', # Other headers... } inputs = Synapse.parse_headers_to_inputs(received_headers) # inputs now contains a structured representation of Synapse properties based on the headers
Note
This is handled automatically when calling
Synapse.from_headers(headers)()
and does not need to be called directly.
- to_headers()#
Converts the state of a Synapse instance into a dictionary of HTTP headers.
This method is essential for packaging Synapse data for network transmission in the Bittensor framework, ensuring that each key aspect of the Synapse is represented in a format suitable for HTTP communication.
Process:
Basic Information: It starts by including the
name
andtimeout
of the Synapse, which are fundamental for identifying the query and managing its lifespan on the network.Complex Objects: The method serializes the
axon
anddendrite
objects, if present, into strings. This serialization is crucial for preserving the state and structure of these objects over the network.Encoding: Non-optional complex objects are serialized and encoded in base64, making them safe for HTTP transport.
Size Metrics: The method calculates and adds the size of headers and the total object size, providing valuable information for network bandwidth management.
Example Usage:
synapse = Synapse(name="ExampleSynapse", timeout=30) headers = synapse.to_headers() # headers now contains a dictionary representing the Synapse instance
- Returns:
A dictionary containing key-value pairs representing the Synapse’s properties, suitable for HTTP communication.
- Return type:
- exception bittensor.SynapseDendriteNoneException(message='Synapse Dendrite is None', synapse=None)#
Bases:
SynapseException
Common base class for all non-exit exceptions.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- message#
- exception bittensor.SynapseParsingError#
Bases:
Exception
This exception is raised when the request headers are unable to be parsed into the synapse type.
Initialize self. See help(type(self)) for accurate signature.
- bittensor.T#
- class bittensor.Tensor(/, **data)#
Bases:
pydantic.BaseModel
Represents a Tensor object.
- Parameters:
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- _extract_dtype#
- _extract_shape#
- deserialize()#
Deserializes the Tensor object.
- Returns:
The deserialized tensor object.
- Return type:
np.array or torch.Tensor
- Raises:
Exception – If the deserialization process encounters an error.
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- numpy()#
- Return type:
- static serialize(tensor_)#
Serializes the given tensor.
- Parameters:
tensor (np.array or torch.Tensor) – The tensor to serialize.
tensor_ (Union[numpy.ndarray, bittensor.utils.registration.torch.Tensor])
- Returns:
The serialized tensor.
- Return type:
- Raises:
Exception – If the serialization process encounters an error.
- tensor()#
- Return type:
Union[numpy.ndarray, bittensor.utils.registration.torch.Tensor]
- class bittensor.TerminalInfo(/, **data)#
Bases:
pydantic.BaseModel
TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process.
This class serves as a metadata carrier, providing essential details about the state and configuration of a terminal during network interactions. This is a crucial class in the Bittensor framework.
The TerminalInfo class contains information such as HTTP status codes and messages, processing times, IP addresses, ports, Bittensor version numbers, and unique identifiers. These details are vital for maintaining network reliability, security, and efficient data flow within the Bittensor network.
This class includes Pydantic validators and root validators to enforce data integrity and format. It is designed to be used natively within Synapses, so that you will not need to call this directly, but rather is used as a helper class for Synapses.
- Parameters:
status_code (int) – HTTP status code indicating the result of a network request. Essential for identifying the outcome of network interactions.
status_message (str) – Descriptive message associated with the status code, providing additional context about the request’s result.
process_time (float) – Time taken by the terminal to process the call, important for performance monitoring and optimization.
ip (str) – IP address of the terminal, crucial for network routing and data transmission.
port (int) – Network port used by the terminal, key for establishing network connections.
version (int) – Bittensor version running on the terminal, ensuring compatibility between different nodes in the network.
nonce (int) – Unique, monotonically increasing number for each terminal, aiding in identifying and ordering network interactions.
uuid (str) – Unique identifier for the terminal, fundamental for network security and identification.
hotkey (str) – Encoded hotkey string of the terminal wallet, important for transaction and identity verification in the network.
signature (str) – Digital signature verifying the tuple of nonce, axon_hotkey, dendrite_hotkey, and uuid, critical for ensuring data authenticity and security.
data (Any)
Usage:
# Creating a TerminalInfo instance from bittensor.core.synapse import TerminalInfo terminal_info = TerminalInfo( status_code=200, status_message="Success", process_time=0.1, ip="198.123.23.1", port=9282, version=111, nonce=111111, uuid="5ecbd69c-1cec-11ee-b0dc-e29ce36fec1a", hotkey="5EnjDGNqqWnuL2HCAdxeEtN2oqtXZw6BMBe936Kfy2PFz1J1", signature="0x0813029319030129u4120u10841824y0182u091u230912u" ) # Accessing TerminalInfo attributes ip_address = terminal_info.ip processing_duration = terminal_info.process_time # TerminalInfo can be used to monitor and verify network interactions, ensuring proper communication and security within the Bittensor network.
TerminalInfo plays a pivotal role in providing transparency and control over network operations, making it an indispensable tool for developers and users interacting with the Bittensor ecosystem.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- _extract_nonce#
- _extract_port#
- _extract_process_time#
- _extract_status_code#
- _extract_version#
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- exception bittensor.TransferError#
Bases:
ChainTransactionError
Error raised when a transfer transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.UnknownSynapseError(message='Synapse Exception', synapse=None)#
Bases:
SynapseException
This exception is raised when the request name is not found in the Axon’s forward_fns dictionary.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
synapse (bittensor.core.synapse.Synapse | None)
- exception bittensor.UnstakeError#
Bases:
ChainTransactionError
Error raised when an unstake transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- bittensor.__archive_entrypoint__#
- bittensor.__blocktime__#
- bittensor.__finney_entrypoint__#
- bittensor.__finney_test_entrypoint__#
- bittensor.__getattr__(name)#
- bittensor.__local_entrypoint__#
- bittensor.__network_explorer_map__#
- bittensor.__networks__#
- bittensor.__pipaddress__#
- bittensor.__rao_symbol__#
- bittensor.__ss58_address_length__#
- bittensor.__ss58_format__#
- bittensor.__tao_symbol__#
- bittensor.__type_registry__#
- bittensor.__version__#
- async bittensor.async_subtensor(network=DEFAULT_NETWORK)#
Creates an initialised AsyncSubtensor object.
- Parameters:
network (str)
- Return type:
- bittensor.axon#
- bittensor.config#
- bittensor.debug(on=True)#
Enables or disables debug logging. :param on: If True, enables debug logging. If False, disables debug logging. :type on: bool
- Parameters:
on (bool)
- bittensor.dendrite#
- bittensor.extrinsics_subpackage#
- bittensor.get_explorer_url_for_network(network, block_hash, network_map)#
Returns the explorer url for the given block hash and network.
- Parameters:
- Returns:
The explorer url for the given block hash and network. Or None if the network is not known.
- Return type:
- bittensor.get_hash(content, encoding='utf-8')#
- bittensor.info(on=True)#
Enables or disables info logging. :param on: If True, enables info logging. If False, disables info logging and sets default (WARNING) level. :type on: bool
- Parameters:
on (bool)
- bittensor.keyfile#
- bittensor.logging#
- bittensor.logging#
- bittensor.metagraph#
- bittensor.mock_subpackage#
- bittensor.ss58_address_to_bytes(ss58_address)#
Converts a ss58 address to a bytes object.
- bittensor.strtobool(val)#
Converts a string to a boolean value.
truth-y values are ‘y’, ‘yes’, ‘t’, ‘true’, ‘on’, and ‘1’; false-y values are ‘n’, ‘no’, ‘f’, ‘false’, ‘off’, and ‘0’.
Raises ValueError if ‘val’ is anything else.
- bittensor.subtensor#
- bittensor.synapse#
- bittensor.trace(on=True)#
Enables or disables trace logging. :param on: If True, enables trace logging. If False, disables trace logging. :type on: bool
- Parameters:
on (bool)
- bittensor.version_checking(timeout=15)#
Deprecated, kept for backwards compatibility. Use check_version() instead.
- Parameters:
timeout (int) – The timeout for calling :func:
check_version
function. Default is15
.
- bittensor.version_split#
- bittensor.wallet#