bittensor#
Subpackages#
Submodules#
Attributes#
Metagraph class that uses |
|
Exceptions#
In place of YAMLError |
|
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. |
|
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#
The |
|
The AxonInfo class represents information about an axon endpoint in the bittensor network. This includes |
|
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. |
|
Dataclass representing information related to Prometheus. |
|
Dataclass for delegate information. For a lighter version of this class, see |
|
Dataclass for representing stake information linked to hotkey and coldkey pairs. |
|
Dataclass for subnet info. |
|
This class represents the hyperparameters for a subnet. |
|
Dataclass representing IP information. |
|
This TypedDict represents the data structure for a proposal vote in the Senate. |
|
A Config with a set of default values. |
|
Implementation of the config class, which manages the configuration of different Bittensor modules. |
|
The Dendrite class represents the abstracted implementation of a network client module. |
|
The |
|
The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, |
|
TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process. |
|
Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes). |
|
Represents a Tensor object. |
|
Base threadpool executor with a priority queue. |
|
Represents the bittensor balance of the wallet, stored as rao (int). |
|
A Mock Subtensor class for running tests. |
|
This class is not used within the bittensor package, but is actively used by the community. |
Functions#
|
|
|
Deprecated, kept for backwards compatibility. Use check_version() instead. |
|
Converts a string to a boolean value. |
|
Returns the explorer url for the given block hash and network. |
|
Converts a ss58 address to a bytes object. |
|
|
|
Enables or disables trace logging. |
|
Enables or disables debug logging. |
|
Enables or disables warning logging. |
|
Package Contents#
- bittensor.__version__#
- bittensor.version_split#
- bittensor.DEFAULTS#
- bittensor.logging#
- class bittensor.Axon(wallet=None, config=None, port=None, ip=None, external_ip=None, external_port=None, max_workers=None)[source]#
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.
- ip#
- port#
- external_ip#
- external_port#
- max_workers#
- wallet#
- uuid#
- full_address#
- started = False#
- thread_pool#
- forward_class_types: dict[str, list[inspect.Signature]]#
- app#
- log_level#
- fast_config#
- fast_server#
- router#
- middleware_cls#
- attach(forward_fn, blacklist_fn=None, priority_fn=None, verify_fn=None)[source]#
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 help()[source]#
Prints the help text (list of command-line arguments and their descriptions) to stdout.
- classmethod add_args(parser, prefix=None)[source]#
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.
- async verify_body_integrity(request)[source]#
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.
- classmethod check_config(config)[source]#
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]
- __repr__()[source]#
Provides a machine-readable (unambiguous) representation of the Axon instance. It is made identical to __str__ in this case.
- Return type:
- __del__()[source]#
This magic method is called when the Axon object is about to be destroyed. It ensures that the Axon server shuts down properly.
- start()[source]#
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.
- stop()[source]#
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.
- serve(netuid, subtensor=None)[source]#
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.
- 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.
- async default_verify(synapse)[source]#
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.
- class bittensor.AxonInfo[source]#
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).
- to_string()[source]#
Converts the AxonInfo object to a string representation using JSON.
- Return type:
- classmethod from_string(json_string)[source]#
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.
- class bittensor.NeuronInfo[source]#
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.
- stake_dict: dict[str, bittensor.utils.balance.Balance]#
- total_stake: bittensor.utils.balance.Balance#
- prometheus_info: bittensor.core.chain_data.prometheus_info.PrometheusInfo | None = None#
- axon_info: bittensor.core.chain_data.axon_info.AxonInfo | None = None#
- classmethod from_weights_bonds_and_neuron_lite(neuron_lite, weights_as_dict, bonds_as_dict)[source]#
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:
- class bittensor.NeuronInfoLite[source]#
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.
- list_from_vec_u8()[source]#
Decodes a bytes object into a list of NeuronInfoLite instances.
- Parameters:
vec_u8 (bytes)
- Return type:
- stake_dict: dict[str, bittensor.utils.balance.Balance]#
- total_stake: bittensor.utils.balance.Balance#
- prometheus_info: bittensor.core.chain_data.prometheus_info.PrometheusInfo | None#
- axon_info: bittensor.core.chain_data.axon_info.AxonInfo | None#
- class bittensor.PrometheusInfo[source]#
Dataclass representing information related to Prometheus.
- Variables:
- class bittensor.DelegateInfo[source]#
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.
- total_stake: bittensor.utils.balance.Balance#
- nominators: list[tuple[str, bittensor.utils.balance.Balance]]#
- return_per_1000: bittensor.utils.balance.Balance#
- total_daily_return: bittensor.utils.balance.Balance#
- classmethod from_vec_u8(vec_u8)[source]#
- Parameters:
vec_u8 (bytes)
- Return type:
Optional[DelegateInfo]
- class bittensor.StakeInfo[source]#
Dataclass for representing stake information linked to hotkey and coldkey pairs.
- Variables:
- classmethod fix_decoded_values(decoded)[source]#
Fixes the decoded values.
- Parameters:
decoded (Any)
- Return type:
- class bittensor.SubnetInfo[source]#
Dataclass for subnet info.
- class bittensor.SubnetHyperparameters[source]#
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)[source]#
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.IPInfo[source]#
Dataclass representing IP information.
- Variables:
- classmethod fix_decoded_values(decoded)[source]#
Returns a SubnetInfo object from a decoded IPInfo dictionary.
- bittensor.ProposalCallData#
- class bittensor.ProposalVoteData[source]#
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.InvalidConfigFile[source]#
Bases:
Exception
In place of YAMLError
Initialize self. See help(type(self)) for accurate signature.
- class bittensor.DefaultConfig(parser=None, args=None, strict=False, default=None)[source]#
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])
- class bittensor.Config(parser=None, args=None, strict=False, default=None)[source]#
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.
- missing_required_args#
- config_params#
- strict#
- params#
- _config#
- parser_no_defaults#
- default_param_args#
- default_params#
- all_default_args#
- defaults_as_suppress#
- params_no_defaults#
- static __split_params__(params, _config)[source]#
- Parameters:
params (argparse.Namespace)
_config (Config)
- static __parse_args__(args, parser=None, strict=False)[source]#
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__()[source]#
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:
- classmethod _merge(a, b)[source]#
Merge two configurations recursively. If there is a conflict, the value from the second configuration will take precedence.
- merge(b)[source]#
Merges the current config with another config.
- Parameters:
b (bittensor.core.config.Config) – Another config to merge.
- classmethod merge_all(configs)[source]#
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)
- is_set(param_name)[source]#
Returns a boolean indicating whether the parameter has been set or is still the default.
- __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:
- bittensor.T#
- class bittensor.Dendrite(wallet=None)[source]#
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.
- exception bittensor.BlacklistedException(message='Synapse Exception', synapse=None)[source]#
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[source]#
Bases:
ChainError
Error for any chain connection related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainError[source]#
Bases:
BaseException
Base error for any chain related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainQueryError[source]#
Bases:
ChainError
Error for any chain query related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.ChainTransactionError[source]#
Bases:
ChainError
Error for any chain transaction related errors.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.IdentityError[source]#
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)[source]#
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.InvalidRequestNameError[source]#
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[source]#
Bases:
ChainTransactionError
Error raised when metadata commitment transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.NominationError[source]#
Bases:
ChainTransactionError
Error raised when a nomination transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.NotDelegateError[source]#
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[source]#
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)[source]#
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)[source]#
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)[source]#
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)
- exception bittensor.RegistrationError[source]#
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)[source]#
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[source]#
Bases:
ChainTransactionError
Error raised when a stake transaction fails.
Initialize self. See help(type(self)) for accurate signature.
- exception bittensor.SynapseDendriteNoneException(message='Synapse Dendrite is None', synapse=None)[source]#
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[source]#
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.
- exception bittensor.TransferError[source]#
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)[source]#
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[source]#
Bases:
ChainTransactionError
Error raised when an unstake 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.
- bittensor.BLOCKTIME = 12#
- class bittensor.StreamingSynapse(/, **data)[source]#
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)
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class BTStreamingResponse(model, *, synapse=None, **kwargs)[source]#
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.
- token_streamer#
- synapse#
- async stream_response(send)[source]#
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.
- async __call__(scope, receive, send)[source]#
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.
- abstract process_streaming_response(response)[source]#
- 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.
- abstract extract_response_json(response)[source]#
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:
- create_streaming_response(token_streamer)[source]#
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)
- class bittensor.Subtensor(network=None, config=None, _mock=False, log_verbose=False, connection_timeout=600)[source]#
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
.
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#
- log_verbose#
- _connection_timeout#
- substrate: substrateinterface.base.SubstrateInterface = None#
- close()[source]#
Cleans up resources for this subtensor instance like active websocket connection and active extensions.
- _get_substrate()[source]#
Establishes a connection to the Substrate node using configured parameters.
- static config()[source]#
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 setup_config(network, config)[source]#
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:
- classmethod add_args(parser, prefix=None)[source]#
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)
- _encode_params(call_definition, params)[source]#
Returns a hex encoded string of the params using their types.
- _get_hyperparameter(param_name, netuid, block=None)[source]#
Retrieves a specified hyperparameter for a specific subnet.
- Parameters:
- Returns:
The value of the specified hyperparameter if the subnet exists,
None
otherwise.- Return type:
- query_subtensor(name, block=None, params=None)[source]#
Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to retrieve specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific attributes.
- Parameters:
- Returns:
An object containing the requested data.
- Return type:
query_response (scalecodec.ScaleType)
This query function is essential for accessing detailed information about the network and its neurons, providing valuable insights into the state and dynamics of the Bittensor ecosystem.
- query_map_subtensor(name, block=None, params=None)[source]#
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_runtime_api(runtime_api, method, params, block=None)[source]#
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.
- state_call(method, data, block=None)[source]#
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.
- query_map(module, name, block=None, params=None)[source]#
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_constant(module_name, constant_name, block=None)[source]#
Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.
- Parameters:
- 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_module(module, name, block=None, params=None)[source]#
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.
- metagraph(netuid, lite=True, block=None)[source]#
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.
- static determine_chain_endpoint_and_network(network)[source]#
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:
- get_netuids_for_hotkey(hotkey_ss58, block=None)[source]#
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_current_block()[source]#
Returns the current block number on the Bittensor blockchain. This function provides the latest block number, indicating the most recent state of the blockchain.
- Returns:
The current chain block number.
- Return type:
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.
- is_hotkey_registered_any(hotkey_ss58, block=None)[source]#
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)[source]#
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.
- is_hotkey_registered(hotkey_ss58, netuid=None, block=None)[source]#
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.
- set_weights(wallet, netuid, uids, weights, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)[source]#
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】.
- root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=False, wait_for_finalization=False)[source]#
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.
- 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)[source]#
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.
- root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True)[source]#
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) – 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.
- burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True)[source]#
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:
- serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True)[source]#
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
.
- 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.
- property block: int#
Returns current chain block.
- Returns:
Current chain block.
- Return type:
block (int)
- blocks_since_last_update(netuid, uid)[source]#
Returns the number of blocks since the last update for a specific UID in the subnetwork.
- get_block_hash(block_id)[source]#
Retrieves the hash of a specific block on the Bittensor blockchain. The block hash is a unique identifier representing the cryptographic hash of the block’s content, ensuring its integrity and immutability.
- Parameters:
block_id (int) – The block number for which the hash is to be retrieved.
- Returns:
The cryptographic hash of the specified block.
- Return type:
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.
- commit(wallet, netuid, data)[source]#
Commits arbitrary data to the Bittensor network by publishing metadata.
- subnetwork_n(netuid, block=None)[source]#
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]
- transfer(wallet, dest, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#
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.
- get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None)[source]#
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.
- neuron_for_uid(uid, netuid, block=None)[source]#
Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron’s attributes, including its stake, rank, and operational status.
- Parameters:
- 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.
- get_subnet_hyperparameters(netuid, block=None)[source]#
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.
- immunity_period(netuid, block=None)[source]#
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.
- get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None)[source]#
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.
- tempo(netuid, block=None)[source]#
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]
- get_commitment(netuid, uid, block=None)[source]#
Retrieves the on-chain commitment for a specific neuron in the Bittensor network.
- Parameters:
- Returns:
The commitment data as a string.
- Return type:
- min_allowed_weights(netuid, block=None)[source]#
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]
- max_weight_limit(netuid, block=None)[source]#
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]
- get_prometheus_info(netuid, hotkey_ss58, block=None)[source]#
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]
- subnet_exists(netuid, block=None)[source]#
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.
- get_all_subnets_info(block=None)[source]#
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.
- bonds(netuid, block=None)[source]#
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.
- get_subnet_burn_cost(block=None)[source]#
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.
- neurons(netuid, block=None)[source]#
Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet’s neuron population, including each neuron’s attributes and network interactions.
- Parameters:
- 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.
- get_total_subnets(block=None)[source]#
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_subnets(block=None)[source]#
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.
- neurons_lite(netuid, block=None)[source]#
Retrieves a list of neurons in a ‘lite’ format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network participation.
- Parameters:
- 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.
- weights(netuid, block=None)[source]#
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.
- get_balance(address, block=None)[source]#
Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.
- Parameters:
- 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_transfer_fee(wallet, dest, value)[source]#
Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This function simulates the transfer to estimate the associated cost, taking into account the current network conditions and transaction complexity.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet from which the transfer is initiated.
dest (str) – The
SS58
address of the destination account.value (Union[bittensor.utils.balance.Balance, float, int]) – The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units.
- Returns:
The estimated transaction fee for the transfer, represented as a Balance object.
- Return type:
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_existential_deposit(block=None)[source]#
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.
- commit_weights(wallet, netuid, salt, uids, weights, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)[source]#
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.
- reveal_weights(wallet, netuid, uids, weights, salt, version_key=settings.version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5)[source]#
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.
- difficulty(netuid, block=None)[source]#
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.
- recycle(netuid, block=None)[source]#
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.
- get_delegate_take(hotkey_ss58, block=None)[source]#
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_delegate_by_hotkey(hotkey_ss58, block=None)[source]#
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.
- _do_serve_axon#
- class bittensor.TerminalInfo(/, **data)[source]#
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.
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- _extract_process_time#
- _extract_port#
- _extract_version#
- _extract_nonce#
- _extract_status_code#
- class bittensor.Synapse(/, **data)[source]#
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__()[source]#
Override method to make
required_hash_fields
read-only.- Parameters:
name (str)
value (Any)
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.
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- deserialize()[source]#
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:
- dendrite: TerminalInfo | None#
- axon: TerminalInfo | None#
- _extract_total_size#
- _extract_header_size#
- _extract_timeout#
- __setattr__(name, value)[source]#
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)
- get_total_size()[source]#
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_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_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_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:
- 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 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:
- to_headers()[source]#
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:
- 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:
- classmethod parse_headers_to_inputs(headers)[source]#
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.
- classmethod from_headers(headers)[source]#
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:
- class bittensor.Tensor(/, **data)[source]#
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.
- model_config#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- tensor()[source]#
- Return type:
Union[numpy.ndarray, bittensor.utils.registration.torch.Tensor]
- deserialize()[source]#
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.
- static serialize(tensor_)[source]#
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.
- _extract_shape#
- _extract_dtype#
- class bittensor.PriorityThreadPoolExecutor(maxsize=-1, max_workers=None, thread_name_prefix='', initializer=None, initargs=())[source]#
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.
- _counter#
- _max_workers#
- _work_queue#
- _idle_semaphore#
- _threads#
- _broken = False#
- _shutdown = False#
- _shutdown_lock#
- _thread_name_prefix#
- _initializer#
- _initargs#
- classmethod add_args(parser, prefix=None)[source]#
Accept specific arguments from parser
- Parameters:
parser (argparse.ArgumentParser)
prefix (str)
- classmethod config()[source]#
Get config from the argument parser.
Return:
bittensor.Config()
object.- Return type:
- property is_empty#
- submit(fn, *args, **kwargs)[source]#
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
- shutdown(wait=True)[source]#
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.
- bittensor.version_checking(timeout=15)[source]#
Deprecated, kept for backwards compatibility. Use check_version() instead.
- Parameters:
timeout (int) – The timeout for calling :func:
check_version
function. Default is15
.
- bittensor.strtobool(val)[source]#
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.get_explorer_url_for_network(network, block_hash, network_map)[source]#
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:
- class bittensor.Balance(balance)[source]#
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).
- property tao#
- __str__()[source]#
Returns the Balance object as a string in the format “symbolvalue”, where the value is in tao.
- static from_float(amount)[source]#
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)
- class bittensor.MockSubtensor(*args, **kwargs)[source]#
Bases:
bittensor.core.subtensor.Subtensor
A Mock Subtensor class for running tests. This should mock only methods that make queries to the chain. e.g. We mock Subtensor.query_subtensor instead of all query methods.
This class will also store a local (mock) state of the chain.
Initializes a Subtensor interface for interacting with the Bittensor blockchain.
Note
Currently subtensor defaults to the
finney
network. This will change in a future release.We strongly encourage users to run their own local subtensor node whenever possible. This increases decentralization and resilience of the network. In a future release, local subtensor will become the default and the fallback to
finney
removed. Please plan ahead for this change. We will provide detailed instructions on how to run a local subtensor node in the documentation in a subsequent release.- Parameters:
network (Optional[str]) – The network name to connect to (e.g.,
finney
,local
). This can also be the chain endpoint (e.g.,wss://entrypoint-finney.opentensor.ai:443
) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.config (Optional[bittensor.core.config.Config]) – Configuration object for the subtensor. If not provided, a default configuration is used.
_mock (bool) – If set to
True
, uses a mocked connection for testing purposes. Default 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
.
This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights.
- chain_state: MockChainState#
- __dict__#
- get_block_hash(block_id)[source]#
Retrieves the hash of a specific block on the Bittensor blockchain. The block hash is a unique identifier representing the cryptographic hash of the block’s content, ensuring its integrity and immutability.
- Parameters:
block_id (int) – The block number for which the hash is to be retrieved.
- Returns:
The cryptographic hash of the specified block.
- Return type:
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.
- static _convert_to_balance(balance)[source]#
- Parameters:
balance (Union[bittensor.utils.balance.Balance, float, int])
- Return type:
- sudo_force_set_balance#
- commit(wallet, netuid, data)[source]#
Commits arbitrary data to the Bittensor network by publishing metadata.
- get_commitment(netuid, uid, block=None)[source]#
Retrieves the on-chain commitment for a specific neuron in the Bittensor network.
- Parameters:
- Returns:
The commitment data as a string.
- Return type:
- query_subtensor(name, block=None, params=[])[source]#
Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to retrieve specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific attributes.
- Parameters:
- Returns:
An object containing the requested data.
- Return type:
query_response (scalecodec.ScaleType)
This query function is essential for accessing detailed information about the network and its neurons, providing valuable insights into the state and dynamics of the Bittensor ecosystem.
- query_map_subtensor(name, block=None, params=[])[source]#
Note: Double map requires one param
- Parameters:
- Return type:
Optional[MockMapResult]
- query_constant(module_name, constant_name, block=None)[source]#
Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.
- Parameters:
- Returns:
The value of the constant if found,
None
otherwise.- Return type:
Optional[scalecodec.ScaleType]
Constants queried through this function can include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network’s operational parameters.
- get_current_block()[source]#
Returns the current block number on the Bittensor blockchain. This function provides the latest block number, indicating the most recent state of the blockchain.
- Returns:
The current chain block number.
- Return type:
Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on the blockchain. It serves as a reference point for network activities and data synchronization.
- get_balance(address, block=None)[source]#
Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.
- Parameters:
- 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.
- neuron_for_uid(uid, netuid, block=None)[source]#
Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron’s attributes, including its stake, rank, and operational status.
- Parameters:
- 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)[source]#
Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet’s neuron population, including each neuron’s attributes and network interactions.
- Parameters:
- 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.
- _neuron_subnet_exists(uid, netuid, block=None)[source]#
- Parameters:
- Return type:
Optional[bittensor.core.chain_data.NeuronInfo]
- neurons_lite(netuid, block=None)[source]#
Retrieves a list of neurons in a ‘lite’ format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network participation.
- Parameters:
- Returns:
A list of simplified neuron information for the subnet.
- Return type:
list[bittensor.core.chain_data.neuron_info_lite.NeuronInfoLite]
This function offers a quick overview of the neuron population within a subnet, facilitating efficient analysis of the network’s decentralized structure and neuron dynamics.
- get_transfer_fee(wallet, dest, value)[source]#
Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This function simulates the transfer to estimate the associated cost, taking into account the current network conditions and transaction complexity.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet from which the transfer is initiated.
dest (str) – The
SS58
address of the destination account.value (Union[bittensor.utils.balance.Balance, float, int]) – The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units.
- Returns:
The estimated transaction fee for the transfer, represented as a Balance object.
- Return type:
Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the wallet has sufficient funds to cover both the transfer amount and the associated costs. This function provides a crucial tool for managing financial operations within the Bittensor network.
- do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)[source]#
- static min_required_stake()[source]#
As the minimum required stake may change, this method allows us to dynamically update the amount in the mock without updating the tests
- do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#
- bittensor.logging#
- class bittensor.SubnetsAPI(wallet)[source]#
Bases:
abc.ABC
This class is not used within the bittensor package, but is actively used by the community.
- Parameters:
wallet (bittensor_wallet.Wallet)
- wallet#
- dendrite#
- abstract prepare_synapse(*args, **kwargs)[source]#
Prepare the synapse-specific payload.
- Return type:
Any
- abstract process_responses(responses)[source]#
Process the responses from the network.
- Parameters:
responses (list[Union[bittensor.core.synapse.Synapse, Any]])
- Return type:
Any
- bittensor.axon#
- bittensor.config#
- bittensor.dendrite#
- bittensor.keyfile#
- bittensor.metagraph#
- bittensor.wallet#
- bittensor.subtensor#
- bittensor.synapse#
- bittensor.__blocktime__#
- bittensor.__network_explorer_map__#
- bittensor.__pipaddress__#
- bittensor.__ss58_format__#
- bittensor.__type_registry__#
- bittensor.__ss58_address_length__#
- bittensor.__networks__#
- bittensor.__finney_entrypoint__#
- bittensor.__finney_test_entrypoint__#
- bittensor.__archive_entrypoint__#
- bittensor.__local_entrypoint__#
- bittensor.__tao_symbol__#
- bittensor.__rao_symbol__#
- bittensor.mock_subpackage#
- bittensor.extrinsics_subpackage#
- bittensor.trace(on=True)[source]#
Enables or disables trace logging. :param on: If True, enables trace logging. If False, disables trace logging. :type on: bool
- Parameters:
on (bool)
- bittensor.debug(on=True)[source]#
Enables or disables debug logging. :param on: If True, enables debug logging. If False, disables debug logging. :type on: bool
- Parameters:
on (bool)