-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathsubtensor.py
4479 lines (3831 loc) · 190 KB
/
subtensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# Copyright © 2023 Opentensor Foundation
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import os
import copy
import socket
import time
import torch
import argparse
import bittensor
import scalecodec
from retry import retry
from loguru import logger
from typing import List, Dict, Union, Optional, Tuple, TypedDict, Any, TypeVar
from substrateinterface.base import QueryMapResult, SubstrateInterface, ExtrinsicReceipt
from substrateinterface.exceptions import SubstrateRequestException
from scalecodec.base import RuntimeConfiguration
from scalecodec.type_registry import load_type_registry_preset
from scalecodec.types import GenericCall
# Local imports.
from .chain_data import (
NeuronInfo,
DelegateInfo,
PrometheusInfo,
SubnetInfo,
SubnetHyperparameters,
StakeInfo,
NeuronInfoLite,
AxonInfo,
ProposalVoteData,
IPInfo,
custom_rpc_type_registry,
)
from .errors import *
from .extrinsics.network import (
register_subnetwork_extrinsic,
set_hyperparameter_extrinsic,
)
from .extrinsics.staking import add_stake_extrinsic, add_stake_multiple_extrinsic
from .extrinsics.unstaking import unstake_extrinsic, unstake_multiple_extrinsic
from .extrinsics.serving import (
serve_extrinsic,
serve_axon_extrinsic,
publish_metadata,
get_metadata,
)
from .extrinsics.registration import (
register_extrinsic,
burned_register_extrinsic,
run_faucet_extrinsic,
swap_hotkey_extrinsic,
)
from .extrinsics.transfer import transfer_extrinsic
from .extrinsics.set_weights import set_weights_extrinsic
from .extrinsics.prometheus import prometheus_extrinsic
from .extrinsics.delegation import (
delegate_extrinsic,
nominate_extrinsic,
undelegate_extrinsic,
)
from .extrinsics.senate import (
register_senate_extrinsic,
leave_senate_extrinsic,
vote_senate_extrinsic,
)
from .extrinsics.root import root_register_extrinsic, set_root_weights_extrinsic
from .types import AxonServeCallParams, PrometheusServeCallParams
from .utils import U16_NORMALIZED_FLOAT, ss58_to_vec_u8, U64_NORMALIZED_FLOAT
from .utils.balance import Balance
from .utils.registration import POWSolution
logger = logger.opt(colors=True)
KEY_NONCE: Dict[str, int] = {}
T = TypeVar("T")
class ParamWithTypes(TypedDict):
name: str # Name of the parameter.
type: str # ScaleType string of the parameter.
class subtensor:
"""
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.
Args:
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.
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 <https://bittensor.com/pdfs/academia/NeurIPS_DAO_Workshop_2022_3_3.pdf>`_. paper.
"""
@staticmethod
def config() -> "bittensor.config":
parser = argparse.ArgumentParser()
subtensor.add_args(parser)
return bittensor.config(parser, args=[])
@classmethod
def help(cls):
"""Print help to stdout"""
parser = argparse.ArgumentParser()
cls.add_args(parser)
print(cls.__new__.__doc__)
parser.print_help()
@classmethod
def add_args(cls, parser: argparse.ArgumentParser, prefix: Optional[str] = None):
prefix_str = "" if prefix is None else f"{prefix}."
try:
default_network = os.getenv("BT_SUBTENSOR_NETWORK") or "finney"
default_chain_endpoint = (
os.getenv("BT_SUBTENSOR_CHAIN_ENDPOINT")
or bittensor.__finney_entrypoint__
)
parser.add_argument(
"--" + prefix_str + "subtensor.network",
default=default_network,
type=str,
help="""The subtensor network flag. The likely choices are:
-- finney (main network)
-- test (test network)
-- archive (archive network +300 blocks)
-- local (local running network)
If this option is set it overloads subtensor.chain_endpoint with
an entry point node from that network.
""",
)
parser.add_argument(
"--" + prefix_str + "subtensor.chain_endpoint",
default=default_chain_endpoint,
type=str,
help="""The subtensor endpoint flag. If set, overrides the --network flag.
""",
)
parser.add_argument(
"--" + prefix_str + "subtensor._mock",
default=False,
type=bool,
help="""If true, uses a mocked connection to the chain.
""",
)
except argparse.ArgumentError:
# re-parsing arguments.
pass
@staticmethod
def determine_chain_endpoint_and_network(network: str):
"""Determines the chain endpoint and network from the passed network or chain_endpoint.
Args:
network (str): The network flag. The choices are: ``-- finney`` (main network), ``-- archive`` (archive network +300 blocks), ``-- local`` (local running network), ``-- test`` (test network).
chain_endpoint (str): The chain endpoint flag. If set, overrides the network argument.
Returns:
network (str): The network flag.
chain_endpoint (str): The chain endpoint flag. If set, overrides the ``network`` argument.
"""
if network is None:
return None, None
if network in ["finney", "local", "test", "archive"]:
if network == "finney":
# Kiru Finney stagin network.
return network, bittensor.__finney_entrypoint__
elif network == "local":
return network, bittensor.__local_entrypoint__
elif network == "test":
return network, bittensor.__finney_test_entrypoint__
elif network == "archive":
return network, bittensor.__archive_entrypoint__
else:
if (
network == bittensor.__finney_entrypoint__
or "entrypoint-finney.opentensor.ai" in network
):
return "finney", bittensor.__finney_entrypoint__
elif (
network == bittensor.__finney_test_entrypoint__
or "test.finney.opentensor.ai" in network
):
return "test", bittensor.__finney_test_entrypoint__
elif (
network == bittensor.__archive_entrypoint__
or "archive.chain.opentensor.ai" in network
):
return "archive", bittensor.__archive_entrypoint__
elif "127.0.0.1" in network or "localhost" in network:
return "local", network
else:
return "unknown", network
@staticmethod
def setup_config(network: str, config: bittensor.config):
if network != None:
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(network)
else:
if config.get("__is_set", {}).get("subtensor.chain_endpoint"):
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(
config.subtensor.chain_endpoint
)
elif config.get("__is_set", {}).get("subtensor.network"):
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(
config.subtensor.network
)
elif config.subtensor.get("chain_endpoint"):
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(
config.subtensor.chain_endpoint
)
elif config.subtensor.get("network"):
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(
config.subtensor.network
)
else:
(
evaluated_network,
evaluated_endpoint,
) = subtensor.determine_chain_endpoint_and_network(
bittensor.defaults.subtensor.network
)
return (
bittensor.utils.networking.get_formatted_ws_endpoint_url(
evaluated_endpoint
),
evaluated_network,
)
def __init__(
self,
network: Optional[str] = None,
config: Optional[bittensor.config] = None,
_mock: bool = False,
log_verbose: bool = True,
) -> None:
"""
Initializes a Subtensor interface for interacting with the Bittensor blockchain.
NOTE:
Currently subtensor defaults to the ``finney`` network. This will change in a future release.
We strongly encourage users to run their own local subtensor node whenever possible. This increases
decentralization and resilience of the network. In a future release, local subtensor will become the
default and the fallback to ``finney`` removed. Please plan ahead for this change. We will provide detailed
instructions on how to run a local subtensor node in the documentation in a subsequent release.
Args:
network (str, optional): The network name to connect to (e.g., ``finney``, ``local``). This can also be the chain endpoint (e.g., ``wss://entrypoint-finney.opentensor.ai:443``) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.
config (bittensor.config, optional): Configuration object for the subtensor. If not provided, a default configuration is used.
_mock (bool, optional): If set to ``True``, uses a mocked connection for testing purposes.
This initialization sets up the connection to the specified Bittensor network, allowing for various
blockchain operations such as neuron registration, stake management, and setting weights.
"""
# Determine config.subtensor.chain_endpoint and config.subtensor.network config.
# If chain_endpoint is set, we override the network flag, otherwise, the chain_endpoint is assigned by the network.
# Argument importance: network > chain_endpoint > config.subtensor.chain_endpoint > config.subtensor.network
# Check if network is a config object. (Single argument passed as first positional)
if isinstance(network, bittensor.config):
if network.subtensor is None:
bittensor.logging.warning(
"If passing a bittensor config object, it must not be empty. Using default subtensor config."
)
config = None
else:
config = network
network = None
if config is None:
config = subtensor.config()
self.config = copy.deepcopy(config) # type: ignore
# Setup config.subtensor.network and config.subtensor.chain_endpoint
self.chain_endpoint, self.network = subtensor.setup_config(network, config) # type: ignore
if (
self.network == "finney"
or self.chain_endpoint == bittensor.__finney_entrypoint__
) and log_verbose:
bittensor.logging.info(
f"You are connecting to {self.network} network with endpoint {self.chain_endpoint}."
)
bittensor.logging.warning(
"We strongly encourage running a local subtensor node whenever possible. "
"This increases decentralization and resilience of the network."
)
bittensor.logging.warning(
"In a future release, local subtensor will become the default endpoint. "
"To get ahead of this change, please run a local subtensor node and point to it."
)
# Returns a mocked connection with a background chain connection.
self.config.subtensor._mock = (
_mock
if _mock != None
else self.config.subtensor.get("_mock", bittensor.defaults.subtensor._mock)
)
if (
self.config.subtensor._mock
): # TODO: review this doesn't appear to be used anywhere.
config.subtensor._mock = True
return bittensor.MockSubtensor() # type: ignore
# Attempt to connect to chosen endpoint. Fallback to finney if local unavailable.
try:
# Set up params.
self.substrate = SubstrateInterface(
ss58_format=bittensor.__ss58_format__,
use_remote_preset=True,
url=self.chain_endpoint,
type_registry=bittensor.__type_registry__,
)
except ConnectionRefusedError as e:
bittensor.logging.error(
f"Could not connect to {self.network} network with {self.chain_endpoint} chain endpoint. Exiting..."
)
bittensor.logging.info(
f"You can check if you have connectivity by runing this command: nc -vz localhost {self.chain_endpoint.split(':')[2]}"
)
exit(1)
# TODO (edu/phil): Advise to run local subtensor and point to dev docs.
try:
self.substrate.websocket.settimeout(600)
except:
bittensor.logging.warning("Could not set websocket timeout.")
if log_verbose:
bittensor.logging.info(
f"Connected to {self.network} network and {self.chain_endpoint}."
)
def __str__(self) -> str:
if self.network == self.chain_endpoint:
# Connecting to chain endpoint without network known.
return "subtensor({})".format(self.chain_endpoint)
else:
# Connecting to network with endpoint known.
return "subtensor({}, {})".format(self.network, self.chain_endpoint)
def __repr__(self) -> str:
return self.__str__()
####################
#### SubstrateInterface related
####################
def connect_websocket(self):
"""
(Re)creates the websocket connection, if the URL contains a 'ws' or 'wss' scheme
"""
self.subtensor.connect_websocket
def close(self):
"""
Cleans up resources for this subtensor instance like active websocket connection and active extensions
"""
self.substrate.close()
#####################
#### Delegation #####
#####################
def nominate(
self,
wallet: "bittensor.wallet",
wait_for_finalization: bool = False,
wait_for_inclusion: bool = True,
) -> bool:
"""
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.
Args:
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.
Returns:
bool: ``True`` if the nomination process is successful, ``False`` otherwise.
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.
"""
return nominate_extrinsic(
subtensor=self,
wallet=wallet,
wait_for_finalization=wait_for_finalization,
wait_for_inclusion=wait_for_inclusion,
)
def delegate(
self,
wallet: "bittensor.wallet",
delegate_ss58: Optional[str] = None,
amount: Optional[Union[Balance, float]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
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.
Args:
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.
Returns:
bool: ``True`` if the nomination process is successful, False otherwise.
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.
"""
return delegate_extrinsic(
subtensor=self,
wallet=wallet,
delegate_ss58=delegate_ss58,
amount=amount,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def undelegate(
self,
wallet: "bittensor.wallet",
delegate_ss58: Optional[str] = None,
amount: Optional[Union[Balance, float]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
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.
Args:
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:
bool: ``True`` if the undelegation is successful, False otherwise.
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.
"""
return undelegate_extrinsic(
subtensor=self,
wallet=wallet,
delegate_ss58=delegate_ss58,
amount=amount,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def send_extrinsic(
self,
wallet: "bittensor.wallet",
module: str,
function: str,
params: dict,
period: int = 5,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
max_retries: int = 3,
wait_time: int = 3,
max_wait: int = 20,
) -> Optional[ExtrinsicReceipt]:
"""
Sends an extrinsic to the Bittensor blockchain using the provided wallet and parameters. This method
constructs and submits the extrinsic, handling retries and blockchain communication.
Args:
wallet (bittensor.wallet): The wallet associated with the extrinsic.
module (str): The module name for the extrinsic.
function (str): The function name for the extrinsic.
params (dict): The parameters for the extrinsic.
period (int, optional): The number of blocks for the extrinsic to live in the mempool. Defaults to 5.
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.
max_retries (int, optional): The maximum number of retries for the extrinsic. Defaults to 3.
wait_time (int, optional): The wait time between retries. Defaults to 3.
max_wait (int, optional): The maximum wait time for the extrinsic. Defaults to 20.
Returns:
Optional[ExtrinsicReceipt]: The receipt of the extrinsic if successful, None otherwise.
"""
call = self.substrate.compose_call(
call_module=module,
call_function=function,
call_params=params,
)
hotkey = wallet.get_hotkey().ss58_address
# Periodically update the nonce cache
if hotkey not in KEY_NONCE or self.get_current_block() % 5 == 0:
KEY_NONCE[hotkey] = self.substrate.get_account_nonce(hotkey)
nonce = KEY_NONCE[hotkey]
# <3 parity tech
old_init_runtime = self.substrate.init_runtime
self.substrate.init_runtime = lambda: None
self.substrate.init_runtime = old_init_runtime
for attempt in range(1, max_retries + 1):
try:
# Create the extrinsic with new nonce
extrinsic = self.substrate.create_signed_extrinsic(
call=call,
keypair=wallet.hotkey,
era={"period": period},
nonce=nonce,
)
# Submit the extrinsic
response = self.substrate.submit_extrinsic(
extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
# Return immediately if we don't wait
if not wait_for_inclusion and not wait_for_finalization:
KEY_NONCE[hotkey] = nonce + 1 # update the nonce cache
return response
# If we wait for finalization or inclusion, check if it is successful
if response.is_success:
KEY_NONCE[hotkey] = nonce + 1 # update the nonce cache
return response
else:
# Wait for a while
wait = min(wait_time * attempt, max_wait)
time.sleep(wait)
# Incr the nonce and try again
nonce = nonce + 1
continue
# This dies because user is spamming... incr and try again
except SubstrateRequestException as e:
if "Priority is too low" in e.args[0]["message"]:
wait = min(wait_time * attempt, max_wait)
bittensor.logging.warning(
f"Priority is too low, retrying with new nonce: {nonce} in {wait} seconds."
)
nonce = nonce + 1
time.sleep(wait)
continue
else:
bittensor.logging.error(f"Error sending extrinsic: {e}")
response = None
return response
#####################
#### Set Weights ####
#####################
def set_weights(
self,
wallet: "bittensor.wallet",
netuid: int,
uids: Union[torch.LongTensor, list],
weights: Union[torch.FloatTensor, list],
version_key: int = bittensor.__version_as_int__,
uid: Optional[int] = None,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
prompt: bool = False,
max_retries: int = 5,
) -> Tuple[bool, str]:
"""
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.
Args:
wallet (bittensor.wallet): The wallet associated with the neuron setting the weights.
netuid (int): The unique identifier of the subnet.
uid (int): Unique identifier for the caller on the subnet specified by `netuid`.
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.
max_retries (int, optional): The number of maximum attempts to set weights. (Default: 5)
Returns:
Tuple[bool, str]: ``True`` if the setting of weights is successful, False otherwise. And `msg`, a string
value describing the success or potential error.
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】.
"""
uid = self.get_uid_for_hotkey_on_subnet(wallet.hotkey.ss58_address, netuid)
retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to set weights!"
while (
self.blocks_since_last_update(netuid, uid) > self.weights_rate_limit(netuid) # type: ignore
and retries < max_retries
):
try:
success, message = set_weights_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
uids=uids,
weights=weights,
version_key=version_key,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
except Exception as e:
bittensor.logging.error(f"Error setting weights: {e}")
finally:
retries += 1
return success, message
def _do_set_weights(
self,
wallet: "bittensor.wallet",
uids: List[int],
vals: List[int],
netuid: int,
version_key: int = bittensor.__version_as_int__,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
) -> Tuple[bool, Optional[str]]: # (success, error_message)
"""
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.
Args:
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:
Tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message.
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.
"""
@retry(delay=2, tries=3, backoff=2, max_delay=4)
def make_substrate_call_with_retry():
with self.substrate as substrate:
call = substrate.compose_call(
call_module="SubtensorModule",
call_function="set_weights",
call_params={
"dests": uids,
"weights": vals,
"netuid": netuid,
"version_key": version_key,
},
)
# Period dictates how long the extrinsic will stay as part of waiting pool
extrinsic = substrate.create_signed_extrinsic(
call=call,
keypair=wallet.hotkey,
era={"period": 5},
)
response = substrate.submit_extrinsic(
extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
return True, "Not waiting for finalziation or inclusion."
response.process_events()
if response.is_success:
return True, "Successfully set weights."
else:
return False, response.error_message
return make_substrate_call_with_retry()
######################
#### Registration ####
######################
def register(
self,
wallet: "bittensor.wallet",
netuid: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
max_allowed_attempts: int = 3,
output_in_place: bool = True,
cuda: bool = False,
dev_id: Union[List[int], int] = 0,
tpb: int = 256,
num_processes: Optional[int] = None,
update_interval: Optional[int] = None,
log_verbose: bool = False,
) -> bool:
"""
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.
Args:
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.
Other arguments: Various optional parameters to customize the registration process.
Returns:
bool: ``True`` if the registration is successful, False otherwise.
This function facilitates the entry of new neurons into the network, supporting the decentralized
growth and scalability of the Bittensor ecosystem.
"""
return register_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
max_allowed_attempts=max_allowed_attempts,
output_in_place=output_in_place,
cuda=cuda,
dev_id=dev_id,
tpb=tpb,
num_processes=num_processes,
update_interval=update_interval,
log_verbose=log_verbose,
)
def swap_hotkey(
self,
wallet: "bittensor.wallet",
new_wallet: "bittensor.wallet",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
) -> bool:
"""Swaps an old hotkey to a new hotkey."""
return swap_hotkey_extrinsic(
subtensor=self,
wallet=wallet,
new_wallet=new_wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def run_faucet(
self,
wallet: "bittensor.wallet",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
max_allowed_attempts: int = 3,
output_in_place: bool = True,
cuda: bool = False,
dev_id: Union[List[int], int] = 0,
tpb: int = 256,
num_processes: Optional[int] = None,
update_interval: Optional[int] = None,
log_verbose: bool = False,
) -> bool:
"""
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.
Args:
wallet (bittensor.wallet): The wallet for which the faucet transaction is to be run.
Other arguments: Various optional parameters to customize the faucet transaction process.
Returns:
bool: ``True`` if the faucet transaction is successful, False otherwise.
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.
"""
return run_faucet_extrinsic(
subtensor=self,
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
max_allowed_attempts=max_allowed_attempts,
output_in_place=output_in_place,
cuda=cuda,
dev_id=dev_id,
tpb=tpb,
num_processes=num_processes,
update_interval=update_interval,
log_verbose=log_verbose,
)
def burned_register(
self,
wallet: "bittensor.wallet",
netuid: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
) -> bool:
"""
Registers a neuron on the Bittensor network by recycling TAO. This method of registration
involves recycling TAO tokens, allowing them to be re-mined by performing work on the network.
Args:
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:
bool: ``True`` if the registration is successful, False otherwise.
"""
return burned_register_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def _do_pow_register(
self,
netuid: int,
wallet: "bittensor.wallet",
pow_result: POWSolution,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
) -> Tuple[bool, Optional[str]]:
"""Sends a (POW) register extrinsic to the chain.
Args:
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:
success (bool): ``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.
"""
@retry(delay=2, tries=3, backoff=2, max_delay=4)
def make_substrate_call_with_retry():
with self.substrate as substrate:
# create extrinsic call
call = substrate.compose_call(
call_module="SubtensorModule",
call_function="register",
call_params={
"netuid": netuid,
"block_number": pow_result.block_number,
"nonce": pow_result.nonce,
"work": [int(byte_) for byte_ in pow_result.seal],
"hotkey": wallet.hotkey.ss58_address,
"coldkey": wallet.coldkeypub.ss58_address,
},
)
extrinsic = substrate.create_signed_extrinsic(
call=call, keypair=wallet.hotkey
)
response = substrate.submit_extrinsic(
extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
return True, None
# process if registration successful, try again if pow is still valid
response.process_events()
if not response.is_success:
return False, response.error_message
# Successful registration
else:
return True, None
return make_substrate_call_with_retry()
def _do_burned_register(
self,
netuid: int,
wallet: "bittensor.wallet",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
) -> Tuple[bool, Optional[str]]:
@retry(delay=2, tries=3, backoff=2, max_delay=4)
def make_substrate_call_with_retry():
with self.substrate as substrate: