bittensor
#
Subpackages#
bittensor.commands
bittensor.commands.delegates
bittensor.commands.identity
bittensor.commands.inspect
bittensor.commands.list
bittensor.commands.metagraph
bittensor.commands.misc
bittensor.commands.network
bittensor.commands.overview
bittensor.commands.register
bittensor.commands.root
bittensor.commands.senate
bittensor.commands.stake
bittensor.commands.transfer
bittensor.commands.unstake
bittensor.commands.wallets
bittensor.extrinsics
bittensor.extrinsics.delegation
bittensor.extrinsics.log_utilities
bittensor.extrinsics.network
bittensor.extrinsics.prometheus
bittensor.extrinsics.registration
bittensor.extrinsics.root
bittensor.extrinsics.senate
bittensor.extrinsics.serving
bittensor.extrinsics.set_weights
bittensor.extrinsics.staking
bittensor.extrinsics.transfer
bittensor.extrinsics.unstaking
Submodules#
Package Contents#
Classes#
|
|
Create a collection of name/value pairs. |
|
A Config with a set of default values. |
|
Dataclass for delegate info. |
|
Dataclass for associated IP Info. |
|
The Mockkeyfile is a mock object representing a keyfile that does not exist on the device. |
|
Dataclass for neuron metadata. |
|
Dataclass for neuron metadata, but without the weights and bonds. |
|
Base threadpool executor with a priority queue |
|
Dataclass for prometheus info. |
|
dict() -> new empty dictionary |
|
Dataclass for stake info. |
|
The |
|
Dataclass for subnet hyperparameters. |
|
Dataclass for subnet info. |
|
Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes). |
|
Represents a Tensor object. |
|
TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process. |
|
The |
|
Implementation of the config class, which manages the configuration of different Bittensor modules. |
|
Standardized logging for Bittensor. |
|
Implementation of the wallet class, which manages balances with staking and transfer. Also manages hotkey and coldkey. |
Functions#
Prompts the user to enter a password for key encryption. |
|
|
Casts the raw value to a string representing the torch data type. |
|
Converts a string to a float, if the string is not |
|
Converts a string to an integer, if the string is not |
|
Casts the raw value to a string representing the tensor shape. |
|
|
|
Decrypts the passed keyfile data using ansible vault. |
|
Deserializes Keypair object from passed keyfile data. |
|
Display the mnemonic and a warning message to keep the mnemonic safe. |
|
Encrypts the passed keyfile data using ansible vault. |
|
|
|
|
|
Retrieves the cold key password from the environment variables. |
|
Recursively finds size of objects. |
|
Returns |
|
Returns |
|
Returns true if the keyfile data is ansible encrypted. |
|
Returns true if the keyfile data is legacy encrypted. |
|
Returns true if the keyfile data is NaCl encrypted. |
|
|
|
Serializes keypair object into keyfile data. |
|
|
|
Validates the password against a password policy. |
Attributes#
- bittensor.ALL_COMMANDS#
- class bittensor.AxonInfo#
-
- __repr__()#
Return repr(self).
- __str__()#
Return str(self).
- classmethod from_neuron_info(neuron_info)#
Converts a dictionary to an axon_info object.
- classmethod from_parameter_dict(parameter_dict)#
Returns an axon_info object from a torch parameter_dict.
- Parameters:
parameter_dict (torch.nn.ParameterDict) –
- Return type:
axon_info
- classmethod from_string(s)#
Creates an AxonInfo object from its string representation using JSON.
- to_parameter_dict()#
Returns a torch tensor of the subnet info.
- Return type:
- class bittensor.BTStreamingResponseModel(**data)#
Bases:
pydantic.BaseModel
BTStreamingResponseModel()
is a Pydantic model that encapsulates the token streamer callable for Pydantic validation. It is used within theStreamingSynapse()
class to create aBTStreamingResponse()
object, which is responsible for handling the streaming of tokens.The token streamer is a callable that takes a send function and returns an awaitable. It is responsible for generating the content of the streaming response, typically by processing tokens and sending them to the client.
This model ensures that the token streamer conforms to the expected signature and provides a clear interface for passing the token streamer to the BTStreamingResponse class.
- Parameters:
data (Any) –
- token_streamer#
Callable[[Send], Awaitable[None]] The token streamer callable, which takes a send function (provided by the ASGI server) and returns an awaitable. It is responsible for generating the content of the streaming response.
- exception bittensor.BlacklistedException#
Bases:
Exception
This exception is raised when the request is blacklisted.
- exception bittensor.ChainConnectionError#
Bases:
ChainError
Error for any chain connection related errors.
- class bittensor.ChainDataType(*args, **kwds)#
Bases:
enum.Enum
Create a collection of name/value pairs.
Example enumeration:
>>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3
Access them by:
attribute access:
>>> Color.RED <Color.RED: 1>
value lookup:
>>> Color(1) <Color.RED: 1>
name lookup:
>>> Color['RED'] <Color.RED: 1>
Enumerations can be iterated over, and know how many members they have:
>>> len(Color) 3
>>> list(Color) [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.
- DelegateInfo = 3#
- DelegatedInfo = 5#
- IPInfo = 7#
- NeuronInfo = 1#
- NeuronInfoLite = 4#
- StakeInfo = 6#
- SubnetHyperparameters = 8#
- SubnetInfo = 2#
- exception bittensor.ChainError#
Bases:
BaseException
Base error for any chain related errors.
- exception bittensor.ChainQueryError#
Bases:
ChainError
Error for any chain query related errors.
- exception bittensor.ChainTransactionError#
Bases:
ChainError
Error for any chain transaction related errors.
- class bittensor.DefaultConfig(parser=None, args=None, strict=False, default=None)#
Bases:
config
A Config with a set of default values.
- Parameters:
parser (argparse.ArgumentParser) –
args (Optional[List[str]]) –
strict (bool) –
default (Optional[Any]) –
- abstract classmethod default()#
Get default config.
- Return type:
T
- class bittensor.DelegateInfo#
Dataclass for delegate info.
- return_per_1000: bittensor.utils.balance.Balance#
- total_daily_return: bittensor.utils.balance.Balance#
- total_stake: bittensor.utils.balance.Balance#
- classmethod delegated_list_from_vec_u8(vec_u8)#
Returns a list of Tuples of DelegateInfo objects, and Balance, from a
vec_u8
.This is the list of delegates that the user has delegated to, and the amount of stake delegated.
- Parameters:
vec_u8 (List[int]) –
- Return type:
List[Tuple[DelegateInfo, bittensor.utils.balance.Balance]]
- classmethod fix_decoded_values(decoded)#
Fixes the decoded values.
- Parameters:
decoded (Any) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a DelegateInfo object from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
Optional[DelegateInfo]
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of DelegateInfo objects from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
List[DelegateInfo]
- class bittensor.IPInfo#
Dataclass for associated IP Info.
- encode()#
Returns a dictionary of the IPInfo object that can be encoded.
- Return type:
Dict[str, Any]
- classmethod fix_decoded_values(decoded)#
Returns a SubnetInfo object from a decoded IPInfo dictionary.
- Parameters:
decoded (Dict) –
- Return type:
- classmethod from_parameter_dict(parameter_dict)#
Returns a IPInfo object from a torch parameter_dict.
- Parameters:
parameter_dict (torch.nn.ParameterDict) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a IPInfo object from a
vec_u8
.
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of IPInfo objects from a
vec_u8
.
- to_parameter_dict()#
Returns a torch tensor of the subnet info.
- Return type:
- exception bittensor.IdentityError#
Bases:
ChainTransactionError
Error raised when an identity transaction fails.
- exception bittensor.InternalServerError#
Bases:
Exception
This exception is raised when the requested function fails on the server. Indicates a server error.
- exception bittensor.InvalidRequestNameError#
Bases:
Exception
This exception is raised when the request name is invalid. Ususally indicates a broken URL.
- exception bittensor.KeyFileError#
Bases:
Exception
Error thrown when the keyfile is corrupt, non-writable, non-readable or the password used to decrypt is invalid.
- exception bittensor.KeyFileError#
Bases:
Exception
Error thrown when the keyfile is corrupt, non-writable, non-readable or the password used to decrypt is invalid.
- exception bittensor.MetadataError#
Bases:
ChainTransactionError
Error raised when metadata commitment transaction fails.
- class bittensor.Mockkeyfile(path)#
The Mockkeyfile is a mock object representing a keyfile that does not exist on the device.
It is designed for use in testing scenarios and simulations where actual filesystem operations are not required. The keypair stored in the Mockkeyfile is treated as non-encrypted and the data is stored as a serialized string.
- Parameters:
path (str) –
- property data#
Returns the serialized keypair data stored in the keyfile.
- Returns:
The serialized keypair data.
- Return type:
- property keypair#
Returns the mock keypair stored in the keyfile.
- Returns:
The mock keypair.
- Return type:
bittensor.Keypair
- __repr__()#
Returns a string representation of the Mockkeyfile, same as
__str__()
.- Returns:
The string representation of the Mockkeyfile.
- Return type:
- __str__()#
Returns a string representation of the Mockkeyfile. The representation will indicate if the keyfile is empty, encrypted, or decrypted.
- Returns:
The string representation of the Mockkeyfile.
- Return type:
- check_and_update_encryption(no_prompt=None, print_result=False)#
- decrypt(password=None)#
Returns without doing anything since the mock keyfile is not encrypted.
- Parameters:
password (str, optional) – Ignored in this context. Defaults to
None
.
- encrypt(password=None)#
Raises a ValueError since encryption is not supported for the mock keyfile.
- Parameters:
password (str, optional) – Ignored in this context. Defaults to
None
.- Raises:
ValueError – Always raises this exception for Mockkeyfile.
- exists_on_device()#
Returns
True
indicating that the mock keyfile exists on the device (although it is not created on the actual file system).- Returns:
Always returns
True
for Mockkeyfile.- Return type:
- get_keypair(password=None)#
Returns the mock keypair stored in the keyfile. The
password
parameter is ignored.- Parameters:
password (str, optional) – Ignored in this context. Defaults to
None
.- Returns:
The mock keypair stored in the keyfile.
- Return type:
bittensor.Keypair
- is_encrypted()#
Returns
False
indicating that the mock keyfile is not encrypted.- Returns:
Always returns
False
for Mockkeyfile.- Return type:
- is_readable()#
Returns
True
indicating that the mock keyfile is readable (although it is not read from the actual file system).- Returns:
Always returns
True
for Mockkeyfile.- Return type:
- is_writable()#
Returns
True
indicating that the mock keyfile is writable (although it is not written to the actual file system).- Returns:
Always returns
True
for Mockkeyfile.- Return type:
- make_dirs()#
Creates the directories for the mock keyfile. Does nothing in this class, since no actual filesystem operations are needed.
- set_keypair(keypair, encrypt=True, overwrite=False, password=None)#
Sets the mock keypair in the keyfile. The
encrypt
andoverwrite
parameters are ignored.
- bittensor.NACL_SALT = b'\x13q\x83\xdf\xf1Z\t\xbc\x9c\x90\xb5Q\x879\xe9\xb1'#
- class bittensor.NeuronInfo#
Dataclass for neuron metadata.
- prometheus_info: PrometheusInfo#
- stake: bittensor.utils.balance.Balance#
- total_stake: bittensor.utils.balance.Balance#
- static _neuron_dict_to_namespace(neuron_dict)#
- Return type:
- static _null_neuron()#
- Return type:
- classmethod fix_decoded_values(neuron_info_decoded)#
Fixes the values of the NeuronInfo object.
- Parameters:
neuron_info_decoded (Any) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a NeuronInfo object from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
- classmethod from_weights_bonds_and_neuron_lite(neuron_lite, weights_as_dict, bonds_as_dict)#
- Parameters:
- Return type:
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of NeuronInfo objects from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
List[NeuronInfo]
- class bittensor.NeuronInfoLite#
Dataclass for neuron metadata, but without the weights and bonds.
- axon_info: NeuronInfoLite.axon_info#
- prometheus_info: PrometheusInfo#
- stake: bittensor.utils.balance.Balance#
- total_stake: bittensor.utils.balance.Balance#
- static _neuron_dict_to_namespace(neuron_dict)#
- Return type:
- static _null_neuron()#
- Return type:
- classmethod fix_decoded_values(neuron_info_decoded)#
Fixes the values of the NeuronInfoLite object.
- Parameters:
neuron_info_decoded (Any) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a NeuronInfoLite object from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of NeuronInfoLite objects from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
List[NeuronInfoLite]
- exception bittensor.NominationError#
Bases:
ChainTransactionError
Error raised when a nomination transaction fails.
- exception bittensor.NotDelegateError#
Bases:
StakeError
Error raised when a hotkey you are trying to stake to is not a delegate.
- exception bittensor.NotRegisteredError#
Bases:
ChainTransactionError
Error raised when a neuron is not registered, and the transaction requires it to be.
- exception bittensor.NotVerifiedException#
Bases:
Exception
This exception is raised when the request is not verified.
- exception bittensor.PostProcessException#
Bases:
Exception
This exception is raised when the response headers cannot be updated.
- exception bittensor.PriorityException#
Bases:
Exception
This exception is raised when the request priority is not met.
- class bittensor.PriorityThreadPoolExecutor(maxsize=-1, max_workers=None, thread_name_prefix='', initializer=None, initargs=())#
Bases:
concurrent.futures._base.Executor
Base threadpool executor with a priority queue
- property is_empty#
- _counter#
- _adjust_thread_count()#
- _initializer_failed()#
- classmethod add_args(parser, prefix=None)#
Accept specific arguments from parser
- Parameters:
parser (argparse.ArgumentParser) –
prefix (str) –
- classmethod config()#
Get config from the argument parser.
Return:
bittensor.config()
object.- Return type:
- shutdown(wait=True)#
Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Parameters:
wait – If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
cancel_futures – If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.
- submit(fn, *args, **kwargs)#
Submits a callable to be executed with the given arguments.
Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable.
- Returns:
A Future representing the given call.
- Parameters:
fn (Callable) –
- Return type:
concurrent.futures._base.Future
- class bittensor.PrometheusInfo#
Dataclass for prometheus info.
- classmethod fix_decoded_values(prometheus_info_decoded)#
Returns a PrometheusInfo object from a prometheus_info_decoded dictionary.
- Parameters:
prometheus_info_decoded (Dict) –
- Return type:
- bittensor.ProposalCallData#
- class bittensor.ProposalVoteData#
Bases:
TypedDict
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
- bittensor.RAOPERTAO = 1000000000.0#
- exception bittensor.RegistrationError#
Bases:
ChainTransactionError
Error raised when a neuron registration transaction fails.
- exception bittensor.RunException#
Bases:
Exception
This exception is raised when the requested function cannot be executed. Indicates a server error.
- exception bittensor.StakeError#
Bases:
ChainTransactionError
Error raised when a stake transaction fails.
- class bittensor.StakeInfo#
Dataclass for stake info.
- stake: bittensor.utils.balance.Balance#
- classmethod fix_decoded_values(decoded)#
Fixes the decoded values.
- Parameters:
decoded (Any) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a StakeInfo object from a
vec_u8
.
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of StakeInfo objects from a
vec_u8
.
- class bittensor.StreamingSynapse#
Bases:
bittensor.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.- class BTStreamingResponse(model, **kwargs)#
Bases:
starlette.responses.StreamingResponse
BTStreamingResponse()
is a specialized subclass of the Starlette StreamingResponse designed to handle the streaming of tokens within the Bittensor network. It is used internally by the StreamingSynapse class to manage the response streaming process, including sending headers and calling the token streamer provided by the subclass.This class is not intended to be directly instantiated or modified by developers subclassing StreamingSynapse. Instead, it is used by the
create_streaming_response()
method to create a response object based on the token streamer provided by the subclass.- Parameters:
model (BTStreamingResponseModel) –
- async __call__(scope, receive, send)#
Asynchronously calls the stream_response method, allowing the BTStreamingResponse object to be used as an ASGI application.
This method is part of the ASGI interface and is called by the ASGI server to handle the request and send the response. It delegates to the
stream_response()
method to perform the actual streaming process.- Parameters:
scope (starlette.types.Scope) – The scope of the request, containing information about the client, server, and request itself.
receive (starlette.types.Receive) – A callable to receive the request, provided by the ASGI server.
send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.
- async stream_response(send)#
Asynchronously streams the response by sending headers and calling the token streamer.
This method is responsible for initiating the response by sending the appropriate headers, including the content type for event-streaming. It then calls the token streamer to generate the content and sends the response body to the client.
- Parameters:
send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.
- create_streaming_response(token_streamer)#
Creates a streaming response using the provided token streamer. This method can be used by the subclass to create a response object that can be sent back to the client. The token streamer should be implemented to generate the content of the response according to the specific requirements of the subclass.
- Parameters:
token_streamer (Callable[[starlette.types.Send], Awaitable[None]]) – A callable that takes a send function and returns an awaitable. It’s responsible for generating the content of the response.
- Returns:
The streaming response object, ready to be sent to the client.
- Return type:
- abstract extract_response_json(response)#
Abstract method that must be implemented by the subclass. This method should provide logic to extract JSON data from the response, including headers and content. It is called after the response has been processed and is responsible for retrieving structured data that can be used by the application.
- Parameters:
response (starlette.responses.Response) – The response object from which to extract JSON data.
- Return type:
- abstract async process_streaming_response(response)#
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 (starlette.responses.Response) – The response object to be processed, typically containing chunks of data.
- class bittensor.SubnetHyperparameters#
Dataclass for subnet hyperparameters.
- classmethod fix_decoded_values(decoded)#
Returns a SubnetInfo object from a decoded SubnetInfo dictionary.
- Parameters:
decoded (Dict) –
- Return type:
- classmethod from_parameter_dict(parameter_dict)#
Returns a SubnetHyperparameters object from a torch parameter_dict.
- Parameters:
parameter_dict (torch.nn.ParameterDict) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a SubnetHyperparameters object from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
Optional[SubnetHyperparameters]
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of SubnetHyperparameters objects from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
List[SubnetHyperparameters]
- to_parameter_dict()#
Returns a torch tensor of the subnet hyperparameters.
- Return type:
- class bittensor.SubnetInfo#
Dataclass for subnet info.
- burn: bittensor.utils.balance.Balance#
- classmethod fix_decoded_values(decoded)#
Returns a SubnetInfo object from a decoded SubnetInfo dictionary.
- Parameters:
decoded (Dict) –
- Return type:
- classmethod from_parameter_dict(parameter_dict)#
Returns a SubnetInfo object from a torch parameter_dict.
- Parameters:
parameter_dict (torch.nn.ParameterDict) –
- Return type:
- classmethod from_vec_u8(vec_u8)#
Returns a SubnetInfo object from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
Optional[SubnetInfo]
- classmethod list_from_vec_u8(vec_u8)#
Returns a list of SubnetInfo objects from a
vec_u8
.- Parameters:
vec_u8 (List[int]) –
- Return type:
List[SubnetInfo]
- to_parameter_dict()#
Returns a torch tensor of the subnet info.
- Return type:
- class bittensor.Synapse(**data)#
Bases:
pydantic.BaseModel
Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes).
Synapses ensure the format and correctness of transmission tensors according to the Bittensor protocol. Each Synapse type is tailored for a specific machine learning (ML) task, following unique compression and communication processes. This helps maintain sanitized, correct, and useful information flow across the network.
The Synapse class encompasses essential network properties such as HTTP route names, timeouts, request sizes, and terminal information. It also includes methods for serialization, deserialization, attribute setting, and hash computation, ensuring secure and efficient data exchange in the network.
The class includes Pydantic validators and root validators to enforce data integrity and format. Additionally, properties like
is_success
,is_failure
,is_timeout
, etc., provide convenient status checks based on dendrite responses.Think of Bittensor Synapses as glorified pydantic wrappers that have been designed to be used in a distributed network. They provide a standardized way to communicate between neurons, and are the primary mechanism for communication between neurons in Bittensor.
Key Features:
- HTTP Route Name (
name
attribute): Enables the identification and proper routing of requests within the network. Essential for users defining custom routes for specific machine learning tasks.
- HTTP Route Name (
- Query Timeout (
timeout
attribute): Determines the maximum duration allowed for a query, ensuring timely responses and network efficiency. Crucial for users to manage network latency and response times, particularly in time-sensitive applications.
- Query Timeout (
- Request Sizes (
total_size
,header_size
attributes): Keeps track of the size of request bodies and headers, ensuring efficient data transmission without overloading the network. Important for users to monitor and optimize the data payload, especially in bandwidth-constrained environments.
- Request Sizes (
- Terminal Information (
dendrite
,axon
attributes): Stores information about the dendrite (receiving end) and axon (sending end), facilitating communication between nodes. Users can access detailed information about the communication endpoints, aiding in debugging and network analysis.
- Terminal Information (
- Body Hash Computation (
computed_body_hash
,required_hash_fields
): Ensures data integrity and security by computing hashes of transmitted data. Provides users with a mechanism to verify data integrity and detect any tampering during transmission.
- 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 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.json() # Get a dictionary of headers from the synapse instance headers = synapse.to_headers() # Reconstruct the synapse from headers using the classmethod 'from_headers' synapse = Synapse.from_headers(headers) # Deserialize synapse after receiving it over the network, controlled by `deserialize` method deserialized_synapse = synapse.deserialize() # Checking the status of the request if synapse.is_success: print("Request succeeded") # Checking and setting the status of the request print(synapse.axon.status_code) synapse.axon.status_code = 408 # Timeout
- Parameters:
name (str) – HTTP route name, set on
axon.attach()
.timeout (float) – Total query length, set by the dendrite terminal.
total_size (int) – Total size of request body in bytes.
header_size (int) – Size of request header in bytes.
dendrite (TerminalInfo) – Information about the dendrite terminal.
axon (TerminalInfo) – Information about the axon terminal.
computed_body_hash (str) – Computed hash of the request body.
required_hash_fields (List[str]) – Fields required to compute the body hash.
data (Any) –
- __setattr__()#
Override method to make
required_hash_fields
read-only.- Parameters:
name (str) –
value (Any) –
- parse_headers_to_inputs()#
Parses headers to construct an inputs dictionary.
- from_headers()#
Creates an instance from a headers dictionary.
This class is a cornerstone in the Bittensor framework, providing the necessary tools for secure, efficient, and standardized communication in a decentralized environment.
- 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_fields_hash
.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:
- 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:
- property is_blacklist: bool#
Checks if the dendrite’s status code indicates a blacklisted request.
This method returns
True
if the status code of the dendrite is403
, which is the HTTP status code for a forbidden request.- Returns:
True
if dendrite’s status code is403
,False
otherwise.- Return type:
- property is_failure: bool#
Checks if the dendrite’s status code indicates failure.
This method returns
True
if the status code of the dendrite is not200
, which would mean the HTTP request was not successful.- Returns:
True
if dendrite’s status code is not200
,False
otherwise.- Return type:
- property is_success: bool#
Checks if the dendrite’s status code indicates success.
This method returns
True
if the status code of the dendrite is200
, which typically represents a successful HTTP request.- Returns:
True
if dendrite’s status code is200
,False
otherwise.- Return type:
- property is_timeout: bool#
Checks if the dendrite’s status code indicates a timeout.
This method returns
True
if the status code of the dendrite is408
, which is the HTTP status code for a request timeout.- Returns:
True
if dendrite’s status code is408
,False
otherwise.- Return type:
- _extract_header_size#
- _extract_timeout#
- _extract_total_size#
- axon: TerminalInfo | None#
- dendrite: TerminalInfo | None#
- __setattr__(name, value)#
Override the
__setattr__()
method to make therequired_hash_fields
property read-only.This is a security mechanism such that the
required_hash_fields
property cannot be overridden by the user or malicious code.- Parameters:
name (str) –
value (Any) –
- deserialize()#
Deserializes the Synapse object.
This method is intended to be overridden by subclasses for custom deserialization logic. In the context of the Synapse superclass, this method simply returns the instance itself. When inheriting from this class, subclasses should provide their own implementation for deserialization if specific deserialization behavior is desired.
By default, if a subclass does not provide its own implementation of this method, the Synapse’s deserialize method will be used, returning the object instance as-is.
In its default form, this method simply returns the instance of the Synapse itself without any modifications. Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting serialized data back into complex object types or performing additional data integrity checks.
Example:
class CustomSynapse(Synapse): additional_data: str def deserialize(self) -> "CustomSynapse": # Custom deserialization logic # For example, decoding a base64 encoded string in 'additional_data' if self.additional_data: self.additional_data = base64.b64decode(self.additional_data).decode('utf-8') return self serialized_data = '{"additional_data": "SGVsbG8gV29ybGQ="}' # Base64 for 'Hello World' custom_synapse = CustomSynapse.parse_raw(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:
- classmethod from_headers(headers)#
Constructs a new Synapse instance from a given headers dictionary, enabling the re-creation of the Synapse’s state as it was prior to network transmission.
This method is a key part of the deserialization process in the Bittensor network, allowing nodes to accurately reconstruct Synapse objects from received data.
Example:
received_headers = { 'bt_header_axon_address': '127.0.0.1', 'bt_header_dendrite_port': '8080', # Other headers... } synapse = Synapse.from_headers(received_headers) # synapse is a new Synapse instance reconstructed from the received headers
- get_total_size()#
Get the total size of the current object.
This method first calculates the size of the current object, then assigns it to the instance variable
self.total_size()
and finally returns this value.- Returns:
The total size of the current object.
- Return type:
- classmethod parse_headers_to_inputs(headers)#
Interprets and transforms a given dictionary of headers into a structured dictionary, facilitating the reconstruction of Synapse objects.
This method is essential for parsing network-transmitted data back into a Synapse instance, ensuring data consistency and integrity.
Process:
Separates headers into categories based on prefixes (
axon
,dendrite
, etc.).Decodes and deserializes
input_obj
headers into their original objects.Assigns simple fields directly from the headers to the input dictionary.
Example:
received_headers = { 'bt_header_axon_address': '127.0.0.1', 'bt_header_dendrite_port': '8080', # Other headers... } inputs = Synapse.parse_headers_to_inputs(received_headers) # inputs now contains a structured representation of Synapse properties based on the headers
Note
This is handled automatically when calling
Synapse.from_headers(headers)()
and does not need to be called directly.
- to_headers()#
Converts the state of a Synapse instance into a dictionary of HTTP headers.
This method is essential for packaging Synapse data for network transmission in the Bittensor framework, ensuring that each key aspect of the Synapse is represented in a format suitable for HTTP communication.
Process:
Basic Information: It starts by including the
name
andtimeout
of the Synapse, which are fundamental for identifying the query and managing its lifespan on the network.Complex Objects: The method serializes the
axon
anddendrite
objects, if present, into strings. This serialization is crucial for preserving the state and structure of these objects over the network.Encoding: Non-optional complex objects are serialized and encoded in base64, making them safe for HTTP transport.
Size Metrics: The method calculates and adds the size of headers and the total object size, providing valuable information for network bandwidth management.
Example Usage:
synapse = Synapse(name="ExampleSynapse", timeout=30) headers = synapse.to_headers() # headers now contains a dictionary representing the Synapse instance
- Returns:
A dictionary containing key-value pairs representing the Synapse’s properties, suitable for HTTP communication.
- Return type:
- exception bittensor.SynapseParsingError#
Bases:
Exception
This exception is raised when the request headers are unable to be parsed into the synapse type.
- bittensor.T#
- bittensor.TORCH_DTYPES#
- class bittensor.Tensor(**data)#
Bases:
pydantic.BaseModel
Represents a Tensor object.
- Parameters:
- _extract_dtype#
- _extract_shape#
- deserialize()#
Deserializes the Tensor object.
- Returns:
The deserialized tensor object.
- Return type:
- Raises:
Exception – If the deserialization process encounters an error.
- numpy()#
- Return type:
numpy.ndarray
- static serialize(tensor)#
Serializes the given tensor.
- Parameters:
tensor (torch.Tensor) – The tensor to serialize.
- Returns:
The serialized tensor.
- Return type:
- Raises:
Exception – If the serialization process encounters an error.
- tensor()#
- Return type:
- class bittensor.TerminalInfo(**data)#
Bases:
pydantic.BaseModel
TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process.
This class serves as a metadata carrier, providing essential details about the state and configuration of a terminal during network interactions. This is a crucial class in the Bittensor framework.
The TerminalInfo class contains information such as HTTP status codes and messages, processing times, IP addresses, ports, Bittensor version numbers, and unique identifiers. These details are vital for maintaining network reliability, security, and efficient data flow within the Bittensor network.
This class includes Pydantic validators and root validators to enforce data integrity and format. It is designed to be used natively within Synapses, so that you will not need to call this directly, but rather is used as a helper class for Synapses.
- Parameters:
status_code (int) – HTTP status code indicating the result of a network request. Essential for identifying the outcome of network interactions.
status_message (str) – Descriptive message associated with the status code, providing additional context about the request’s result.
process_time (float) – Time taken by the terminal to process the call, important for performance monitoring and optimization.
ip (str) – IP address of the terminal, crucial for network routing and data transmission.
port (int) – Network port used by the terminal, key for establishing network connections.
version (int) – Bittensor version running on the terminal, ensuring compatibility between different nodes in the network.
nonce (int) – Unique, monotonically increasing number for each terminal, aiding in identifying and ordering network interactions.
uuid (str) – Unique identifier for the terminal, fundamental for network security and identification.
hotkey (str) – Encoded hotkey string of the terminal wallet, important for transaction and identity verification in the network.
signature (str) – Digital signature verifying the tuple of nonce, axon_hotkey, dendrite_hotkey, and uuid, critical for ensuring data authenticity and security.
data (Any) –
Usage:
# Creating a TerminalInfo instance 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.
- _extract_nonce#
- _extract_port#
- _extract_process_time#
- _extract_status_code#
- _extract_version#
- exception bittensor.TransferError#
Bases:
ChainTransactionError
Error raised when a transfer transaction fails.
- bittensor.U16_MAX = 65535#
- bittensor.U64_MAX = 18446744073709551615#
- exception bittensor.UnknownSynapseError#
Bases:
Exception
This exception is raised when the request name is not found in the Axon’s forward_fns dictionary.
- exception bittensor.UnstakeError#
Bases:
ChainTransactionError
Error raised when an unstake transaction fails.
- bittensor.__archive_entrypoint__ = 'wss://archive.chain.opentensor.ai:443/'#
- bittensor.__bellagene_entrypoint__ = 'wss://parachain.opentensor.ai:443'#
- bittensor.__blocktime__ = 12#
- bittensor.__console__#
- bittensor.__delegates_details_url__: str = 'https://raw.githubusercontent.com/opentensor/bittensor-delegates/main/public/delegates.json'#
- bittensor.__finney_entrypoint__ = 'wss://entrypoint-finney.opentensor.ai:443'#
- bittensor.__finney_test_entrypoint__ = 'wss://test.finney.opentensor.ai:443/'#
- bittensor.__local_entrypoint__ = 'ws://127.0.0.1:9944'#
- bittensor.__network_explorer_map__#
- bittensor.__networks__ = ['local', 'finney', 'test', 'archive']#
- bittensor.__new_signature_version__ = 360#
- bittensor.__pipaddress__ = 'https://pypi.org/pypi/bittensor/json'#
- bittensor.__ss58_address_length__ = 48#
- bittensor.__ss58_format__ = 42#
- bittensor.__type_registry__#
- bittensor.__use_console__ = True#
- bittensor.__version__ = '6.6.1'#
- bittensor.__version_as_int__#
- bittensor.ask_password_to_encrypt()#
Prompts the user to enter a password for key encryption.
- Returns:
The valid password entered by the user.
- Return type:
password (str)
- class bittensor.axon(wallet=None, config=None, port=None, ip=None, external_ip=None, external_port=None, max_workers=None)#
The
axon
class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network.This class is responsible for managing incoming requests from other neurons and implements various mechanisms to ensure efficient and secure network interactions.
An axon relies on a FastAPI router to create endpoints for different message types. These endpoints are crucial for handling various request types that a neuron might receive. The class is designed to be flexible and customizable, allowing users to specify custom rules for forwarding, blacklisting, prioritizing, and verifying incoming requests. The class also includes internal mechanisms to manage a thread pool, supporting concurrent handling of requests with defined priority levels.
Methods in this class are equipped to deal with incoming requests from various scenarios in the network and serve as the server face for a neuron. It accepts multiple arguments, like wallet, configuration parameters, ip address, server binding port, external ip, external port and max workers. Key methods involve managing and operating the FastAPI application router, including the attachment and operation of endpoints.
Key Features:
FastAPI router integration for endpoint creation and management.
Customizable request handling including forwarding, blacklisting, and prioritization.
Verification of incoming requests against custom-defined functions.
Thread pool management for concurrent request handling.
Command-line argument support for user-friendly program interaction.
Example Usage:
import bittensor # Define your custom synapse class class MySyanpse( bittensor.Synapse ): input: int = 1 output: int = None # Define a custom request forwarding function using your synapse class def forward( synapse: MySyanpse ) -> MySyanpse: # Apply custom logic to synapse and return it synapse.output = 2 return synapse # Define a custom request verification function def verify_my_synapse( synapse: MySyanpse ): # Apply custom verification logic to synapse # Optionally raise Exception assert synapse.input == 1 ... # Define a custom request blacklist fucntion def blacklist_my_synapse( synapse: MySyanpse ) -> bool: # Apply custom blacklist return False ( if non blacklisted ) or True ( if blacklisted ) # Define a custom request priority fucntion def prioritize_my_synape( synapse: MySyanpse ) -> 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_synape ) # 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_synape ).attach( forward_fn = forward_my_synapse_2, verify_fn = verify_my_synapse_2, blacklist_fn = blacklist_my_synapse_2, priority_fn = prioritize_my_synape_2 ).serve( netuid = ... subtensor = ... ).start()
- Parameters:
wallet (bittensor.wallet, optional) – Wallet with hotkey and coldkeypub.
config (bittensor.config, optional) – Configuration parameters for the axon.
port (int, optional) – Port for server binding.
ip (str, optional) – Binding IP address.
external_ip (str, optional) – External IP address to broadcast.
external_port (int, optional) – External port to broadcast.
max_workers (int, optional) – 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.
- __del__()#
This magic method is called when the Axon object is about to be destroyed. It ensures that the Axon server shuts down properly.
- __repr__()#
Provides a machine-readable (unambiguous) representation of the Axon instance. It is made identical to __str__ in this case.
- Return type:
- classmethod add_args(parser, prefix=None)#
Adds AxonServer-specific command-line arguments to the argument parser.
- Parameters:
parser (argparse.ArgumentParser) – Argument parser to which the arguments will be added.
prefix (str, optional) – Prefix to add to the argument names. Defaults to None.
Note
Environment variables are used to define default values for the arguments.
- attach(forward_fn, blacklist_fn=None, priority_fn=None, verify_fn=None)#
Attaches custom functions to the Axon server for handling incoming requests. This method enables the Axon to define specific behaviors for request forwarding, verification, blacklisting, and prioritization, thereby customizing its interaction within the Bittensor network.
Registers an API endpoint to the FastAPI application router. It uses the name of the first argument of the
forward_fn()
function as the endpoint name.The attach method in the Bittensor framework’s axon class is a crucial function for registering API endpoints to the Axon’s FastAPI application router. This method allows the Axon server to define how it handles incoming requests by attaching functions for forwarding, verifying, blacklisting, and prioritizing requests. It’s a key part of customizing the server’s behavior and ensuring efficient and secure handling of requests within the Bittensor network.
- Parameters:
forward_fn (Callable) – Function to be called when the API endpoint is accessed. It should have at least one argument.
blacklist_fn (Callable, optional) – 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 (Callable, optional) – 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 (Callable, optional) – 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 (Callable) –
priority_fn (Callable) –
verify_fn (Callable) –
Example Usage:
def forward_custom(synapse: MyCustomSynapse) -> MyCustomSynapse: # Custom logic for processing the request return synapse def blacklist_custom(synapse: MyCustomSynapse) -> Tuple[bool, str]: return True, "Allowed!" def priority_custom(synapse: MyCustomSynapse) -> float: return 1.0 def verify_custom(synapse: MyCustomSynapse): # Custom logic for verifying the request pass my_axon = bittensor.axon(...) my_axon.attach(forward_fn=forward_custom, verify_fn=verify_custom)
Note
The
attach()
method is fundamental in setting up the Axon server’s request handling capabilities, enabling it to participate effectively and securely in the Bittensor network. The flexibility offered by this method allows developers to tailor the Axon’s behavior to specific requirements and use cases.
- classmethod check_config(config)#
This method checks the configuration for the axon’s port and wallet.
- Parameters:
config (bittensor.config) – The config object holding axon settings.
- Raises:
AssertionError – If the axon or external ports are not in range [1024, 65535]
- classmethod config()#
Parses the command-line arguments to form a Bittensor configuration object.
- Returns:
Configuration object with settings from command-line arguments.
- Return type:
- async default_verify(synapse)#
This method is used to verify the authenticity of a received message using a digital signature.
It ensures that the message was not tampered with and was sent by the expected sender.
The
default_verify()
method in the Bittensor framework is a critical security function within the Axon server. It is designed to authenticate incoming messages by verifying their digital signatures. This verification ensures the integrity of the message and confirms that it was indeed sent by the claimed sender. The method plays a pivotal role in maintaining the trustworthiness and reliability of the communication within the Bittensor network.- Key Features
- Security Assurance
The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access and data manipulation.
- Preventing Replay Attacks
The method checks for increasing nonce values, which is a vital step in preventing replay attacks. A replay attack involves an adversary reusing or delaying the transmission of a valid data transmission to deceive the receiver.
- 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.Synapse) – bittensor.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.
- classmethod help()#
Prints the help text (list of command-line arguments and their descriptions) to stdout.
- info()#
Returns the axon info object associated with this axon.
- Return type:
- serve(netuid, subtensor=None)#
Serves the Axon on the specified subtensor connection using the configured wallet. This method registers the Axon with a specific subnet within the Bittensor network, identified by the
netuid
. It links the Axon to the broader network, allowing it to participate in the decentralized exchange of information.- Parameters:
netuid (int) – The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology.
subtensor (bittensor.subtensor, optional) – 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.
- start()#
Starts the Axon server and its underlying FastAPI server thread, transitioning the state of the Axon instance to
started
. This method initiates the server’s ability to accept and process incoming network requests, making it an active participant in the Bittensor network.The start method triggers the FastAPI server associated with the Axon to begin listening for incoming requests. It is a crucial step in making the neuron represented by this Axon operational within the Bittensor network.
- Returns:
The Axon instance in the ‘started’ state.
- Return type:
Example:
my_axon = bittensor.axon(...) ... # setup axon, attach functions, etc. my_axon.start() # Starts the axon server
Note
After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom logic.
- stop()#
Stops the Axon server and its underlying GRPC server thread, transitioning the state of the Axon instance to
stopped
. This method ceases the server’s ability to accept new network requests, effectively removing the neuron’s server-side presence in the Bittensor network.By stopping the FastAPI server, the Axon ceases to listen for incoming requests, and any existing connections are gracefully terminated. This function is typically used when the neuron is being shut down or needs to temporarily go offline.
- Returns:
The Axon instance in the ‘stopped’ state.
- Return type:
Example:
my_axon = bittensor.axon(...) my_axon.start() ... my_axon.stop() # Stops the axon server
Note
It is advisable to ensure that all ongoing processes or requests are completed or properly handled before invoking this method.
- to_string()#
Provides a human-readable representation of the AxonInfo for this Axon.
- async verify_body_integrity(request)#
The
verify_body_integrity
method in the Bittensor framework is a key security function within the Axon server’s middleware. It is responsible for ensuring the integrity of the body of incoming HTTP requests.It asynchronously verifies the integrity of the body of a request by comparing the hash of required fields with the corresponding hashes provided in the request headers. This method is critical for ensuring that the incoming request payload has not been altered or tampered with during transmission, establishing a level of trust and security between the sender and receiver in the network.
- Parameters:
request (Request) – The incoming FastAPI request object containing both headers and the request body.
- Returns:
- Returns the parsed body of the request as a dictionary if all the hash comparisons match,
indicating that the body is intact and has not been tampered with.
- Return type:
- Raises:
JSONResponse – Raises a JSONResponse with a 400 status code if any of the hash comparisons fail, indicating a potential integrity issue with the incoming request payload. The response includes the detailed error message specifying which field has a hash mismatch.
This method performs several key functions:
Decoding and loading the request body for inspection.
Gathering required field names for hash comparison from the Axon configuration.
Loading and parsing the request body into a dictionary.
Reconstructing the Synapse object and recomputing the hash for verification and logging.
Comparing the recomputed hash with the hash provided in the request headers for verification.
Note
The integrity verification is an essential step in ensuring the security of the data exchange within the Bittensor network. It helps prevent tampering and manipulation of data during transit, thereby maintaining the reliability and trust in the network communication.
- bittensor.cast_dtype(raw)#
Casts the raw value to a string representing the torch data type.
- Parameters:
raw (Union[None, torch.dtype, str]) – The raw value to cast.
- Returns:
The string representing the torch data type.
- Return type:
- Raises:
Exception – If the raw value is of an invalid type.
- bittensor.cast_float(raw)#
Converts a string to a float, if the string is not
None
.This function attempts to convert a string to a float. If the string is
None
, it simply returnsNone
.
- bittensor.cast_int(raw)#
Converts a string to an integer, if the string is not
None
.This function attempts to convert a string to an integer. If the string is
None
, it simply returnsNone
.
- bittensor.cast_shape(raw)#
Casts the raw value to a string representing the tensor shape.
- class bittensor.cli(config=None, args=None)#
Implementation of the Command Line Interface (CLI) class for the Bittensor protocol. This class handles operations like key management (hotkey and coldkey) and token transfer.
- Parameters:
config (Optional[bittensor.config]) –
args (Optional[List[str]]) –
- static __create_parser__()#
Creates the argument parser for the Bittensor CLI.
- Returns:
An argument parser object for Bittensor CLI.
- Return type:
- static check_config(config)#
Checks if the essential configuration exists under different command
- Parameters:
config (bittensor.config) – The configuration settings for the CLI.
- static create_config(args)#
From the argument parser, add config to bittensor.executor and local config
- Parameters:
args (List[str]) – List of command line arguments.
- Returns:
The configuration object for Bittensor CLI.
- Return type:
- run()#
Executes the command from the configuration.
- class bittensor.config(parser=None, args=None, strict=False, default=None)#
Bases:
munch.DefaultMunch
Implementation of the config class, which manages the configuration of different Bittensor modules.
- Parameters:
parser (argparse.ArgumentParser) –
args (Optional[List[str]]) –
strict (bool) –
default (Optional[Any]) –
- __is_set: Dict[str, bool]#
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:
- static __parse_args__(args, parser=None, strict=False)#
Parses the passed args use the passed parser.
- Parameters:
args (List[str]) – List of arguments to parse.
parser (argparse.ArgumentParser) – Command line parser object.
strict (bool) – If
true
, the command line arguments are strictly parsed.
- Returns:
Namespace object created from parser arguments.
- Return type:
Namespace
- __repr__()#
Invertible* string-form of a Munch.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!') >>> print (repr(b)) Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42}) >>> eval(repr(b)) Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})}) >>> print (repr(with_spaces)) Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})}) >>> eval(repr(with_spaces)) Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
(*) Invertible so long as collection contents are each repr-invertible.
- Return type:
- static __split_params__(params, _config)#
- Parameters:
params (argparse.Namespace) –
_config (config) –
- classmethod _merge(a, b)#
Merge two configurations recursively. If there is a conflict, the value from the second configuration will take precedence.
- static _remove_private_keys(d)#
- is_set(param_name)#
Returns a boolean indicating whether the parameter has been set or is still the default.
- merge(b)#
Merges the current config with another config.
- Parameters:
b – Another config to merge.
- classmethod merge_all(configs)#
Merge all configs in the list into one config. If there is a conflict, the value from the last configuration in the list will take precedence.
- update_with_kwargs(kwargs)#
Add config to self
- bittensor.configs#
- bittensor.custom_rpc_type_registry#
- bittensor.decrypt_keyfile_data(keyfile_data, password=None, coldkey_name=None)#
Decrypts the passed keyfile data using ansible vault.
- Parameters:
- Returns:
The decrypted data.
- Return type:
decrypted_data (bytes)
- Raises:
KeyFileError – Raised if the file is corrupted or if the password is incorrect.
- bittensor.defaults#
- class bittensor.dendrite(wallet=None)#
Bases:
torch.nn.Module
The Dendrite class, inheriting from PyTorch’s Module 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 recieve 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:
- __repr__()#
Returns a string representation of the Dendrite object, acting as a fallback for __str__().
- Return type:
- query(self, *args, **kwargs) bittensor.Synapse | List[bittensor.Synapse] #
Makes synchronous requests to one or multiple target Axons and returns responses.
- Return type:
Union[bittensor.Synapse, List[bittensor.Synapse], bittensor.StreamingSynapse, List[bittensor.StreamingSynapse]]
- forward(self, axons, synapse=bittensor.Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) bittensor.Synapse #
Asynchronously sends requests to one or multiple Axons and collates their responses.
- Parameters:
axons (Union[List[Union[bittensor.AxonInfo, bittensor.axon]], Union[bittensor.AxonInfo, bittensor.axon]]) –
synapse (bittensor.Synapse) –
timeout (float) –
deserialize (bool) –
run_async (bool) –
streaming (bool) –
- Return type:
List[Union[AsyncGenerator[Any], bittenst.Synapse, bittensor.StreamingSynapse]]
- call(self, target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True) bittensor.Synapse #
Asynchronously sends a request to a specified Axon and processes the response.
- Parameters:
target_axon (Union[bittensor.AxonInfo, bittensor.axon]) –
synapse (bittensor.Synapse) –
timeout (float) –
deserialize (bool) –
- Return type:
- call_stream(self, target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True) AsyncGenerator[bittensor.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.AxonInfo, bittensor.axon]) –
synapse (bittensor.Synapse) –
timeout (float) –
deserialize (bool) –
- Return type:
AsyncGenerator[Any]
- preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) bittensor.Synapse #
Preprocesses the synapse for making a request, including building headers and signing.
- Parameters:
target_axon_info (bittensor.AxonInfo) –
synapse (bittensor.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 (fastapi.Response) –
json_response (dict) –
local_synapse (bittensor.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:
>>> aysnc with dendrite(wallet = bittensor.wallet()) as d: >>> print(d) >>> d( <axon> ) # ping axon >>> d( [<axons>] ) # ping multiple >>> d( bittensor.axon(), bittensor.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() ) >>> print(d) >>> d( <axon> ) # ping axon >>> d( [<axons>] ) # ping multiple >>> d( bittensor.axon(), bittensor.Synapse )
- property session: aiohttp.ClientSession#
An asynchronous property that provides access to the internal aiohttp client session.
This property ensures the management of HTTP connections in an efficient way. It lazily initializes the aiohttp.ClientSession on its first use. The session is then reused for subsequent HTTP requests, offering performance benefits by reusing underlying connections.
This is used internally by the dendrite when querying axons, and should not be used directly unless absolutely necessary for your application.
- Returns:
The active aiohttp client session instance. If no session exists, a new one is created and returned. This session is used for asynchronous HTTP requests within the dendrite, adhering to the async nature of the network interactions in the Bittensor framework.
- Return type:
aiohttp.ClientSession
Example usage:
import bittensor as bt # Import bittensor wallet = bt.wallet( ... ) # Initialize a wallet dendrite = bt.dendrite( wallet ) # Initialize a dendrite instance with the wallet async with (await dendrite.session).post( # Use the session to make an HTTP POST request url, # URL to send the request to headers={...}, # Headers dict to be sent with the request json={...}, # JSON body data to be sent with the request timeout=10, # Timeout duration in seconds ) as response: json_response = await response.json() # Extract the JSON response from the server
- async __aenter__()#
Asynchronous context manager entry method.
Enables the use of the
async with
statement with the Dendrite instance. When entering the context, the current instance of the class is returned, making it accessible within the asynchronous context.- Returns:
The current instance of the Dendrite class.
- Return type:
Dendrite
Usage:
async with Dendrite() as dendrite: await dendrite.some_async_method()
- async __aexit__(exc_type, exc_value, traceback)#
Asynchronous context manager exit method.
Ensures proper cleanup when exiting the
async with
context. This method will close the aiohttp client session asynchronously, releasing any tied resources.- Parameters:
exc_type (Type[BaseException], optional) – The type of exception that was raised.
exc_value (BaseException, optional) – The instance of exception that was raised.
traceback (TracebackType, optional) – A traceback object encapsulating the call stack at the point where the exception was raised.
Usage:
async with bt.dendrite( wallet ) as dendrite: await dendrite.some_async_method()
Note
This automatically closes the session by calling
__aexit__()
after the context closes.
- __del__()#
Dendrite destructor.
This method is invoked when the Dendrite instance is about to be destroyed. The destructor ensures that the aiohttp client session is closed before the instance is fully destroyed, releasing any remaining resources.
Note
Relying on the destructor for cleanup can be unpredictable. It is recommended to explicitly close sessions using the provided methods or the
async with
context manager.Usage:
dendrite = Dendrite() # ... some operations ... del dendrite # This will implicitly invoke the __del__ method and close the session.
- __repr__()#
Returns a string representation of the Dendrite object, acting as a fallback for
__str__()
.- Returns:
The string representation of the Dendrite object in the format
dendrite(<user_wallet_address>)()
.- Return type:
- __str__()#
Returns a string representation of the Dendrite object.
- Returns:
The string representation of the Dendrite object in the format
dendrite(<user_wallet_address>)()
.- Return type:
- _get_endpoint_url(target_axon, request_name)#
Constructs the endpoint URL for a network request to a target axon.
This internal method generates the full HTTP URL for sending a request to the specified axon. The URL includes the IP address and port of the target axon, along with the specific request name. It differentiates between requests to the local system (using ‘0.0.0.0’) and external systems.
- Parameters:
target_axon – The target axon object containing IP and port information.
request_name – The specific name of the request being made.
- Returns:
A string representing the complete HTTP URL for the request.
- Return type:
- _handle_request_errors(synapse, request_name, exception)#
Handles exceptions that occur during network requests, updating the synapse with appropriate status codes and messages.
This method interprets different types of exceptions and sets the corresponding status code and message in the synapse object. It covers common network errors such as connection issues and timeouts.
- Parameters:
synapse – The synapse object associated with the request.
request_name – The name of the request during which the exception occurred.
exception – The exception object caught during the request.
Note
This method updates the synapse object in-place.
- _log_incoming_response(synapse)#
Logs information about incoming responses for debugging and monitoring.
Similar to
_log_outgoing_request()
, this method logs essential details of the incoming responses, including the size of the response, synapse name, axon details, status code, and status message. This logging is vital for troubleshooting and understanding the network interactions in Bittensor.- Parameters:
synapse – The synapse object representing the received response.
- _log_outgoing_request(synapse)#
Logs information about outgoing requests for debugging purposes.
This internal method logs key details about each outgoing request, including the size of the request, the name of the synapse, the axon’s details, and a success indicator. This information is crucial for monitoring and debugging network activity within the Bittensor network.
To turn on debug messages, set the environment variable BITTENSOR_DEBUG to
1
, or call the bittensor debug method like so:import bittensor bittensor.debug()
- Parameters:
synapse – The synapse object representing the request being sent.
- async aclose_session()#
Asynchronously closes the internal aiohttp client session.
This method is the asynchronous counterpart to the
close_session()
method. It should be used in asynchronous contexts to ensure that the aiohttp client session is closed properly. The method releases resources associated with the session, such as open connections and internal buffers, which is essential for resource management in asynchronous applications.- Usage:
When finished with dendrite in an asynchronous context await
dendrite_instance.aclose_session()
.
Example:
async with dendrite_instance: # Operations using dendrite pass # The session will be closed automatically after the above block
- async call(target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True)#
Asynchronously sends a request to a specified Axon and processes the response.
This function establishes a connection with a specified Axon, sends the encapsulated data through the Synapse object, waits for a response, processes it, and then returns the updated Synapse object.
- Parameters:
target_axon (Union['bittensor.AxonInfo', 'bittensor.axon']) – The target Axon to send the request to.
synapse (bittensor.Synapse, optional) – The Synapse object encapsulating the data. Defaults to a new
bittensor.Synapse()
instance.timeout (float, optional) – Maximum duration to wait for a response from the Axon in seconds. Defaults to
12.0
.deserialize (bool, optional) – Determines if the received response should be deserialized. Defaults to
True
.
- Returns:
The Synapse object, updated with the response data from the Axon.
- Return type:
- async call_stream(target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True)#
Sends a request to a specified Axon and yields streaming responses.
Similar to
call
, but designed for scenarios where the Axon sends back data in multiple chunks or streams. The function yields each chunk as it is received. This is useful for processing large responses piece by piece without waiting for the entire data to be transmitted.- Parameters:
target_axon (Union['bittensor.AxonInfo', 'bittensor.axon']) – The target Axon to send the request to.
synapse (bittensor.Synapse, optional) – The Synapse object encapsulating the data. Defaults to a new
bittensor.Synapse()
instance.timeout (float, optional) – Maximum duration to wait for a response (or a chunk of the response) from the Axon in seconds. Defaults to
12.0
.deserialize (bool, optional) – Determines if each received chunk should be deserialized. Defaults to
True
.
- Yields:
object – Each yielded object contains a chunk of the arbitrary response data from the Axon. bittensor.Synapse: After the AsyncGenerator has been exhausted, yields the final filled Synapse.
- Return type:
AsyncGenerator[Any]
- close_session()#
Closes the internal aiohttp client session synchronously.
This method ensures the proper closure and cleanup of the aiohttp client session, releasing any resources like open connections and internal buffers. It is crucial for preventing resource leakage and should be called when the dendrite instance is no longer in use, especially in synchronous contexts.
Note
This method utilizes asyncio’s event loop to close the session asynchronously from a synchronous context. It is advisable to use this method only when asynchronous context management is not feasible.
- Usage:
When finished with dendrite in a synchronous context
dendrite_instance.close_session()
.
- async forward(axons, synapse=bittensor.Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False)#
Asynchronously sends requests to one or multiple Axons and collates their responses.
This function acts as a bridge for sending multiple requests concurrently or sequentially based on the provided parameters. It checks the type of the target Axons, preprocesses the requests, and then sends them off. After getting the responses, it processes and collates them into a unified format.
When querying an Axon that sends a single response, this function returns a Synapse object containing the response data. If multiple Axons are queried, a list of Synapse objects is returned, each containing the response from the corresponding Axon.
For example:
>>> ... >>> wallet = bittensor.wallet() # Initialize a wallet >>> synapse = bittensor.Synapse(...) # Create a synapse object that contains query data >>> dendrte = bittensor.dendrite(wallet = wallet) # Initialize a dendrite instance >>> axons = metagraph.axons # Create a list of axons to query >>> responses = await dendrite(axons, synapse) # Send the query to all axons and await the responses
When querying an Axon that sends back data in chunks using the Dendrite, this function returns an AsyncGenerator that yields each chunk as it is received. The generator can be iterated over to process each chunk individually.
For example:
>>> ... >>> dendrte = bittensor.dendrite(wallet = wallet) >>> async for chunk in dendrite.forward(axons, synapse, timeout, deserialize, run_async, streaming): >>> # Process each chunk here >>> print(chunk)
- Parameters:
axons (Union[List[Union['bittensor.AxonInfo', 'bittensor.axon']], Union['bittensor.AxonInfo', 'bittensor.axon']]) – The target Axons to send requests to. Can be a single Axon or a list of Axons.
synapse (bittensor.Synapse, optional) – The Synapse object encapsulating the data. Defaults to a new
bittensor.Synapse()
instance.timeout (float, optional) – Maximum duration to wait for a response from an Axon in seconds. Defaults to
12.0
.deserialize (bool, optional) – Determines if the received response should be deserialized. Defaults to
True
.run_async (bool, optional) – If
True
, sends requests concurrently. Otherwise, sends requests sequentially. Defaults toTrue
.streaming (bool, optional) – Indicates if the response is expected to be in streaming format. Defaults to
False
.
- Returns:
If a single Axon is targeted, returns its response. If multiple Axons are targeted, returns a list of their responses.
- Return type:
Union[AsyncGenerator, bittensor.Synapse, List[bittensor.Synapse]]
- preprocess_synapse_for_request(target_axon_info, synapse, timeout=12.0)#
Preprocesses the synapse for making a request. This includes building headers for Dendrite and Axon and signing the request.
- Parameters:
target_axon_info (bittensor.AxonInfo) – The target axon information.
synapse (bittensor.Synapse) – The synapse object to be preprocessed.
timeout (float, optional) – The request timeout duration in seconds. Defaults to
12.0
seconds.
- Returns:
The preprocessed synapse.
- Return type:
- process_server_response(server_response, json_response, local_synapse)#
Processes the server response, updates the local synapse state with the server’s state and merges headers set by the server.
- Parameters:
server_response (object) –
The aiohttp response object from the server.
json_response (dict) – The parsed JSON response from the server.
local_synapse (bittensor.Synapse) – The local synapse object to be updated.
- Raises:
None – But errors in attribute setting are silently ignored.
- query(*args, **kwargs)#
Makes a synchronous request to multiple target Axons and returns the server responses.
Cleanup is automatically handled and sessions are closed upon completed requests.
- Parameters:
axons (Union[List[Union['bittensor.AxonInfo', 'bittensor.axon']], Union['bittensor.AxonInfo', 'bittensor.axon']]) – The list of target Axon information.
synapse (bittensor.Synapse, optional) – The Synapse object. Defaults to
bittensor.Synapse()
.timeout (float, optional) – The request timeout duration in seconds. Defaults to
12.0
seconds.
- Returns:
If a single target axon is provided, returns the response from that axon. If multiple target axons are provided, returns a list of responses from all target axons.
- Return type:
Union[bittensor.Synapse, List[bittensor.Synapse]]
- bittensor.deserialize_keypair_from_keyfile_data(keyfile_data)#
Deserializes Keypair object from passed keyfile data.
- Parameters:
keyfile_data (bytes) – The keyfile data as bytes to be loaded.
- Returns:
The Keypair loaded from bytes.
- Return type:
keypair (bittensor.Keypair)
- Raises:
KeyFileError – Raised if the passed bytes cannot construct a keypair object.
- bittensor.display_mnemonic_msg(keypair, key_type)#
Display the mnemonic and a warning message to keep the mnemonic safe.
- Parameters:
keypair (Keypair) – Keypair object.
key_type (str) – Type of the key (coldkey or hotkey).
- bittensor.encrypt_keyfile_data(keyfile_data, password=None)#
Encrypts the passed keyfile data using ansible vault.
- bittensor.from_scale_encoding(input, type_name, is_vec=False, is_option=False)#
- Parameters:
input (Union[List[int], bytes, scalecodec.base.ScaleBytes]) –
type_name (ChainDataType) –
is_vec (bool) –
is_option (bool) –
- Return type:
Optional[Dict]
- bittensor.from_scale_encoding_using_type_string(input, type_string)#
- bittensor.get_coldkey_password_from_environment(coldkey_name)#
Retrieves the cold key password from the environment variables.
- bittensor.get_size(obj, seen=None)#
Recursively finds size of objects.
This function traverses every item of a given object and sums their sizes to compute the total size.
- class bittensor.keyfile(path)#
Defines an interface for a substrate interface keypair stored on device.
- Parameters:
path (str) –
- property data: bytes#
Returns the keyfile data under path.
- Returns:
The keyfile data stored under the path.
- Return type:
keyfile_data (bytes)
- Raises:
KeyFileError – Raised if the file does not exist, is not readable, or writable.
- property keyfile_data: bytes#
Returns the keyfile data under path.
- Returns:
The keyfile data stored under the path.
- Return type:
keyfile_data (bytes)
- Raises:
KeyFileError – Raised if the file does not exist, is not readable, or writable.
- property keypair: bittensor.Keypair#
Returns the keypair from path, decrypts data if the file is encrypted.
- Returns:
The keypair stored under the path.
- Return type:
keypair (bittensor.Keypair)
- Raises:
KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.
- __repr__()#
Return repr(self).
- __str__()#
Return str(self).
- _may_overwrite()#
Asks the user if it is okay to overwrite the file.
- Returns:
True
if the user allows overwriting the file.- Return type:
may_overwrite (bool)
- _read_keyfile_data_from_file()#
Reads the keyfile data from the file.
- Returns:
The keyfile data stored under the path.
- Return type:
keyfile_data (bytes)
- Raises:
KeyFileError – Raised if the file does not exist or is not readable.
- _write_keyfile_data_to_file(keyfile_data, overwrite=False)#
Writes the keyfile data to the file.
- Parameters:
- Raises:
KeyFileError – Raised if the file is not writable or the user responds No to the overwrite prompt.
- check_and_update_encryption(print_result=True, no_prompt=False)#
Check the version of keyfile and update if needed.
- Parameters:
- Raises:
KeyFileError – Raised if the file does not exists, is not readable, writable.
- Returns:
Return
True
if the keyfile is the most updated with nacl, elseFalse
.- Return type:
result (bool)
- decrypt(password=None)#
Decrypts the file under the path.
- Parameters:
password (str, optional) – The password for decryption. If
None
, asks for user input.- Raises:
KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.
- encrypt(password=None)#
Encrypts the file under the path.
- Parameters:
password (str, optional) – The password for encryption. If
None
, asks for user input.- Raises:
KeyFileError – Raised if the file does not exist, is not readable, or writable.
- exists_on_device()#
Returns
True
if the file exists on the device.- Returns:
True
if the file is on the device.- Return type:
on_device (bool)
- get_keypair(password=None)#
Returns the keypair from the path, decrypts data if the file is encrypted.
- Parameters:
password (str, optional) – The password used to decrypt the file. If
None
, asks for user input.- Returns:
The keypair stored under the path.
- Return type:
keypair (bittensor.Keypair)
- Raises:
KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.
- is_encrypted()#
Returns
True
if the file under path is encrypted.- Returns:
True
if the file is encrypted.- Return type:
encrypted (bool)
- is_readable()#
Returns
True
if the file under path is readable.- Returns:
True
if the file is readable.- Return type:
readable (bool)
- is_writable()#
Returns
True
if the file under path is writable.- Returns:
True
if the file is writable.- Return type:
writable (bool)
- make_dirs()#
Creates directories for the path if they do not exist.
- set_keypair(keypair, encrypt=True, overwrite=False, password=None)#
Writes the keypair to the file and optionally encrypts data.
- Parameters:
keypair (bittensor.Keypair) – The keypair to store under the path.
encrypt (bool, optional) – If
True
, encrypts the file under the path. Default isTrue
.overwrite (bool, optional) – If
True
, forces overwrite of the current file. Default isFalse
.password (str, optional) – The password used to encrypt the file. If
None
, asks for user input.
- Raises:
KeyFileError – Raised if the file does not exist, is not readable, writable, or if the password is incorrect.
- bittensor.keyfile_data_encryption_method(keyfile_data)#
Returns
true
if the keyfile data is encrypted.
- bittensor.keyfile_data_is_encrypted(keyfile_data)#
Returns
true
if the keyfile data is encrypted.
- bittensor.keyfile_data_is_encrypted_ansible(keyfile_data)#
Returns true if the keyfile data is ansible encrypted.
- bittensor.keyfile_data_is_encrypted_legacy(keyfile_data)#
Returns true if the keyfile data is legacy encrypted. :param keyfile_data: The bytes to validate. :type keyfile_data: bytes
- bittensor.keyfile_data_is_encrypted_nacl(keyfile_data)#
Returns true if the keyfile data is NaCl encrypted.
- bittensor.legacy_encrypt_keyfile_data(keyfile_data, password=None)#
- class bittensor.logging#
Standardized logging for Bittensor.
- classmethod _format(prefix, sufix=None)#
Format logging message
- classmethod add_args(parser, prefix=None)#
Accept specific arguments fro parser
- Parameters:
parser (argparse.ArgumentParser) –
prefix (str) –
- classmethod check_config(config)#
Check config
- Parameters:
config (bittensor.config) –
- classmethod config()#
Get config from the argument parser.
- Returns:
bittensor.config object
- classmethod exception(prefix, sufix=None)#
Exception logging with traceback
- classmethod help()#
Print help to stdout
- classmethod log_filter(record)#
Filter out debug log if debug is not on
- classmethod log_formatter(record)#
Log with different format according to record[‘extra’]
- classmethod log_save_filter(record)#
- classmethod log_save_formatter(record)#
- classmethod set_debug(debug_on=True)#
Set debug for the specific cls class
- Parameters:
debug_on (bool) –
- classmethod set_trace(trace_on=True)#
Set trace back for the specific cls class
- Parameters:
trace_on (bool) –
- classmethod success(prefix, sufix=None)#
Success logging
- class bittensor.metagraph(netuid, network='finney', lite=True, sync=True)#
Bases:
torch.nn.Module
The metagraph class is a core component of the Bittensor network, representing the neural graph that forms the backbone of the decentralized machine learning system.
The metagraph is a dynamic representation of the network’s state, capturing the interconnectedness and attributes of neurons (participants) in the Bittensor ecosystem. This class is not just a static structure but a live reflection of the network, constantly updated and synchronized with the state of the blockchain.
In Bittensor, neurons are akin to nodes in a distributed system, each contributing computational resources and participating in the network’s collective intelligence. The metagraph tracks various attributes of these neurons, such as stake, trust, and consensus, which are crucial for the network’s incentive mechanisms and the Yuma Consensus algorithm as outlined in the NeurIPS paper. These attributes govern how neurons interact, how they are incentivized, and their roles within the network’s decision-making processes.
- Parameters:
netuid (int) – A unique identifier that distinguishes between different instances or versions of the Bittensor network.
network (str) – The name of the network, signifying specific configurations or iterations within the Bittensor ecosystem.
version (torch.nn.parameter.Parameter) – The version number of the network, formatted for compatibility with PyTorch models, integral for tracking network updates.
n (torch.nn.Parameter) – The total number of neurons in the network, reflecting its size and complexity.
block (torch.nn.Parameter) – The current block number in the blockchain, crucial for synchronizing with the network’s latest state.
stake – Represents the cryptocurrency staked by neurons, impacting their influence and earnings within the network.
total_stake – The cumulative stake across all neurons.
ranks – Neuron rankings as per the Yuma Consensus algorithm, influencing their incentive distribution and network authority.
trust – Scores indicating the reliability of neurons, mainly miners, within the network’s operational context.
consensus – Scores reflecting each neuron’s alignment with the network’s collective decisions.
validator_trust – Trust scores for validator neurons, crucial for network security and validation.
incentive – Rewards allocated to neurons, particularly miners, for their network contributions.
emission – The rate at which rewards are distributed to neurons.
dividends – Rewards received primarily by validators as part of the incentive mechanism.
active – Status indicating whether a neuron is actively participating in the network.
last_update – Timestamp of the latest update to a neuron’s data.
validator_permit – Indicates if a neuron is authorized to act as a validator.
weights – Inter-neuronal weights set by each neuron, influencing network dynamics.
bonds – Represents speculative investments by neurons in others, part of the reward mechanism.
uids – Unique identifiers for each neuron, essential for network operations.
axons (List) – Details about each neuron’s axon, critical for facilitating network communication.
lite (bool) –
sync (bool) –
The metagraph plays a pivotal role in Bittensor’s decentralized AI operations, influencing everything from data propagation to reward distribution. It embodies the principles of decentralized governance and collaborative intelligence, ensuring that the network remains adaptive, secure, and efficient.
- Example Usage:
Initializing the metagraph to represent the current state of the Bittensor network:
metagraph = bt.metagraph(netuid=config.netuid, network=subtensor.network, sync=False)
Synchronizing the metagraph with the network to reflect the latest state and neuron data:
metagraph.sync(subtensor=subtensor)
Accessing metagraph properties to inform network interactions and decisions:
total_stake = metagraph.S neuron_ranks = metagraph.R neuron_incentives = metagraph.I ...
Maintaining a local copy of hotkeys for querying and interacting with network entities:
hotkeys = deepcopy(metagraph.hotkeys)
- property B: torch.FloatTensor#
Bonds in the Bittensor network represent a speculative reward mechanism where neurons can accumulate bonds in other neurons. Bonds are akin to investments or stakes in other neurons, reflecting a belief in their future value or performance. This mechanism encourages correct weighting and collaboration among neurons while providing an additional layer of incentive.
- Returns:
A tensor representing the bonds held by each neuron, where each value signifies the proportion of bonds owned by one neuron in another.
- Return type:
torch.FloatTensor
- property C: torch.FloatTensor#
Represents the consensus values of neurons in the Bittensor network. Consensus is a measure of how much a neuron’s contributions are trusted and agreed upon by the majority of the network. It is calculated based on a staked weighted trust system, where the network leverages the collective judgment of all participating peers. Higher consensus values indicate that a neuron’s contributions are more widely trusted and valued across the network.
- Returns:
A tensor of consensus values, where each element reflects the level of trust and agreement a neuron has achieved within the network.
- Return type:
torch.FloatTensor
- property D: torch.FloatTensor#
Represents the dividends received by neurons in the Bittensor network. Dividends are a form of reward or distribution, typically given to neurons based on their stake, performance, and contribution to the network. They are an integral part of the network’s incentive structure, encouraging active and beneficial participation.
- Returns:
A tensor of dividend values, where each element indicates the dividends received by a neuron, reflecting their share of network rewards.
- Return type:
torch.FloatTensor
- property E: torch.FloatTensor#
Denotes the emission values of neurons in the Bittensor network. Emissions refer to the distribution or release of rewards (often in the form of cryptocurrency) to neurons, typically based on their stake and performance. This mechanism is central to the network’s incentive model, ensuring that active and contributing neurons are appropriately rewarded.
- Returns:
A tensor where each element represents the emission value for a neuron, indicating the amount of reward distributed to that neuron.
- Return type:
torch.FloatTensor
- property I: torch.FloatTensor#
Incentive values of neurons represent the rewards they receive for their contributions to the network. The Bittensor network employs an incentive mechanism that rewards neurons based on their informational value, stake, and consensus with other peers. This ensures that the most valuable and trusted contributions are incentivized.
- Returns:
A tensor of incentive values, indicating the rewards or benefits accrued by each neuron based on their contributions and network consensus.
- Return type:
torch.FloatTensor
- property R: torch.FloatTensor#
Contains the ranks of neurons in the Bittensor network. Ranks are determined by the network based on each neuron’s performance and contributions. Higher ranks typically indicate a greater level of contribution or performance by a neuron. These ranks are crucial in determining the distribution of incentives within the network, with higher-ranked neurons receiving more incentive.
- Returns:
A tensor where each element represents the rank of a neuron. Higher values indicate higher ranks within the network.
- Return type:
torch.FloatTensor
- property S: torch.FloatTensor#
Represents the stake of each neuron in the Bittensor network. Stake is an important concept in the Bittensor ecosystem, signifying the amount of network weight (or “stake”) each neuron holds, represented on a digital ledger. The stake influences a neuron’s ability to contribute to and benefit from the network, playing a crucial role in the distribution of incentives and decision-making processes.
- Returns:
A tensor representing the stake of each neuron in the network. Higher values signify a greater stake held by the respective neuron.
- Return type:
torch.FloatTensor
- property T: torch.FloatTensor#
Represents the trust values assigned to each neuron in the Bittensor network. Trust is a key metric that reflects the reliability and reputation of a neuron based on its past behavior and contributions. It is an essential aspect of the network’s functioning, influencing decision-making processes and interactions between neurons.
The trust matrix is inferred from the network’s inter-peer weights, indicating the level of trust each neuron has in others. A higher value in the trust matrix suggests a stronger trust relationship between neurons.
- Returns:
A tensor of trust values, where each element represents the trust level of a neuron. Higher values denote a higher level of trust within the network.
- Return type:
torch.FloatTensor
- property Tv: torch.FloatTensor#
Contains the validator trust values of neurons in the Bittensor network. Validator trust is specifically associated with neurons that act as validators within the network. This specialized form of trust reflects the validators’ reliability and integrity in their role, which is crucial for maintaining the network’s stability and security.
Validator trust values are particularly important for the network’s consensus and validation processes, determining the validators’ influence and responsibilities in these critical functions.
- Returns:
A tensor of validator trust values, specifically applicable to neurons serving as validators, where higher values denote greater trustworthiness in their validation roles.
- Return type:
torch.FloatTensor
- property W: torch.FloatTensor#
Represents the weights assigned to each neuron in the Bittensor network. In the context of Bittensor, weights are crucial for determining the influence and interaction between neurons. Each neuron is responsible for setting its weights, which are then recorded on a digital ledger. These weights are reflective of the neuron’s assessment or judgment of other neurons in the network.
The weight matrix \(W = [w_{ij}]\) is a key component of the network’s architecture, where the \(i^{th}\) row is set by neuron \(i\) and represents its weights towards other neurons. These weights influence the ranking and incentive mechanisms within the network. Higher weights from a neuron towards another can imply greater trust or value placed on that neuron’s contributions.
- Returns:
A tensor of inter-peer weights, where each element \(w_{ij}\) represents the weight assigned by neuron \(i\) to neuron \(j\). This matrix is fundamental to the network’s functioning, influencing the distribution of incentives and the inter-neuronal dynamics.
- Return type:
torch.FloatTensor
- property addresses: List[str]#
Provides a list of IP addresses for each neuron in the Bittensor network. These addresses are used for network communication, allowing neurons to connect, interact, and exchange information with each other. IP addresses are fundamental for the network’s peer-to-peer communication infrastructure.
- Returns:
A list of IP addresses, with each string representing the address of a neuron. These addresses enable the decentralized, distributed nature of the network, facilitating direct communication and data exchange among neurons.
- Return type:
List[str]
Note
While IP addresses are a basic aspect of network communication, specific details about their use in the Bittensor network may not be covered in the NeurIPS paper. They are, however, integral to the functioning of any distributed network.
- property coldkeys: List[str]#
Contains a list of
coldkeys
for each neuron in the Bittensor network.Coldkeys are similar to hotkeys but are typically used for more secure, offline activities such as storing assets or offline signing of transactions. They are an important aspect of a neuron’s security, providing an additional layer of protection for sensitive operations and assets.
- Returns:
A list of coldkeys, each string representing the coldkey of a neuron. These keys play a vital role in the secure management of assets and sensitive operations within the network.
- Return type:
List[str]
Note
The concept of coldkeys, while not explicitly covered in the NeurIPS paper, is a standard practice in blockchain and decentralized networks for enhanced security and asset protection.
- property hotkeys: List[str]#
Represents a list of
hotkeys
for each neuron in the Bittensor network.Hotkeys are unique identifiers used by neurons for active participation in the network, such as sending and receiving information or transactions. They are akin to public keys in cryptographic systems and are essential for identifying and authenticating neurons within the network’s operations.
- Returns:
A list of hotkeys, with each string representing the hotkey of a corresponding neuron.
These keys are crucial for the network’s security and integrity, ensuring proper identification and authorization of network participants.
- Return type:
List[str]
Note
While the NeurIPS paper may not explicitly detail the concept of hotkeys, they are a fundamental of decentralized networks for secure and authenticated interactions.
- __repr__()#
Provides a detailed string representation of the metagraph object, intended for unambiguous understanding and debugging purposes. This method simply calls the
__str__()
method, ensuring consistency between the informal and formal string representations of the metagraph.- Returns:
The same string representation as provided by the
__str__()
method, detailing the metagraph’s key attributes including network UID, number of neurons, block number, and network name.- Return type:
Example
The
__repr__()
output can be used in debugging to get a clear and concise description of the metagraph:metagraph_repr = repr(metagraph) print(metagraph_repr) # Output mirrors that of __str__
- __str__()#
Provides a human-readable string representation of the metagraph object. This representation includes key identifiers and attributes of the metagraph, making it easier to quickly understand the state and configuration of the metagraph in a simple format.
- Returns:
A string that succinctly represents the metagraph, including its network UID, the total number of neurons (n), the current block number, and the network’s name. This format is particularly useful for logging, debugging, and displaying the metagraph in a concise manner.
- Return type:
Example
When printing the metagraph object or using it in a string context, this method is automatically invoked:
print(metagraph) # Output: "metagraph(netuid:1, n:100, block:500, network:finney)"
- _assign_neurons(block, lite, subtensor)#
Assigns neurons to the metagraph based on the provided block number and the lite flag.
This method is responsible for fetching and setting the neuron data in the metagraph, which includes neuron attributes like UID, stake, trust, and other relevant information.
- Parameters:
block – The block number for which the neuron data needs to be fetched. If
None
, the latest block data is used.lite – A boolean flag indicating whether to use a lite version of the neuron data. The lite version typically includes essential information and is quicker to fetch and process.
subtensor – The subtensor instance used for fetching neuron data from the network.
- Internal Usage:
Used internally during the sync process to fetch and set neuron data:
self._assign_neurons(block, lite, subtensor)
- _create_tensor(data, dtype)#
Creates a tensor parameter with the given data and data type. This method is a utility function used internally to encapsulate data into a PyTorch tensor, making it compatible with the metagraph’s PyTorch model structure.
- Parameters:
data – The data to be included in the tensor. This could be any numeric data, like stakes, ranks, etc.
dtype – The data type for the tensor, typically a PyTorch data type like
torch.float32
ortorch.int64
.
- Returns:
A tensor parameter encapsulating the provided data.
- Return type:
torch.nn.Parameter
- Internal Usage:
Used internally to create tensor parameters for various metagraph attributes:
self.stake = self._create_tensor(neuron_stakes, dtype=torch.float32)
- _initialize_subtensor(subtensor)#
Initializes the subtensor to be used for syncing the metagraph.
This method ensures that a subtensor instance is available and properly set up for data retrieval during the synchronization process.
If no subtensor is provided, this method is responsible for creating a new instance of the subtensor, configured according to the current network settings.
- Parameters:
subtensor – The subtensor instance provided for initialization. If
None
, a new subtensor instance is created using the current network configuration.- Returns:
The initialized subtensor instance, ready to be used for syncing the metagraph.
- Return type:
- Internal Usage:
Used internally during the sync process to ensure a valid subtensor instance is available:
subtensor = self._initialize_subtensor(subtensor)
- _process_root_weights(data, attribute, subtensor)#
Specifically processes the root weights data for the metagraph. This method is similar to
_process_weights_or_bonds()
but is tailored for processing root weights, which have a different structure and significance in the network.- Parameters:
data – The raw root weights data to be processed.
attribute (str) – A string indicating the attribute type, here it’s typically
weights
.subtensor (bittensor.subtensor) – The subtensor instance used for additional data and context needed in processing.
- Returns:
A tensor parameter encapsulating the processed root weights data.
- Return type:
torch.nn.Parameter
- Internal Usage:
Used internally to process and set root weights for the metagraph:
self.root_weights = self._process_root_weights( raw_root_weights_data, "weights", subtensor )
- _process_weights_or_bonds(data, attribute)#
Processes the raw weights or bonds data and converts it into a structured tensor format. This method handles the transformation of neuron connection data (
weights
orbonds
) from a list or other unstructured format into a tensor that can be utilized within the metagraph model.- Parameters:
data – The raw weights or bonds data to be processed. This data typically comes from the subtensor.
attribute (str) – A string indicating whether the data is
weights
orbonds
, which determines the specific processing steps to be applied.
- Returns:
A tensor parameter encapsulating the processed weights or bonds data.
- Return type:
torch.nn.Parameter
- Internal Usage:
Used internally to process and set weights or bonds for the neurons:
self.weights = self._process_weights_or_bonds(raw_weights_data, "weights")
- _set_metagraph_attributes(block, subtensor)#
Sets various attributes of the metagraph based on the latest network data fetched from the subtensor.
This method updates parameters like the number of neurons, block number, stakes, trusts, ranks, and other neuron-specific information.
- Parameters:
block – The block number for which the metagraph attributes need to be set. If
None
, the latest block data is used.subtensor – The subtensor instance used for fetching the latest network data.
- Internal Usage:
Used internally during the sync process to update the metagraph’s attributes:
self._set_metagraph_attributes(block, subtensor)
- _set_weights_and_bonds(subtensor=None)#
Computes and sets the weights and bonds for each neuron in the metagraph. This method is responsible for processing the raw weight and bond data obtained from the network and converting it into a structured format suitable for the metagraph model.
- Parameters:
subtensor (bittensor.subtensor) – The subtensor instance used for fetching weights and bonds data. If
None
, the weights and bonds are not updated.
- Internal Usage:
Used internally during the sync process to update the weights and bonds of the neurons:
self._set_weights_and_bonds(subtensor=subtensor)
- load()#
Loads the state of the metagraph from the default save directory. This method is instrumental for restoring the metagraph to its last saved state. It automatically identifies the save directory based on the
network
andnetuid
properties of the metagraph, locates the latest block file in that directory, and loads all metagraph parameters from it.This functionality is particularly beneficial when continuity in the state of the metagraph is necessary across different runtime sessions, or after a restart of the system. It ensures that the metagraph reflects the exact state it was in at the last save point, maintaining consistency in the network’s representation.
The method delegates to
load_from_path
, supplying it with the directory path constructed from the metagraph’s currentnetwork
andnetuid
properties. This abstraction simplifies the process of loading the metagraph’s state for the user, requiring no direct path specifications.- Returns:
The metagraph instance after loading its state from the default directory.
- Return type:
Example
Load the metagraph state from the last saved snapshot in the default directory:
metagraph.load()
After this operation, the metagraph’s parameters and neuron data are restored to their state at the time of the last save in the default directory.
Note
The default save directory is determined based on the metagraph’s
network
andnetuid
attributes. It is important to ensure that these attributes are set correctly and that the default save directory contains the appropriate state files for the metagraph.
- load_from_path(dir_path)#
Loads the state of the metagraph from a specified directory path. This method is crucial for restoring the metagraph to a specific state based on saved data. It locates the latest block file in the given directory and loads all metagraph parameters from it. This is particularly useful for analyses that require historical states of the network or for restoring previous states of the metagraph in different execution environments.
The method first identifies the latest block file in the specified directory, then loads the metagraph state including neuron attributes and parameters from this file. This ensures that the metagraph is accurately reconstituted to reflect the network state at the time of the saved block.
- Parameters:
dir_path (str) – The directory path where the metagraph’s state files are stored. This path should contain one or more saved state files, typically named in a format that includes the block number.
- Returns:
The metagraph instance after loading its state from the specified directory path.
- Return type:
Example
Load the metagraph state from a specific directory:
dir_path = "/path/to/saved/metagraph/states" metagraph.load_from_path(dir_path)
The metagraph is now restored to the state it was in at the time of the latest saved block in the specified directory.
Note
This method assumes that the state files in the specified directory are correctly formatted and contain valid data for the metagraph. It is essential to ensure that the directory path and the state files within it are accurate and consistent with the expected metagraph structure.
- metadata()#
Retrieves the metadata of the metagraph, providing key information about the current state of the Bittensor network. This metadata includes details such as the network’s unique identifier (
netuid
), the total number of neurons (n
), the current block number, the network’s name, and the version of the Bittensor network.- Returns:
A dictionary containing essential metadata about the metagraph, including:
netuid
: The unique identifier for the network.n
: The total number of neurons in the network.block
: The current block number in the network’s blockchain.network
: The name of the Bittensor network.version
: The version number of the Bittensor software.
- Return type:
Note
This metadata is crucial for understanding the current state and configuration of the network, as well as for tracking its evolution over time.
- save()#
Saves the current state of the metagraph to a file on disk. This function is crucial for persisting the current state of the network’s metagraph, which can later be reloaded or analyzed. The save operation includes all neuron attributes and parameters, ensuring a complete snapshot of the metagraph’s state.
- Returns:
The metagraph instance after saving its state.
- Return type:
Example
Save the current state of the metagraph to the default directory:
metagraph.save()
The saved state can later be loaded to restore or analyze the metagraph’s state at this point.
If using the default save path:
metagraph.load()
If using a custom save path:
metagraph.load_from_path(dir_path)
- sync(block=None, lite=True, subtensor=None)#
Synchronizes the metagraph with the Bittensor network’s current state. It updates the metagraph’s attributes to reflect the latest data from the network, ensuring the metagraph represents the most current state of the network.
- Parameters:
block (Optional[int]) – A specific block number to synchronize with. If None, the metagraph syncs with the latest block. This allows for historical analysis or specific state examination of the network.
lite (bool) – If True, a lite version of the metagraph is used for quicker synchronization. This is beneficial when full detail is not necessary, allowing for reduced computational and time overhead.
subtensor (Optional[bittensor.subtensor]) – An instance of the subtensor class from Bittensor, providing an interface to the underlying blockchain data. If provided, this instance is used for data retrieval during synchronization.
- Returns:
The metagraph instance, updated to the state of the specified block or the latest network state.
- Return type:
Example
Sync the metagraph with the latest block from the subtensor, using the lite version for efficiency:
metagraph.sync(subtensor=subtensor)
Sync with a specific block number for detailed analysis:
metagraph.sync(block=12345, lite=False, subtensor=subtensor)
Note
If attempting to access data beyond the previous 300 blocks, you must use the
archive
network for subtensor. Light nodes are configured only to store the previous 300 blocks if connecting to finney or test networks.For example:
subtensor = bittensor.subtensor(network='archive')
- bittensor.serialized_keypair_to_keyfile_data(keypair)#
Serializes keypair object into keyfile data.
- Parameters:
keypair (bittensor.Keypair) – The keypair object to be serialized.
- Returns:
Serialized keypair data.
- Return type:
data (bytes)
- class bittensor.subtensor(network=None, config=None, _mock=False, log_verbose=True)#
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.
- Parameters:
network (str) – The name of the Bittensor network (e.g., ‘finney’, ‘test’, ‘archive’, ‘local’) the instance is connected to, determining the blockchain interaction context.
chain_endpoint (str) – The blockchain node endpoint URL, enabling direct communication with the Bittensor blockchain for transaction processing and data retrieval.
config (bittensor.config) –
_mock (bool) –
log_verbose (bool) –
Example Usage:
# Connect to the main Bittensor network (Finney). finney_subtensor = subtensor(network='finney') # Close websocket connection with the Bittensor network. finney_subtensor.close() # (Re)creates the websocket connection with the Bittensor network. finney_subtensor.connect_websocket() # Register a new neuron on the network. wallet = bittensor.wallet(...) # Assuming a wallet instance is created. 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=[...]) # Speculate by accumulating bonds in other promising neurons. success = finney_subtensor.delegate(wallet=wallet, delegate_ss58=other_neuron_ss58, amount=bond_amount) # Get the metagraph for a specific subnet using given subtensor connection metagraph = 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.
- property block: int#
Returns current chain block. :returns: Current chain block. :rtype: block (int)
- Return type:
- get_proposal_vote_data#
- _do_associate_ips(wallet, ip_info_list, netuid, wait_for_inclusion=False, wait_for_finalization=True)#
Sends an associate IPs extrinsic to the chain.
- Parameters:
wallet (
bittensor.wallet()
) – Wallet object.ip_info_list (
List[IPInfo]()
) – List of IPInfo objects.netuid (int) – Netuid to associate IPs to.
wait_for_inclusion (bool) – If
true
, waits for inclusion.wait_for_finalization (bool) – If
true
, waits for finalization.
- Returns:
True
if associate IPs was successful. error (Optional[str]()
): Error message if associate IPs failed, None otherwise.- Return type:
success (bool)
- _do_burned_register(netuid, wallet, wait_for_inclusion=False, wait_for_finalization=True)#
- _do_delegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#
- _do_nominate(wallet, wait_for_inclusion=True, wait_for_finalization=False)#
- _do_pow_register(netuid, wallet, pow_result, wait_for_inclusion=False, wait_for_finalization=True)#
Sends a (POW) register extrinsic to the chain.
- Parameters:
netuid (int) – The subnet to register on.
wallet (bittensor.wallet) – The wallet to register.
pow_result (POWSolution) – The PoW result to register.
wait_for_inclusion (bool) – If
true
, waits for the extrinsic to be included in a block.wait_for_finalization (bool) – If
true
, waits for the extrinsic to be finalized.
- Returns:
True
if the extrinsic was included in a block. error (Optional[str]):None
on success or not waiting for inclusion/finalization, otherwise the error message.- Return type:
success (bool)
- _do_root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True)#
- _do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
Internal method to submit a serve axon transaction to the Bittensor blockchain. This method creates and submits a transaction, enabling a neuron’s Axon to serve requests on the network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron.
call_params (AxonServeCallParams) – Parameters required for the serve axon call.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
- Returns:
A tuple containing a success flag and an optional error message.
- Return type:
This function is crucial for initializing and announcing a neuron’s Axon service on the network, enhancing the decentralized computation capabilities of Bittensor.
- _do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#
Sends a serve prometheus extrinsic to the chain. :param wallet: Wallet object. :type wallet:
bittensor.wallet()
:param call_params: Prometheus serve call parameters. :type call_params:PrometheusServeCallParams()
:param wait_for_inclusion: Iftrue
, waits for inclusion. :type wait_for_inclusion: bool :param wait_for_finalization: Iftrue
, waits for finalization. :type wait_for_finalization: bool- Returns:
True
if serve prometheus was successful. error (Optional[str]()
): Error message if serve prometheus failed,None
otherwise.- Return type:
success (bool)
- Parameters:
wallet (bittensor.wallet) –
call_params (bittensor.types.PrometheusServeCallParams) –
wait_for_inclusion (bool) –
wait_for_finalization (bool) –
- _do_set_weights(wallet, uids, vals, netuid, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=True)#
Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons. This method constructs and submits the transaction, handling retries and blockchain communication.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.
uids (List[int]) – List of neuron UIDs for which weights are being set.
vals (List[int]) – List of weight values corresponding to each UID.
netuid (int) – Unique identifier for the network.
version_key (int, optional) – Version key for compatibility with the network.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
- Returns:
A tuple containing a success flag and an optional error message.
- Return type:
This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions.
- _do_stake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#
Sends a stake extrinsic to the chain.
- Parameters:
wallet (
bittensor.wallet()
) – Wallet object that can sign the extrinsic.hotkey_ss58 (str) – Hotkey
ss58
address to stake to.amount (
Balance()
) – Amount to stake.wait_for_inclusion (bool) – If
true
, waits for inclusion before returning.wait_for_finalization (bool) – If
true
, waits for finalization before returning.
- Returns:
True
if the extrinsic was successful.- Return type:
success (bool)
- Raises:
StakeError – If the extrinsic failed.
- _do_swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True)#
- _do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)#
Sends a transfer extrinsic to the chain.
- Parameters:
wallet (
bittensor.wallet()
) – Wallet object.dest (str) – Destination public key address.
transfer_balance (
Balance()
) – Amount to transfer.wait_for_inclusion (bool) – If
true
, waits for inclusion.wait_for_finalization (bool) – If
true
, waits for finalization.
- Returns:
True
if transfer was successful. block_hash (str): Block hash of the transfer. On success and if wait_for_ finalization/inclusion isTrue
. error (str): Error message if transfer failed.- Return type:
success (bool)
- _do_undelegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#
- _do_unstake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#
Sends an unstake extrinsic to the chain.
- Parameters:
wallet (
bittensor.wallet()
) – Wallet object that can sign the extrinsic.hotkey_ss58 (str) – Hotkey
ss58
address to unstake from.amount (
Balance()
) – Amount to unstake.wait_for_inclusion (bool) – If
true
, waits for inclusion before returning.wait_for_finalization (bool) – If
true
, waits for finalization before returning.
- Returns:
True
if the extrinsic was successful.- Return type:
success (bool)
- Raises:
StakeError – If the extrinsic failed.
- _encode_params(call_definition, params)#
Returns a hex encoded string of the params using their types.
- Parameters:
call_definition (List[ParamWithTypes]) –
- Return type:
- static _null_neuron()#
- Return type:
- classmethod add_args(parser, prefix=None)#
- Parameters:
parser (argparse.ArgumentParser) –
prefix (str) –
- add_stake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Adds the specified amount of stake to a neuron identified by the hotkey
SS58
address. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives.- Parameters:
wallet (bittensor.wallet) – The wallet to be used for staking.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey associated with the neuron.amount (Union[Balance, float]) – The amount of TAO to stake.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the staking is successful, False otherwise.- Return type:
This function enables neurons to increase their stake in the network, enhancing their influence and potential rewards in line with Bittensor’s consensus and reward mechanisms.
- add_stake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Adds stakes to multiple neurons identified by their hotkey SS58 addresses. This bulk operation allows for efficient staking across different neurons from a single wallet.
- Parameters:
wallet (bittensor.wallet) – The wallet used for staking.
hotkey_ss58s (List[str]) – List of
SS58
addresses of hotkeys to stake to.amounts (List[Union[Balance, float]], optional) – Corresponding amounts of TAO to stake for each hotkey.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the staking is successful for all specified neurons, False otherwise.- Return type:
This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative nature of the Bittensor network.
- associated_validator_ip_info(netuid, block=None)#
Retrieves the list of all validator IP addresses associated with a specific subnet in the Bittensor network. This information is crucial for network communication and the identification of validator nodes.
- Parameters:
- Returns:
A list of IPInfo objects for validator nodes in the subnet, or
None
if no validators are associated.- Return type:
Optional[List[IPInfo]]
Validator IP information is key for establishing secure and reliable connections within the network, facilitating consensus and validation processes critical for the network’s integrity and performance.
- blocks_since_epoch(netuid, block=None)#
Returns network BlocksSinceLastStep hyper parameter
- bonds(netuid, block=None)#
Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its bonds with other neurons.
- Return type:
Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.
- burn(netuid, block=None)#
Retrieves the ‘Burn’ hyperparameter for a specified subnet. The ‘Burn’ parameter represents the amount of Tao that is effectively removed from circulation 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’s economic model, particularly how it manages inflation and the overall supply of its native token Tao.
- burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
Registers a neuron on the Bittensor network by burning TAO. This method of registration involves recycling TAO tokens, contributing to the network’s deflationary mechanism.
- Parameters:
wallet (bittensor.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.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the registration is successful, False otherwise.- Return type:
This function offers an alternative registration path, aligning with the network’s principles of token circulation and value conservation.
- close()#
Cleans up resources for this subtensor instance like active websocket connection and active extensions
- static config()#
- Return type:
- connect_websocket()#
(Re)creates the websocket connection, if the URL contains a ‘ws’ or ‘wss’ scheme
- delegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.
- Parameters:
wallet (bittensor.wallet) – The wallet containing the hotkey to be nominated.
wait_for_finalization (bool, optional) – If
True
, waits until the transaction is finalized on the blockchain.wait_for_inclusion (bool, optional) – If
True
, waits until the transaction is included in a block.delegate_ss58 (Optional[str]) –
amount (Union[bittensor.utils.balance.Balance, float]) –
prompt (bool) –
- Returns:
True
if the nomination process is successful, False otherwise.- Return type:
This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.
- static determine_chain_endpoint_and_network(network)#
Determines the chain endpoint and network from the passed network or chain_endpoint.
- Parameters:
- Returns:
The network flag. chain_endpoint (str): The chain endpoint flag. If set, overrides the
network
argument.- Return type:
network (str)
- difficulty(netuid, block=None)#
Retrieves the ‘Difficulty’ hyperparameter for a specified subnet in the Bittensor network. This parameter is instrumental in determining the computational challenge required for neurons to participate in consensus and validation processes.
- Parameters:
- Returns:
The value of the ‘Difficulty’ hyperparameter if the subnet exists,
None
otherwise.- Return type:
Optional[int]
The ‘Difficulty’ parameter directly impacts the network’s security and integrity by setting the computational effort required for validating transactions and participating in the network’s consensus mechanism.
- does_hotkey_exist(hotkey_ss58, block=None)#
Returns true if the hotkey is known by the chain and there are accounts.
- get_all_neurons_for_pubkey(hotkey_ss58, block=None)#
Retrieves information about all neuron instances associated with a given public key (hotkey
SS58
address) across different subnets of the Bittensor network. This function aggregates neuron data from various subnets to provide a comprehensive view of a neuron’s presence and status within the network.- Parameters:
- Returns:
A list of NeuronInfo objects detailing the neuron’s presence across various subnets.
- Return type:
List[NeuronInfo]
This function is valuable for analyzing a neuron’s overall participation, influence, and contributions across the Bittensor network.
- get_all_subnet_netuids(block=None)#
Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.
- Parameters:
block (Optional[int], optional) – The blockchain block number at which to retrieve the subnet netuids.
- Returns:
A list of subnet netuids.
- Return type:
List[int]
This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into its diversity and scale.
- get_all_subnets_info(block=None)#
Retrieves detailed information about all subnets within the Bittensor network. This function provides comprehensive data on each subnet, including its characteristics and operational parameters.
- Parameters:
block (Optional[int], optional) – The blockchain block number for the query.
- Returns:
A list of SubnetInfo objects, each containing detailed information about a subnet.
- Return type:
List[SubnetInfo]
Gaining insights into the subnets’ details assists in understanding the network’s composition, the roles of different subnets, and their unique features.
- get_all_uids_for_hotkey(hotkey_ss58, block=None)#
Retrieves all unique identifiers (UIDs) associated with a given hotkey across different subnets within the Bittensor network. This function helps in identifying all the neuron instances that are linked to a specific hotkey.
- Parameters:
- Returns:
A list of UIDs associated with the given hotkey across various subnets.
- Return type:
List[int]
This function is important for tracking a neuron’s presence and activities across different subnets within the Bittensor ecosystem.
- get_axon_info(netuid, hotkey_ss58, block=None)#
Returns the axon information for this hotkey account
- Parameters:
- Return type:
Optional[bittensor.chain_data.AxonInfo]
- get_balance(address, block=None)#
Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.
- Parameters:
- Returns:
The account balance at the specified block, represented as a Balance object.
- Return type:
Balance
This function is important for monitoring account holdings and managing financial transactions within the Bittensor ecosystem. It helps in assessing the economic status and capacity of network participants.
- get_balances(block=None)#
Retrieves the token balances of all accounts within the Bittensor network as of a specific blockchain block. This function provides a comprehensive view of the token distribution among different accounts.
- Parameters:
block (int, optional) – The blockchain block number at which to perform the query.
- Returns:
A dictionary mapping each account’s
ss58
address to its balance.- Return type:
Dict[str, Balance]
This function is valuable for analyzing the overall economic landscape of the Bittensor network, including the distribution of financial resources and the financial status of network participants.
- get_block_hash(block_id)#
Retrieves the hash of a specific block on the Bittensor blockchain. The block hash is a unique identifier representing the cryptographic hash of the block’s content, ensuring its integrity and immutability.
- Parameters:
block_id (int) – The block number for which the hash is to be retrieved.
- Returns:
The cryptographic hash of the specified block.
- Return type:
The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.
- get_commitment(netuid, uid, block=None)#
- get_current_block()#
Returns the current block number on the Bittensor blockchain. This function provides the latest block number, indicating the most recent state of the blockchain.
- Returns:
The current chain block number.
- Return type:
Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on the blockchain. It serves as a reference point for network activities and data synchronization.
- get_delegate_by_hotkey(hotkey_ss58, block=None)#
Retrieves detailed information about a delegate neuron based on its hotkey. This function provides a comprehensive view of the delegate’s status, including its stakes, nominators, and reward distribution.
- Parameters:
- Returns:
Detailed information about the delegate neuron,
None
if not found.- Return type:
Optional[DelegateInfo]
This function is essential for understanding the roles and influence of delegate neurons within the Bittensor network’s consensus and governance structures.
- get_delegate_take(hotkey_ss58, block=None)#
Retrieves the delegate ‘take’ percentage for a neuron identified by its hotkey. The ‘take’ represents the percentage of rewards that the delegate claims from its nominators’ stakes.
- Parameters:
- Returns:
The delegate take percentage, None if not available.
- Return type:
Optional[float]
The delegate take is a critical parameter in the network’s incentive structure, influencing the distribution of rewards among neurons and their nominators.
- get_delegated(coldkey_ss58, block=None)#
Retrieves a list of delegates and their associated stakes for a given coldkey. This function identifies the delegates that a specific account has staked tokens on.
- Parameters:
- Returns:
A list of tuples, each containing a delegate’s information and staked amount.
- Return type:
List[Tuple[DelegateInfo, Balance]]
This function is important for account holders to understand their stake allocations and their involvement in the network’s delegation and consensus mechanisms.
- get_delegates(block=None)#
Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.
- Parameters:
block (Optional[int], optional) – The blockchain block number for the query.
- Returns:
A list of DelegateInfo objects detailing each delegate’s characteristics.
- Return type:
List[DelegateInfo]
Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.
- get_emission_value_by_subnet(netuid, block=None)#
Retrieves the emission value of a specific subnet within the Bittensor network. The emission value represents the rate at which the subnet emits or distributes the network’s native token (Tao).
- Parameters:
- Returns:
The emission value of the subnet, None if not available.
- Return type:
Optional[float]
The emission value is a critical economic parameter, influencing the incentive distribution and reward mechanisms within the subnet.
- get_existential_deposit(block=None)#
Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped to conserve network resources.
- Parameters:
block (Optional[int], optional) – 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[Balance]
The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts.
- get_hotkey_owner(hotkey_ss58, block=None)#
Returns the coldkey owner of the passed hotkey
- get_netuids_for_hotkey(hotkey_ss58, block=None)#
Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with the hotkey is active.
- get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None)#
Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
Optional[NeuronInfo]
This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem.
- get_nominators_for_hotkey(hotkey_ss58, block=None)#
Retrieves a list of nominators and their stakes for a neuron identified by its hotkey. Nominators are neurons that stake their tokens on a delegate to support its operations.
- Parameters:
- Returns:
A list of tuples containing each nominator’s address and staked amount.
- Return type:
List[Tuple[str, Balance]]
This function provides insights into the neuron’s support network within the Bittensor ecosystem, indicating its trust and collaboration relationships.
- get_prometheus_info(netuid, hotkey_ss58, block=None)#
Returns the prometheus information for this hotkey account
- Parameters:
- Return type:
Optional[bittensor.chain_data.AxonInfo]
- get_proposal_call_data(proposal_hash, block=None)#
Retrieves the call data of a specific proposal on the Bittensor blockchain. This data provides detailed information about the proposal, including its purpose and specifications.
- Parameters:
- Returns:
An object containing the proposal’s call data, or
None
if not found.- Return type:
Optional[bittensor.ProposalCallData]
This function is crucial for analyzing the types of proposals made within the network and the specific changes or actions they intend to implement or address.
- get_proposal_hashes(block=None)#
Retrieves the list of proposal hashes currently present on the Bittensor blockchain. Each hash uniquely identifies a proposal made within the network.
- Parameters:
block (Optional[int], optional) – The blockchain block number to query the proposal hashes.
- Returns:
A list of proposal hashes, or
None
if not available.- Return type:
Optional[List[str]]
This function enables tracking and reviewing the proposals made in the network, offering insights into the active governance and decision-making processes.
- get_proposals(block=None)#
Retrieves all active proposals on the Bittensor blockchain, along with their call and voting data. This comprehensive view allows for a thorough understanding of the proposals and their reception by the senate.
- Parameters:
block (Optional[int], optional) – The blockchain block number to query the proposals.
- Returns:
A dictionary mapping proposal hashes to their corresponding call and vote data, or
None
if not available.- Return type:
Optional[Dict[str, Tuple[bittensor.ProposalCallData, bittensor.ProposalVoteData]]]
This function is integral for analyzing the governance activity on the Bittensor network, providing a holistic view of the proposals and their impact or potential changes within the network.
- get_senate_members(block=None)#
Retrieves the list of current senate members from the Bittensor blockchain. Senate members are responsible for governance and decision-making within the network.
- Parameters:
block (Optional[int], optional) – The blockchain block number at which to retrieve the senate members.
- Returns:
A list of
SS58
addresses of current senate members, orNone
if not available.- Return type:
Optional[List[str]]
Understanding the composition of the senate is key to grasping the governance structure and decision-making authority within the Bittensor network.
- get_stake(hotkey_ss58, block=None)#
Returns a list of stake tuples (coldkey, balance) for each delegating coldkey including the owner
- get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block=None)#
Returns the stake under a coldkey - hotkey pairing
- get_stake_info_for_coldkey(coldkey_ss58, block=None)#
Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates.
- Parameters:
- Returns:
A list of StakeInfo objects detailing the stake allocations for the account.
- Return type:
List[StakeInfo]
Stake information is vital for account holders to assess their investment and participation in the network’s delegation and consensus processes.
- get_stake_info_for_coldkeys(coldkey_ss58_list, block=None)#
Retrieves stake information for a list of coldkeys. This function aggregates stake data for multiple accounts, providing a collective view of their stakes and delegations.
- Parameters:
- Returns:
A dictionary mapping each coldkey to a list of its StakeInfo objects.
- Return type:
This function is useful for analyzing the stake distribution and delegation patterns of multiple accounts simultaneously, offering a broader perspective on network participation and investment strategies.
- get_subnet_burn_cost(block=None)#
Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the amount of Tao that needs to be locked or burned to establish a new subnet.
- Parameters:
block (Optional[int]) – The blockchain block number for the query.
- Returns:
The burn cost for subnet registration.
- Return type:
The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling the proliferation of subnets and ensuring their commitment to the network’s long-term viability.
- get_subnet_connection_requirement(netuid_0, netuid_1, block=None)#
- get_subnet_connection_requirements(netuid, block=None)#
Retrieves the connection requirements for a specific subnet within the Bittensor network. This function provides details on the criteria that must be met for neurons to connect to the subnet.
- Parameters:
- Returns:
A dictionary detailing the connection requirements for the subnet.
- Return type:
Understanding these requirements is crucial for neurons looking to participate in or interact with specific subnets, ensuring compliance with their connection standards.
- get_subnet_hyperparameters(netuid, block=None)#
Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.
- Parameters:
- Returns:
The subnet’s hyperparameters, or
None
if not available.- Return type:
Optional[SubnetHyperparameters]
Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network’s consensus and incentive mechanisms.
- get_subnet_info(netuid, block=None)#
Retrieves detailed information about a specific subnet within the Bittensor network. This function provides key data on the subnet, including its operational parameters and network status.
- Parameters:
- Returns:
Detailed information about the subnet, or
None
if not found.- Return type:
Optional[SubnetInfo]
This function is essential for neurons and stakeholders interested in the specifics of a particular subnet, including its governance, performance, and role within the broader network.
- get_subnet_modality(netuid, block=None)#
- get_subnet_owner(netuid, block=None)#
Retrieves the owner’s address of a specific subnet within the Bittensor network. The owner is typically the entity responsible for the creation and maintenance of the subnet.
- Parameters:
- Returns:
The SS58 address of the subnet’s owner, or
None
if not available.- Return type:
Optional[str]
Knowing the subnet owner provides insights into the governance and operational control of the subnet, which can be important for decision-making and collaboration within the network.
- get_subnets(block=None)#
Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers.
- Parameters:
block (Optional[int], optional) – The blockchain block number for the query.
- Returns:
A list of network UIDs representing each active subnet.
- Return type:
List[int]
This function is valuable for understanding the network’s structure and the diversity of subnets available for neuron participation and collaboration.
- get_total_stake_for_coldkey(ss58_address, block=None)#
Returns the total stake held on a coldkey across all hotkeys including delegates
- get_total_stake_for_hotkey(ss58_address, block=None)#
Returns the total stake held on a hotkey including delegative
- get_total_subnets(block=None)#
Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.
- Parameters:
block (Optional[int], optional) – The blockchain block number for the query.
- Returns:
The total number of subnets in the network.
- Return type:
Understanding the total number of subnets is essential for assessing the network’s growth and the extent of its decentralized infrastructure.
- get_transfer_fee(wallet, dest, value)#
Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This function simulates the transfer to estimate the associated cost, taking into account the current network conditions and transaction complexity.
- Parameters:
- Returns:
The estimated transaction fee for the transfer, represented as a Balance object.
- Return type:
Balance
Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the wallet has sufficient funds to cover both the transfer amount and the associated costs. This function provides a crucial tool for managing financial operations within the Bittensor network.
- get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None)#
Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.
- Parameters:
- Returns:
The UID of the neuron if it is registered on the subnet,
None
otherwise.- Return type:
Optional[int]
The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.
- get_vote_data(proposal_hash, block=None)#
Retrieves the voting data for a specific proposal on the Bittensor blockchain. This data includes information about how senate members have voted on the proposal.
- Parameters:
- Returns:
An object containing the proposal’s voting data, or
None
if not found.- Return type:
Optional[ProposalVoteData]
This function is important for tracking and understanding the decision-making processes within the Bittensor network, particularly how proposals are received and acted upon by the governing body.
- classmethod help()#
Print help to stdout
- immunity_period(netuid, block=None)#
Retrieves the ‘ImmunityPeriod’ hyperparameter for a specific subnet. This parameter defines the duration during which new neurons are protected from certain network penalties or restrictions.
- Parameters:
- Returns:
The value of the ‘ImmunityPeriod’ hyperparameter if the subnet exists,
None
otherwise.- Return type:
Optional[int]
The ‘ImmunityPeriod’ is a critical aspect of the network’s governance system, ensuring that new participants have a grace period to establish themselves and contribute to the network without facing immediate punitive actions.
- incentive(netuid, block=None)#
Retrieves the list of incentives for neurons within a specific subnet of the Bittensor network. This function provides insights into the reward distribution mechanisms and the incentives allocated to each neuron based on their contributions and activities.
- Parameters:
- Returns:
The list of incentives for neurons within the subnet, indexed by UID.
- Return type:
List[int]
Understanding the incentive structure is crucial for analyzing the network’s economic model and the motivational drivers for neuron participation and collaboration.
- is_hotkey_delegate(hotkey_ss58, block=None)#
Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if the neuron associated with the hotkey is part of the network’s delegation system.
- Parameters:
- Returns:
True
if the hotkey is a delegate,False
otherwise.- Return type:
Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.
- is_hotkey_registered(hotkey_ss58, netuid=None, block=None)#
Determines whether a given hotkey (public key) is registered in the Bittensor network, either globally across any subnet or specifically on a specified subnet. This function checks the registration status of a neuron identified by its hotkey, which is crucial for validating its participation and activities within the network.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the neuron’s hotkey.
netuid (Optional[int], optional) – The unique identifier of the subnet to check the registration. If
None
, the registration is checked across all subnets.block (Optional[int], optional) – The blockchain block number at which to perform the query.
- Returns:
True
if the hotkey is registered in the specified context (either any subnet or a specific subnet),False
otherwise.- Return type:
This function is important for verifying the active status of neurons in the Bittensor network. It aids in understanding whether a neuron is eligible to participate in network processes such as consensus, validation, and incentive distribution based on its registration status.
- is_hotkey_registered_any(hotkey_ss58, block=None)#
Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on any subnet, False otherwise.- Return type:
This function is essential for determining the network-wide presence and participation of a neuron.
- is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None)#
Checks if a neuron’s hotkey is registered on a specific subnet within the Bittensor network.
- Parameters:
- Returns:
True
if the hotkey is registered on the specified subnet, False otherwise.- Return type:
This function helps in assessing the participation of a neuron in a particular subnet, indicating its specific area of operation or influence within the network.
- is_senate_member(hotkey_ss58, block=None)#
Checks if a given neuron (identified by its hotkey SS58 address) is a member of the Bittensor senate. The senate is a key governance body within the Bittensor network, responsible for overseeing and approving various network operations and proposals.
- Parameters:
- Returns:
True
if the neuron is a senate member at the given block, False otherwise.- Return type:
This function is crucial for understanding the governance dynamics of the Bittensor network and for identifying the neurons that hold decision-making power within the network.
- kappa(netuid, block=None)#
Retrieves the ‘Kappa’ hyperparameter for a specified subnet. ‘Kappa’ is a critical parameter in the Bittensor network that controls the distribution of stake weights among neurons, impacting their rankings and incentive allocations.
- Parameters:
- Returns:
The value of the ‘Kappa’ hyperparameter if the subnet exists, None otherwise.
- Return type:
Optional[float]
- Mathematical Context:
Kappa (κ) is used in the calculation of neuron ranks, which determine their share of network incentives. It is derived from the softmax function applied to the inter-neuronal weights set by each neuron. The formula for Kappa is: κ_i = exp(w_i) / Σ(exp(w_j)), where w_i represents the weight set by neuron i, and the denominator is the sum of exponential weights set by all neurons. This mechanism ensures a normalized and probabilistic distribution of ranks based on relative weights.
Understanding ‘Kappa’ is crucial for analyzing stake dynamics and the consensus mechanism within the network, as it plays a significant role in neuron ranking and incentive allocation processes.
- leave_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron from which the stake is being removed.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey account to unstake from.amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the unstaking process is successful, False otherwise.- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
- max_allowed_validators(netuid, block=None)#
Returns network MaxAllowedValidators hyper parameter
- max_n(netuid, block=None)#
Returns network MaxAllowedUids hyper parameter
- max_weight_limit(netuid, block=None)#
Returns network MaxWeightsLimit hyper parameter
- metagraph(netuid, lite=True, block=None)#
Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the network’s structure, including neuron connections and interactions.
- Parameters:
- Returns:
The metagraph representing the subnet’s structure and neuron relationships.
- Return type:
bittensor.Metagraph
The metagraph is an essential tool for understanding the topology and dynamics of the Bittensor network’s decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes.
- min_allowed_weights(netuid, block=None)#
Returns network MinAllowedWeights hyper parameter
- neuron_for_uid(uid, netuid, block=None)#
Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron’s attributes, including its stake, rank, and operational status.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
Optional[NeuronInfo]
This function is crucial for analyzing individual neurons’ contributions and status within a specific subnet, offering insights into their roles in the network’s consensus and validation mechanisms.
- neuron_for_uid_lite(uid, netuid, block=None)#
Retrieves a lightweight version of information about a neuron in a specific subnet, identified by its UID. The ‘lite’ version focuses on essential attributes such as stake and network activity.
- Parameters:
- Returns:
A simplified version of neuron information if found,
None
otherwise.- Return type:
Optional[NeuronInfoLite]
This function is useful for quick and efficient analyses of neuron status and activities within a subnet without the need for comprehensive data retrieval.
- neuron_for_wallet(wallet, netuid, block=None)#
Retrieves information about a neuron associated with a given wallet on a specific subnet. This function provides detailed data about the neuron’s status, stake, and activities based on the wallet’s hotkey address.
- Parameters:
- Returns:
Detailed information about the neuron if found,
None
otherwise.- Return type:
Optional[NeuronInfo]
This function is important for wallet owners to understand and manage their neuron’s presence and activities within a particular subnet of the Bittensor network.
- neuron_has_validator_permit(uid, netuid, block=None)#
Checks if a neuron, identified by its unique identifier (UID), has a validator permit on a specific subnet within the Bittensor network. This function determines whether the neuron is authorized to participate in validation processes on the subnet.
- Parameters:
- Returns:
True
if the neuron has a validator permit, False otherwise.- Return type:
Optional[bool]
This function is essential for understanding a neuron’s role and capabilities within a specific subnet, particularly regarding its involvement in network validation and governance.
- neurons(netuid, block=None)#
Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet’s neuron population, including each neuron’s attributes and network interactions.
- Parameters:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
List[NeuronInfo]
Understanding the distribution and status of neurons within a subnet is key to comprehending the network’s decentralized structure and the dynamics of its consensus and governance processes.
- neurons_lite(netuid, block=None)#
Retrieves a list of neurons in a ‘lite’ format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network participation.
- Parameters:
- Returns:
A list of simplified neuron information for the subnet.
- Return type:
List[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.
- nominate(wallet, wait_for_finalization=False, wait_for_inclusion=True)#
Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.
- Parameters:
- Returns:
True
if the nomination process is successful,False
otherwise.- Return type:
This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.
- query_constant(module_name, constant_name, block=None)#
Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.
- Parameters:
- Returns:
The value of the constant if found,
None
otherwise.- Return type:
Optional[object]
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_identity(key, block=None)#
Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves detailed identity information about a specific neuron, which is a crucial aspect of the network’s decentralized identity and governance system.
Note
See the Bittensor CLI documentation for supported identity parameters.
- Parameters:
- Returns:
An object containing the identity information of the neuron if found,
None
otherwise.- Return type:
Optional[object]
The identity information can include various attributes such as the neuron’s stake, rank, and other network-specific details, providing insights into the neuron’s role and status within the Bittensor network.
- query_map(module, name, block=None, params=[])#
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], optional) – The blockchain block number at which to perform the query.
params (Optional[List[object]], optional) – Parameters to be passed to the query.
- Returns:
A data structure representing the map storage if found,
None
otherwise.- Return type:
Optional[object]
This function is particularly useful for retrieving detailed and structured data from various blockchain modules, offering insights into the network’s state and the relationships between its different components.
- query_map_subtensor(name, block=None, params=[])#
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
This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as inter-neuronal connections and stake distributions.
- query_module(module, name, block=None, params=[])#
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:
module (str) – The name of the module from which to query data.
name (str) – The name of the storage function within the module.
block (Optional[int], optional) – The blockchain block number at which to perform the query.
params (Optional[List[object]], optional) – A list of parameters to pass to the query function.
- Returns:
An object containing the requested data if found,
None
otherwise.- Return type:
Optional[object]
This versatile query function is key to accessing a wide range of data and insights from different parts of the Bittensor blockchain, enhancing the understanding and analysis of the network’s state and dynamics.
- query_runtime_api(runtime_api, method, params, block=None)#
Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to interact with specific runtime methods and decode complex data types.
- Parameters:
runtime_api (str) – The name of the runtime API to query.
method (str) – The specific method within the runtime API to call.
params (Optional[List[ParamWithTypes]], optional) – The parameters to pass to the method call.
block (Optional[int], optional) – 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[bytes]
This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network’s runtime environment.
- query_subtensor(name, block=None, params=[])#
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 if found,
None
otherwise.- Return type:
Optional[object]
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.
- register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, prompt=False, max_allowed_attempts=3, output_in_place=True, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False)#
Registers a neuron on the Bittensor network using the provided wallet. Registration is a critical step for a neuron to become an active participant in the network, enabling it to stake, set weights, and receive incentives.
- Parameters:
wallet (bittensor.wallet) – 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.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
arguments (Other) – Various optional parameters to customize the registration process.
prompt (bool) –
max_allowed_attempts (int) –
output_in_place (bool) –
cuda (bool) –
tpb (int) –
num_processes (Optional[int]) –
update_interval (Optional[int]) –
log_verbose (bool) –
- 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.
- register_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron from which the stake is being removed.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey account to unstake from.amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the unstaking process is successful, False otherwise.- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
- register_subnetwork(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
Registers a new subnetwork on the Bittensor network using the provided wallet. This function is used for the creation and registration of subnetworks, which are specialized segments of the overall Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet to be used for registration.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the subnetwork registration is successful, False otherwise.- Return type:
This function allows for the expansion and diversification of the Bittensor network, supporting its decentralized and adaptable architecture.
- rho(netuid, block=None)#
Retrieves the ‘Rho’ hyperparameter for a specified subnet within the Bittensor network. ‘Rho’ represents the global inflation rate, which directly influences the network’s token emission rate and economic model.
Note
This is currently fixed such that the Bittensor blockchain emmits 7200 Tao per day.
- Parameters:
- Returns:
The value of the ‘Rho’ hyperparameter if the subnet exists,
None
otherwise.- Return type:
Optional[int]
- Mathematical Context:
Rho (p) is calculated based on the network’s target inflation and actual neuron staking. It adjusts the emission rate of the TAO token to balance the network’s economy and dynamics. The formula for Rho is defined as: p = (Staking_Target / Staking_Actual) * Inflation_Target. Here, Staking_Target and Staking_Actual represent the desired and actual total stakes in the network, while Inflation_Target is the predefined inflation rate goal.
‘Rho’ is essential for understanding the network’s economic dynamics, affecting the reward distribution and incentive structures across the network’s neurons.
- root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
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, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the registration on the root network is successful, False otherwise.- Return type:
This function enables neurons to engage in the most critical and influential aspects of the network’s governance, signifying a high level of commitment and responsibility in the Bittensor ecosystem.
- root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=False, wait_for_finalization=False, prompt=False)#
Sets the weights for neurons on the root network. This action is crucial for defining the influence and interactions of neurons at the root level of the Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.
netuids (Union[torch.LongTensor, list]) – The list of neuron UIDs for which weights are being set.
weights (Union[torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int, optional) – Version key for compatibility with the network.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- 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.
- run_faucet(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False, max_allowed_attempts=3, output_in_place=True, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False)#
Facilitates a faucet transaction, allowing new neurons to receive an initial amount of TAO for participating in the network. This function is particularly useful for newcomers to the Bittensor network, enabling them to start with a small stake on testnet only.
- Parameters:
wallet (bittensor.wallet) – The wallet for which the faucet transaction is to be run.
arguments (Other) – Various optional parameters to customize the faucet transaction process.
wait_for_inclusion (bool) –
wait_for_finalization (bool) –
prompt (bool) –
max_allowed_attempts (int) –
output_in_place (bool) –
cuda (bool) –
tpb (int) –
num_processes (Optional[int]) –
update_interval (Optional[int]) –
log_verbose (bool) –
- Returns:
True
if the faucet transaction is successful, False otherwise.- Return type:
This function is part of Bittensor’s onboarding process, ensuring that new neurons have the necessary resources to begin their journey in the decentralized AI network.
Note
This is for testnet ONLY and is disabled currently. You must build your own staging subtensor chain with the
--features pow-faucet
argument to enable this.
- scaling_law_power(netuid, block=None)#
Returns network ScalingLawPower hyper parameter
- serve(wallet, ip, port, protocol, netuid, placeholder1=0, placeholder2=0, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
Registers a neuron’s serving endpoint on the Bittensor network. This function announces the IP address and port where the neuron is available to serve requests, facilitating peer-to-peer communication within the network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron being served.
ip (str) – The IP address of the serving neuron.
port (int) – The port number on which the neuron is serving.
protocol (int) – The protocol type used by the neuron (e.g., GRPC, HTTP).
netuid (int) – The unique identifier of the subnetwork.
arguments (Other) – Placeholder parameters for future extensions.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.placeholder1 (int) –
placeholder2 (int) –
- Returns:
True
if the serve registration is successful, False otherwise.- Return type:
This function is essential for establishing the neuron’s presence in the network, enabling it to participate in the decentralized machine learning processes of Bittensor.
- serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
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.Axon) – The Axon instance to be registered for serving.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- 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.
- serve_prometheus(wallet, port, netuid, wait_for_inclusion=False, wait_for_finalization=True)#
- serving_rate_limit(netuid, block=None)#
Retrieves the serving rate limit for a specific subnet within the Bittensor network. This rate limit determines the maximum number of requests a neuron can serve within a given time frame.
- Parameters:
- Returns:
The serving rate limit of the subnet if it exists,
None
otherwise.- Return type:
Optional[int]
The serving rate limit is a crucial parameter for maintaining network efficiency and preventing overuse of resources by individual neurons. It helps ensure a balanced distribution of service requests across the network.
- set_hyperparameter(wallet, netuid, parameter, value, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
Sets a specific hyperparameter for a given subnetwork on the Bittensor blockchain. This action involves adjusting network-level parameters, influencing the behavior and characteristics of the subnetwork.
- Parameters:
wallet (bittensor.wallet) – The wallet used for setting the hyperparameter.
netuid (int) – The unique identifier of the subnetwork.
parameter (str) – The name of the hyperparameter to be set.
value – The new value for the hyperparameter.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the hyperparameter setting is successful, False otherwise.- Return type:
This function plays a critical role in the dynamic governance and adaptability of the Bittensor network, allowing for fine-tuning of network operations and characteristics.
- set_weights(wallet, netuid, uids, weights, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False)#
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) – The wallet associated with the neuron setting the weights.
netuid (int) – The unique identifier of the subnet.
uids (Union[torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.
weights (Union[torch.FloatTensor, list]) – The corresponding weights to be set for each UID.
version_key (int, optional) – Version key for compatibility with the network.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the setting of weights is successful, False otherwise.- Return type:
This function is crucial in shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.
- static setup_config(network, config)#
- Parameters:
network (str) –
config (bittensor.config) –
- state_call(method, data, block=None)#
Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain’s state. This function is typically used for advanced queries that require specific method calls and data inputs.
- Parameters:
- Returns:
The result of the state call if successful,
None
otherwise.- Return type:
Optional[object]
The state call function provides a more direct and flexible way of querying blockchain data, useful for specific use cases where standard queries are insufficient.
- subnet_exists(netuid, block=None)#
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
- Parameters:
- Returns:
True
if the subnet exists, False otherwise.- Return type:
This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network’s structure and composition.
- subnetwork_n(netuid, block=None)#
Returns network SubnetworkN hyper parameter
- swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#
Swaps an old hotkey to a new hotkey.
- synergy_scaling_law_power(netuid, block=None)#
Returns network SynergyScalingLawPower hyper parameter
- tempo(netuid, block=None)#
Returns network Tempo hyper parameter
- total_issuance(block=None)#
Retrieves the total issuance of the Bittensor network’s native token (Tao) as of a specific blockchain block. This represents the total amount of currency that has been issued or mined on the network.
- Parameters:
block (Optional[int], optional) – The blockchain block number at which to perform the query.
- Returns:
The total issuance of TAO, represented as a Balance object.
- Return type:
Balance
The total issuance is a key economic indicator in the Bittensor network, reflecting the overall supply of the currency and providing insights into the network’s economic health and inflationary trends.
- total_stake(block=None)#
Retrieves the total amount of TAO staked on the Bittensor network as of a specific blockchain block. This represents the cumulative stake across all neurons in the network, indicating the overall level of participation and investment by the network’s participants.
- Parameters:
block (Optional[int], optional) – The blockchain block number at which to perform the query.
- Returns:
The total amount of TAO staked on the network, represented as a Balance object.
- Return type:
Balance
The total stake is an important metric for understanding the network’s security, governance dynamics, and the level of commitment by its participants. It is also a critical factor in the network’s consensus and incentive mechanisms.
- transfer(wallet, dest, amount, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Executes a transfer of funds from the provided wallet to the specified destination address. This function is used to move TAO tokens within the Bittensor network, facilitating transactions between neurons.
- Parameters:
wallet (bittensor.wallet) – The wallet from which funds are being transferred.
dest (str) – The destination public key address.
amount (Union[Balance, float]) – The amount of TAO to be transferred.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the transfer is successful, False otherwise.- Return type:
This function is essential for the fluid movement of tokens in the network, supporting various economic activities such as staking, delegation, and reward distribution.
- tx_rate_limit(block=None)#
Retrieves the transaction rate limit for the Bittensor network as of a specific blockchain block. This rate limit sets the maximum number of transactions that can be processed within a given time frame.
- Parameters:
block (Optional[int], optional) – The blockchain block number at which to perform the query.
- Returns:
The transaction rate limit of the network, None if not available.
- Return type:
Optional[int]
The transaction rate limit is an essential parameter for ensuring the stability and scalability of the Bittensor network. It helps in managing network load and preventing congestion, thereby maintaining efficient and timely transaction processing.
- undelegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Removes a specified amount of stake from a delegate neuron using the provided wallet. This action reduces the staked amount on another neuron, effectively withdrawing support or speculation.
- Parameters:
wallet (bittensor.wallet) – The wallet used for the undelegation process.
delegate_ss58 (Optional[str]) – The
SS58
address of the delegate neuron.amount (Union[Balance, float]) – The amount of TAO to undelegate.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the undelegation is successful, False otherwise.- Return type:
This function reflects the dynamic and speculative nature of the Bittensor network, allowing neurons to adjust their stakes and investments based on changing perceptions and performances within the network.
- unstake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron from which the stake is being removed.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey account to unstake from.amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the unstaking process is successful, False otherwise.- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
- unstake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts efficiently. This function is useful for managing the distribution of stakes across multiple neurons.
- Parameters:
wallet (bittensor.wallet) – The wallet linked to the coldkey from which the stakes are being withdrawn.
hotkey_ss58s (List[str]) – A list of hotkey
SS58
addresses to unstake from.amounts (List[Union[Balance, float]], optional) – The amounts of TAO to unstake from each hotkey. If not provided, unstakes all available stakes.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.
- Returns:
True
if the batch unstaking is successful, False otherwise.- Return type:
This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake management aspect of the Bittensor network.
- update_identity(wallet, identified=None, params={}, wait_for_inclusion=True, wait_for_finalization=False)#
Updates the identity of a neuron on the Bittensor blockchain. This function allows neurons to modify their identity attributes, reflecting changes in their roles, stakes, or other network-specific parameters.
Note
See the Bittensor CLI documentation for supported identity parameters.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron whose identity is being updated.
identified (str, optional) – The identified
SS58
address of the neuron. Defaults to the wallet’s coldkey address.params (dict, optional) – A dictionary of parameters to update in the neuron’s identity.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
- Returns:
True
if the identity update is successful, False otherwise.- Return type:
This function plays a vital role in maintaining the accuracy and currency of neuron identities in the Bittensor network, ensuring that the network’s governance and consensus mechanisms operate effectively.
- validator_batch_size(netuid, block=None)#
Returns network ValidatorBatchSize hyper parameter
- validator_epoch_length(netuid, block=None)#
Returns network ValidatorEpochLen hyper parameter
- validator_epochs_per_reset(netuid, block=None)#
Returns network ValidatorEpochsPerReset hyper parameter
- validator_exclude_quantile(netuid, block=None)#
Returns network ValidatorEpochLen hyper parameter
- validator_logits_divergence(netuid, block=None)#
Returns network ValidatorLogitsDivergence hyper parameter
- validator_prune_len(netuid, block=None)#
Returns network ValidatorPruneLen hyper parameter
- validator_sequence_length(netuid, block=None)#
Returns network ValidatorSequenceLength hyper parameter
- vote_senate(wallet, proposal_hash, proposal_idx, vote, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor.wallet) – The wallet associated with the neuron from which the stake is being removed.
hotkey_ss58 (Optional[str]) – The
SS58
address of the hotkey account to unstake from.amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.
wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional) – Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional) – If
True
, prompts for user confirmation before proceeding.proposal_hash (str) –
proposal_idx (int) –
vote (bool) –
- Returns:
True
if the unstaking process is successful, False otherwise.- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
- weights(netuid, block=None)#
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron’s UID to the weights it assigns to other neurons, reflecting the network’s trust and value assignment mechanisms.
- Parameters:
- Returns:
A list of tuples mapping each neuron’s UID to its assigned weights.
- Return type:
The weight distribution is a key factor in the network’s consensus algorithm and the ranking of neurons, influencing their influence and reward allocation within the subnet.
- class bittensor.tensor#
- bittensor.turn_console_off()#
- bittensor.turn_console_on()#
- bittensor.validate_password(password)#
Validates the password against a password policy.
- bittensor.version_split#
- class bittensor.wallet(name=None, hotkey=None, path=None, config=None)#
The wallet class in the Bittensor framework handles wallet functionality, crucial for participating in the Bittensor network.
It manages two types of keys: coldkey and hotkey, each serving different purposes in network operations. Each wallet contains a coldkey and a hotkey.
The coldkey is the user’s primary key for holding stake in their wallet and is the only way that users can access Tao. Coldkeys can hold tokens and should be encrypted on your device.
The coldkey is the primary key used for securing the wallet’s stake in the Bittensor network (Tao) and is critical for financial transactions like staking and unstaking tokens. It’s recommended to keep the coldkey encrypted and secure, as it holds the actual tokens.
The hotkey, in contrast, is used for operational tasks like subscribing to and setting weights in the network. It’s linked to the coldkey through the metagraph and does not directly hold tokens, thereby offering a safer way to interact with the network during regular operations.
- Parameters:
name (str) – The name of the wallet, used to identify it among possibly multiple wallets.
path (str) – File system path where wallet keys are stored.
hotkey_str (str) – String identifier for the hotkey.
_hotkey (bittensor.Keypair) – Internal representations of the hotkey and coldkey.
_coldkey (bittensor.Keypair) – Internal representations of the hotkey and coldkey.
_coldkeypub (bittensor.Keypair) – Internal representations of the hotkey and coldkey.
hotkey (str) –
config (bittensor.config) –
- create_if_non_existent, create, recreate
Methods to handle the creation of wallet keys.
- get_coldkey, get_hotkey, get_coldkeypub
Methods to retrieve specific keys.
- set_coldkey, set_hotkey, set_coldkeypub
Methods to set or update keys.
- hotkey_file, coldkey_file, coldkeypub_file
Properties that return respective key file objects.
- regenerate_coldkey, regenerate_hotkey, regenerate_coldkeypub
Methods to regenerate keys from different sources.
- config, help, add_args
Utility methods for configuration and assistance.
The wallet class is a fundamental component for users to interact securely with the Bittensor network, facilitating both operational tasks and transactions involving value transfer across the network.
Example Usage:
# Create a new wallet with default coldkey and hotkey names my_wallet = wallet() # Access hotkey and coldkey hotkey = my_wallet.get_hotkey() coldkey = my_wallet.get_coldkey() # Set a new coldkey my_wallet.new_coldkey(n_words=24) # number of seed words to use # Update wallet hotkey my_wallet.set_hotkey(new_hotkey) # Print wallet details print(my_wallet) # Access coldkey property, must use password to unlock my_wallet.coldkey
- property coldkey: bittensor.Keypair#
Loads the hotkey from wallet.path/wallet.name/coldkey or raises an error.
- Returns:
coldkey loaded from config arguments.
- Return type:
coldkey (Keypair)
- Raises:
KeyFileError – Raised if the file is corrupt of non-existent.
CryptoKeyError – Raised if the user enters an incorrec password for an encrypted keyfile.
- property coldkey_file: bittensor.keyfile#
Property that returns the coldkey file.
- Returns:
The coldkey file.
- Return type:
bittensor.keyfile
- property coldkeypub: bittensor.Keypair#
Loads the coldkeypub from wallet.path/wallet.name/coldkeypub.txt or raises an error.
- Returns:
coldkeypub loaded from config arguments.
- Return type:
coldkeypub (Keypair)
- Raises:
KeyFileError – Raised if the file is corrupt of non-existent.
CryptoKeyError – Raised if the user enters an incorrect password for an encrypted keyfile.
- property coldkeypub_file: bittensor.keyfile#
Property that returns the coldkeypub file.
- Returns:
The coldkeypub file.
- Return type:
bittensor.keyfile
- property hotkey: bittensor.Keypair#
Loads the hotkey from wallet.path/wallet.name/hotkeys/wallet.hotkey or raises an error.
- Returns:
hotkey loaded from config arguments.
- Return type:
hotkey (Keypair)
- Raises:
KeyFileError – Raised if the file is corrupt of non-existent.
CryptoKeyError – Raised if the user enters an incorrec password for an encrypted keyfile.
- property hotkey_file: bittensor.keyfile#
Property that returns the hotkey file.
- Returns:
The hotkey file.
- Return type:
bittensor.keyfile
- regen_coldkey#
- regen_coldkeypub#
- regen_hotkey#
- __repr__()#
Returns the string representation of the wallet object.
- Returns:
The string representation.
- Return type:
- __str__()#
Returns the string representation of the Wallet object.
- Returns:
The string representation.
- Return type:
- classmethod add_args(parser, prefix=None)#
Accept specific arguments from parser.
- Parameters:
parser (argparse.ArgumentParser) – Argument parser object.
prefix (str) – Argument prefix.
- classmethod config()#
Get config from the argument parser.
- Returns:
Config object.
- Return type:
- create(coldkey_use_password=True, hotkey_use_password=False)#
Checks for existing coldkeypub and hotkeys, and creates them if non-existent.
- create_coldkey_from_uri(uri, use_password=True, overwrite=False, suppress=False)#
Creates coldkey from suri string, optionally encrypts it with the user-provided password.
- Parameters:
- Returns:
This object with newly created coldkey.
- Return type:
wallet (bittensor.wallet)
- create_hotkey_from_uri(uri, use_password=False, overwrite=False, suppress=False)#
Creates hotkey from suri string, optionally encrypts it with the user-provided password.
- Parameters:
uri (str) – (str, required): URI string to use i.e.,
/Alice
or/Bob
use_password (bool, optional) – Is the created key password protected.
overwrite (bool, optional) – Determines if this operation overwrites the hotkey under the same path
<wallet path>/<wallet name>/hotkeys/<hotkey>
.suppress (bool) –
- Returns:
This object with newly created hotkey.
- Return type:
wallet (bittensor.wallet)
- create_if_non_existent(coldkey_use_password=True, hotkey_use_password=False)#
Checks for existing coldkeypub and hotkeys, and creates them if non-existent.
- create_new_coldkey(n_words=12, use_password=True, overwrite=False, suppress=False)#
Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.
- Parameters:
- Returns:
This object with newly created coldkey.
- Return type:
wallet (bittensor.wallet)
- create_new_hotkey(n_words=12, use_password=False, overwrite=False, suppress=False)#
Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.
- Parameters:
- Returns:
This object with newly created hotkey.
- Return type:
wallet (bittensor.wallet)
- get_coldkey(password=None)#
Gets the coldkey from the wallet.
- Parameters:
password (str, optional) – The password to decrypt the coldkey. Defaults to
None
.- Returns:
The coldkey keypair.
- Return type:
bittensor.Keypair
- get_coldkeypub(password=None)#
Gets the coldkeypub from the wallet.
- Parameters:
password (str, optional) – The password to decrypt the coldkeypub. Defaults to
None
.- Returns:
The coldkeypub keypair.
- Return type:
bittensor.Keypair
- get_hotkey(password=None)#
Gets the hotkey from the wallet.
- Parameters:
password (str, optional) – The password to decrypt the hotkey. Defaults to
None
.- Returns:
The hotkey keypair.
- Return type:
bittensor.Keypair
- classmethod help()#
Print help to stdout.
- new_coldkey(n_words=12, use_password=True, overwrite=False, suppress=False)#
Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.
- Parameters:
- Returns:
This object with newly created coldkey.
- Return type:
wallet (bittensor.wallet)
- new_hotkey(n_words=12, use_password=False, overwrite=False, suppress=False)#
Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.
- Parameters:
n_words (int) – (int, optional): Number of mnemonic words to use.
use_password (bool, optional) – Is the created key password protected.
overwrite (bool, optional) – Determines if this operation overwrites the hotkey under the same path
<wallet path>/<wallet name>/hotkeys/<hotkey>
.suppress (bool) –
- Returns:
This object with newly created hotkey.
- Return type:
wallet (bittensor.wallet)
- recreate(coldkey_use_password=True, hotkey_use_password=False)#
Checks for existing coldkeypub and hotkeys and creates them if non-existent.
- regenerate_coldkey(mnemonic: list | str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet #
- regenerate_coldkey(seed: str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
- regenerate_coldkey(json: Tuple[str | Dict, str] | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
Regenerates the coldkey from the passed mnemonic or seed, or JSON encrypts it with the user’s password and saves the file.
- Parameters:
mnemonic – (Union[list, str], optional): Key mnemonic as list of words or string space separated words.
seed – (str, optional): Seed as hex string.
json – (Tuple[Union[str, Dict], str], optional): Restore from encrypted JSON backup as
(json_data: Union[str, Dict], passphrase: str)
use_password (bool, optional) – Is the created key password protected.
overwrite (bool, optional) – Determines if this operation overwrites the coldkey under the same path
<wallet path>/<wallet name>/coldkey
.
- Returns:
This object with newly created coldkey.
- Return type:
wallet (bittensor.wallet)
Note
Uses priority order:
mnemonic > seed > json
.
- regenerate_coldkeypub(ss58_address=None, public_key=None, overwrite=False, suppress=False)#
Regenerates the coldkeypub from the passed
ss58_address
or public_key and saves the file. Requires eitherss58_address
or public_key to be passed.- Parameters:
ss58_address (Optional[str]) – (str, optional): Address as
ss58
string.public_key (Optional[Union[str, bytes]]) – (str | bytes, optional): Public key as hex string or bytes.
overwrite (bool, optional) – False): Determins if this operation overwrites the coldkeypub (if exists) under the same path
<wallet path>/<wallet name>/coldkeypub
.suppress (bool) –
- Returns:
Newly re-generated wallet with coldkeypub.
- Return type:
wallet (bittensor.wallet)
- regenerate_hotkey(mnemonic: list | str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet #
- regenerate_hotkey(seed: str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
- regenerate_hotkey(json: Tuple[str | Dict, str] | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
Regenerates the hotkey from passed mnemonic or seed, encrypts it with the user’s password and saves the file.
- Parameters:
mnemonic – (Union[list, str], optional): Key mnemonic as list of words or string space separated words.
seed – (str, optional): Seed as hex string.
json – (Tuple[Union[str, Dict], str], optional): Restore from encrypted JSON backup as
(json_data: Union[str, Dict], passphrase: str)
.use_password (bool, optional) – Is the created key password protected.
overwrite (bool, optional) – Determies if this operation overwrites the hotkey under the same path
<wallet path>/<wallet name>/hotkeys/<hotkey>
.
- Returns:
This object with newly created hotkey.
- Return type:
wallet (bittensor.wallet)
- set_coldkey(keypair, encrypt=True, overwrite=False)#
Sets the coldkey for the wallet.
- set_coldkeypub(keypair, encrypt=False, overwrite=False)#
Sets the coldkeypub for the wallet.
- Parameters:
- Returns:
The coldkeypub file.
- Return type:
bittensor.keyfile
- set_hotkey(keypair, encrypt=False, overwrite=False)#
Sets the hotkey for the wallet.