From 004219b156a7ebb3f9fe2c8a6966de59e61ca40b Mon Sep 17 00:00:00 2001 From: ibraheem-opentensor Date: Tue, 1 Oct 2024 10:19:13 -0700 Subject: [PATCH] Adds bittensor 8.0.0 --- .coveragerc | 7 + .dockerignore | 21 + .flake8 | 4 + .gitignore | 216 ++ .test_durations | 268 +++ CHANGELOG.md | 1101 +++++++++ Dockerfile | 40 + LICENSE | 16 + Makefile | 26 + README.md | 245 ++ VERSION | 1 + bittensor/__init__.py | 53 + bittensor/__main__.py | 21 + bittensor/core/__init__.py | 0 bittensor/core/axon.py | 1521 ++++++++++++ bittensor/core/chain_data/__init__.py | 22 + bittensor/core/chain_data/axon_info.py | 163 ++ bittensor/core/chain_data/delegate_info.py | 105 + .../core/chain_data/delegate_info_lite.py | 29 + bittensor/core/chain_data/ip_info.py | 81 + bittensor/core/chain_data/neuron_info.py | 176 ++ bittensor/core/chain_data/neuron_info_lite.py | 171 ++ bittensor/core/chain_data/prometheus_info.py | 31 + .../core/chain_data/proposal_vote_data.py | 21 + .../chain_data/scheduled_coldkey_swap_info.py | 65 + bittensor/core/chain_data/stake_info.py | 79 + .../core/chain_data/subnet_hyperparameters.py | 112 + bittensor/core/chain_data/subnet_info.py | 103 + bittensor/core/chain_data/utils.py | 291 +++ bittensor/core/config.py | 396 ++++ bittensor/core/dendrite.py | 832 +++++++ bittensor/core/errors.py | 129 ++ bittensor/core/extrinsics/__init__.py | 16 + bittensor/core/extrinsics/commit_weights.py | 274 +++ bittensor/core/extrinsics/prometheus.py | 187 ++ bittensor/core/extrinsics/serving.py | 319 +++ bittensor/core/extrinsics/set_weights.py | 194 ++ bittensor/core/extrinsics/transfer.py | 215 ++ bittensor/core/extrinsics/utils.py | 49 + bittensor/core/metagraph.py | 1299 +++++++++++ bittensor/core/settings.py | 241 ++ bittensor/core/stream.py | 158 ++ bittensor/core/subtensor.py | 1733 ++++++++++++++ bittensor/core/synapse.py | 852 +++++++ bittensor/core/tensor.py | 249 ++ bittensor/core/threadpool.py | 295 +++ bittensor/core/types.py | 38 + bittensor/utils/__init__.py | 279 +++ bittensor/utils/axon_utils.py | 58 + bittensor/utils/balance.py | 268 +++ bittensor/utils/btlogging/__init__.py | 27 + bittensor/utils/btlogging/defines.py | 28 + bittensor/utils/btlogging/format.py | 222 ++ bittensor/utils/btlogging/helpers.py | 88 + bittensor/utils/btlogging/loggingmachine.py | 534 +++++ bittensor/utils/deprecated.py | 150 ++ bittensor/utils/mock/__init__.py | 18 + bittensor/utils/mock/subtensor_mock.py | 908 ++++++++ bittensor/utils/networking.py | 199 ++ bittensor/utils/registration.py | 99 + bittensor/utils/subnets.py | 77 + bittensor/utils/version.py | 134 ++ bittensor/utils/weight_utils.py | 414 ++++ contrib/CODE_REVIEW_DOCS.md | 72 + contrib/CONTRIBUTING.md | 299 +++ contrib/DEBUGGING.md | 161 ++ contrib/DEVELOPMENT_WORKFLOW.md | 159 ++ contrib/RELEASE_GUIDELINES.md | 87 + contrib/STYLE.md | 350 +++ contrib/TESTING.md | 94 + docker-compose.yml | 10 + example.env | 5 + mypy.ini | 18 + requirements/btcli.txt | 1 + requirements/cubit.txt | 3 + requirements/dev.txt | 19 + requirements/prod.txt | 23 + requirements/torch.txt | 1 + scripts/check_compatibility.sh | 76 + scripts/check_pre_submit.sh | 18 + scripts/check_requirements_changes.sh | 10 + scripts/create_wallet.sh | 13 + scripts/environments/README.md | 21 + scripts/environments/apple_m1_environment.yml | 272 +++ scripts/install.sh | 298 +++ scripts/post_install_cli.py | 29 + setup.py | 98 + tests/__init__.py | 18 + tests/e2e_tests/__init__.py | 0 tests/e2e_tests/conftest.py | 84 + tests/e2e_tests/test_axon.py | 128 + tests/e2e_tests/test_commit_weights.py | 165 ++ tests/e2e_tests/test_dendrite.py | 136 ++ tests/e2e_tests/test_incentive.py | 184 ++ tests/e2e_tests/test_liquid_alpha.py | 186 ++ tests/e2e_tests/test_metagraph.py | 177 ++ tests/e2e_tests/test_subtensor_functions.py | 152 ++ tests/e2e_tests/test_transfer.py | 52 + tests/e2e_tests/utils/chain_interactions.py | 186 ++ tests/e2e_tests/utils/e2e_test_utils.py | 83 + tests/helpers/__init__.py | 34 + tests/helpers/helpers.py | 170 ++ tests/integration_tests/__init__.py | 16 + .../test_metagraph_integration.py | 110 + .../test_subtensor_integration.py | 250 ++ tests/pytest.ini | 3 + tests/unit_tests/__init__.py | 0 tests/unit_tests/conftest.py | 13 + .../extrinsics/test_commit_weights.py | 133 ++ tests/unit_tests/extrinsics/test_init.py | 114 + .../unit_tests/extrinsics/test_prometheus.py | 167 ++ tests/unit_tests/extrinsics/test_serving.py | 401 ++++ .../unit_tests/extrinsics/test_set_weights.py | 278 +++ tests/unit_tests/extrinsics/test_transfer.py | 142 ++ tests/unit_tests/factories/__init__.py | 0 tests/unit_tests/factories/neuron_factory.py | 63 + tests/unit_tests/test_axon.py | 781 +++++++ tests/unit_tests/test_chain_data.py | 479 ++++ tests/unit_tests/test_dendrite.py | 416 ++++ tests/unit_tests/test_deprecated.py | 51 + tests/unit_tests/test_logging.py | 199 ++ tests/unit_tests/test_metagraph.py | 176 ++ tests/unit_tests/test_subnets.py | 82 + tests/unit_tests/test_subtensor.py | 2053 +++++++++++++++++ tests/unit_tests/test_synapse.py | 269 +++ tests/unit_tests/test_tensor.py | 245 ++ tests/unit_tests/utils/__init__.py | 0 tests/unit_tests/utils/test_balance.py | 520 +++++ tests/unit_tests/utils/test_init.py | 27 + tests/unit_tests/utils/test_networking.py | 167 ++ tests/unit_tests/utils/test_registration.py | 62 + tests/unit_tests/utils/test_utils.py | 169 ++ tests/unit_tests/utils/test_version.py | 171 ++ tests/unit_tests/utils/test_weight_utils.py | 681 ++++++ 134 files changed, 28098 insertions(+) create mode 100644 .coveragerc create mode 100644 .dockerignore create mode 100644 .flake8 create mode 100644 .gitignore create mode 100644 .test_durations create mode 100644 CHANGELOG.md create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 VERSION create mode 100644 bittensor/__init__.py create mode 100644 bittensor/__main__.py create mode 100644 bittensor/core/__init__.py create mode 100644 bittensor/core/axon.py create mode 100644 bittensor/core/chain_data/__init__.py create mode 100644 bittensor/core/chain_data/axon_info.py create mode 100644 bittensor/core/chain_data/delegate_info.py create mode 100644 bittensor/core/chain_data/delegate_info_lite.py create mode 100644 bittensor/core/chain_data/ip_info.py create mode 100644 bittensor/core/chain_data/neuron_info.py create mode 100644 bittensor/core/chain_data/neuron_info_lite.py create mode 100644 bittensor/core/chain_data/prometheus_info.py create mode 100644 bittensor/core/chain_data/proposal_vote_data.py create mode 100644 bittensor/core/chain_data/scheduled_coldkey_swap_info.py create mode 100644 bittensor/core/chain_data/stake_info.py create mode 100644 bittensor/core/chain_data/subnet_hyperparameters.py create mode 100644 bittensor/core/chain_data/subnet_info.py create mode 100644 bittensor/core/chain_data/utils.py create mode 100644 bittensor/core/config.py create mode 100644 bittensor/core/dendrite.py create mode 100644 bittensor/core/errors.py create mode 100644 bittensor/core/extrinsics/__init__.py create mode 100644 bittensor/core/extrinsics/commit_weights.py create mode 100644 bittensor/core/extrinsics/prometheus.py create mode 100644 bittensor/core/extrinsics/serving.py create mode 100644 bittensor/core/extrinsics/set_weights.py create mode 100644 bittensor/core/extrinsics/transfer.py create mode 100644 bittensor/core/extrinsics/utils.py create mode 100644 bittensor/core/metagraph.py create mode 100644 bittensor/core/settings.py create mode 100644 bittensor/core/stream.py create mode 100644 bittensor/core/subtensor.py create mode 100644 bittensor/core/synapse.py create mode 100644 bittensor/core/tensor.py create mode 100644 bittensor/core/threadpool.py create mode 100644 bittensor/core/types.py create mode 100644 bittensor/utils/__init__.py create mode 100644 bittensor/utils/axon_utils.py create mode 100644 bittensor/utils/balance.py create mode 100644 bittensor/utils/btlogging/__init__.py create mode 100644 bittensor/utils/btlogging/defines.py create mode 100644 bittensor/utils/btlogging/format.py create mode 100644 bittensor/utils/btlogging/helpers.py create mode 100644 bittensor/utils/btlogging/loggingmachine.py create mode 100644 bittensor/utils/deprecated.py create mode 100644 bittensor/utils/mock/__init__.py create mode 100644 bittensor/utils/mock/subtensor_mock.py create mode 100644 bittensor/utils/networking.py create mode 100644 bittensor/utils/registration.py create mode 100644 bittensor/utils/subnets.py create mode 100644 bittensor/utils/version.py create mode 100644 bittensor/utils/weight_utils.py create mode 100644 contrib/CODE_REVIEW_DOCS.md create mode 100644 contrib/CONTRIBUTING.md create mode 100644 contrib/DEBUGGING.md create mode 100644 contrib/DEVELOPMENT_WORKFLOW.md create mode 100644 contrib/RELEASE_GUIDELINES.md create mode 100644 contrib/STYLE.md create mode 100644 contrib/TESTING.md create mode 100644 docker-compose.yml create mode 100644 example.env create mode 100644 mypy.ini create mode 100644 requirements/btcli.txt create mode 100644 requirements/cubit.txt create mode 100644 requirements/dev.txt create mode 100644 requirements/prod.txt create mode 100644 requirements/torch.txt create mode 100755 scripts/check_compatibility.sh create mode 100755 scripts/check_pre_submit.sh create mode 100755 scripts/check_requirements_changes.sh create mode 100755 scripts/create_wallet.sh create mode 100644 scripts/environments/README.md create mode 100644 scripts/environments/apple_m1_environment.yml create mode 100755 scripts/install.sh create mode 100644 scripts/post_install_cli.py create mode 100644 setup.py create mode 100644 tests/__init__.py create mode 100644 tests/e2e_tests/__init__.py create mode 100644 tests/e2e_tests/conftest.py create mode 100644 tests/e2e_tests/test_axon.py create mode 100644 tests/e2e_tests/test_commit_weights.py create mode 100644 tests/e2e_tests/test_dendrite.py create mode 100644 tests/e2e_tests/test_incentive.py create mode 100644 tests/e2e_tests/test_liquid_alpha.py create mode 100644 tests/e2e_tests/test_metagraph.py create mode 100644 tests/e2e_tests/test_subtensor_functions.py create mode 100644 tests/e2e_tests/test_transfer.py create mode 100644 tests/e2e_tests/utils/chain_interactions.py create mode 100644 tests/e2e_tests/utils/e2e_test_utils.py create mode 100644 tests/helpers/__init__.py create mode 100644 tests/helpers/helpers.py create mode 100644 tests/integration_tests/__init__.py create mode 100644 tests/integration_tests/test_metagraph_integration.py create mode 100644 tests/integration_tests/test_subtensor_integration.py create mode 100644 tests/pytest.ini create mode 100644 tests/unit_tests/__init__.py create mode 100644 tests/unit_tests/conftest.py create mode 100644 tests/unit_tests/extrinsics/test_commit_weights.py create mode 100644 tests/unit_tests/extrinsics/test_init.py create mode 100644 tests/unit_tests/extrinsics/test_prometheus.py create mode 100644 tests/unit_tests/extrinsics/test_serving.py create mode 100644 tests/unit_tests/extrinsics/test_set_weights.py create mode 100644 tests/unit_tests/extrinsics/test_transfer.py create mode 100644 tests/unit_tests/factories/__init__.py create mode 100644 tests/unit_tests/factories/neuron_factory.py create mode 100644 tests/unit_tests/test_axon.py create mode 100644 tests/unit_tests/test_chain_data.py create mode 100644 tests/unit_tests/test_dendrite.py create mode 100644 tests/unit_tests/test_deprecated.py create mode 100644 tests/unit_tests/test_logging.py create mode 100644 tests/unit_tests/test_metagraph.py create mode 100644 tests/unit_tests/test_subnets.py create mode 100644 tests/unit_tests/test_subtensor.py create mode 100644 tests/unit_tests/test_synapse.py create mode 100644 tests/unit_tests/test_tensor.py create mode 100644 tests/unit_tests/utils/__init__.py create mode 100644 tests/unit_tests/utils/test_balance.py create mode 100644 tests/unit_tests/utils/test_init.py create mode 100644 tests/unit_tests/utils/test_networking.py create mode 100644 tests/unit_tests/utils/test_registration.py create mode 100644 tests/unit_tests/utils/test_utils.py create mode 100644 tests/unit_tests/utils/test_version.py create mode 100644 tests/unit_tests/utils/test_weight_utils.py diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000000..b0e422abef --- /dev/null +++ b/.coveragerc @@ -0,0 +1,7 @@ +[run] +omit = + ./nuclei/* + ./routers/* + ./setup.py + ./tests/* + ./env/* diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..eabfb03301 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,21 @@ +**/data/ +**/*.log +**/*.png +**/*.pstats +**/*.ipynb +**/bittensor.egg-info/* +**/lib/* +**/build/* +**/dist/* +**/runs/* +**/env/* +**/venv/* +**/tmp/* +**/test_results/* +**/__pycache__/* +**/.circleci +**/.git +**/.github +**/.hypothesis +**/.vscode +**/.gitignore diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000..6b2eaa0333 --- /dev/null +++ b/.flake8 @@ -0,0 +1,4 @@ +[flake8] +max-line-length = 120 +exclude = .git,__pycache__, __init__.py, docs/source/conf.py,old,build,dist,venv,.venv,.tox +select = E9,F63,F7,F82,F401 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..5cc3b79913 --- /dev/null +++ b/.gitignore @@ -0,0 +1,216 @@ +# Byte-compiled / optimized / DLL files +**/__pycache__/ +*.py[cod] +*$py.class +*.pyc + +# Remove notebooks. +*.ipynb + +# weigths and biases +wandb/ + +*.csv +*.torch +*.pt +*.log + +# runs/data/models/logs/~ +data/ +**/data/ + +# C extensions +*.so + +# IDE +*.idea/ + +# VSCODE +.vscode/ + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ +# Generated by Cargo +# will have compiled files and executables +**/target/ +# These are backup files generated by rustfmt +**/*.rs.bk + +.DS_Store + +# The cache for docker container dependency +.cargo + +# The cache for chain data in container +.local + +# State folder for all neurons. +**/data/* +!data/.gitkeep + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +# PIPY Stuff +bittensor.egg-info +bittensor*.egg +bdist.* + +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +**/build/* +**/dist/* +**/runs/* +**/env/* +**/data/* +**/.data/* +**/tmp/* + +**/.bash_history +**/*.xml +**/*.pstats +**/*.png + +# Replicate library +**/.replicate +replicate.yaml +**/run.sh + +# Notebooks +*.ipynb + +tests/zombienet/bin/**/* \ No newline at end of file diff --git a/.test_durations b/.test_durations new file mode 100644 index 0000000000..8cb7d74bff --- /dev/null +++ b/.test_durations @@ -0,0 +1,268 @@ +{ + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_delegate_stake": 32.565206749999994, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_inspect": 2.0870491260000037, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_metagraph": 17.437785333, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_neuron_run_reregister_false": 35.75446520799999, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_nominate": 38.171487959, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview": 54.78253583300001, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_all": 303.709275458, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_no_wallet": 33.569985001, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_not_in_first_subnet": 7.832046707999993, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_hotkeys_config": 1.235335959000004, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_sort_by_bad_column_name": 34.20312183400001, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_sort_by_config": 1.4365408759999951, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_sort_order_config": 1.4505757079999952, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_sort_order_config_bad_sort_type": 34.18927604199999, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_with_width_config": 1.6561556670000002, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_without_hotkeys_config": 1.2479347909999987, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_without_sort_by_config": 34.193473041, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_without_sort_order_config": 1.436726291999996, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_overview_without_width_config": 1.449721043000011, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_recycle_register": 48.5383515, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_register": 6.655044251, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_set_weights": 0.006143250000008038, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake": 44.89659891599999, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_all_hotkeys": 31.83300620899999, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_exclude_hotkeys_from_all": 0.0015482090000062954, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_multiple_hotkeys_max_stake": 0.0011364169999907858, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_multiple_hotkeys_max_stake_not_enough_balance": 0.0009022089999959348, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_single_hotkey_max_stake": 0.0009031669999970404, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_single_hotkey_max_stake_enough_stake": 0.0012163340000057588, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_single_hotkey_max_stake_not_enough_balance": 0.0009654589999996688, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_stake_with_specific_hotkeys": 357.5746072910001, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_transfer": 16.976931332999996, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_transfer_not_enough_balance": 22.429711792000006, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_undelegate_stake": 27.56590779199999, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_unstake_with_all_hotkeys": 38.311913373, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_unstake_with_exclude_hotkeys_from_all": 0.0018990010000123903, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_unstake_with_multiple_hotkeys_max_stake": 0.0010086670000006848, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkAndConfig::test_unstake_with_specific_hotkeys": 0.0012716660000009483, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkUsingArgs::test_delegate": 0.0012134169999740152, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkUsingArgs::test_list_delegates": 12.917025874999979, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkUsingArgs::test_list_subnets": 0.32005762600000764, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkUsingArgs::test_run_reregister_false": 2.500768667000017, + "tests/integration_tests/test_cli.py::TestCLIWithNetworkUsingArgs::test_run_synapse_all": 8.177792832999984, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_btcli_help": 0.05371037599999795, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_check_configs": 0.5839849989999948, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_list": 0.015767583999995338, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_list_no_wallet": 0.004536540000003697, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_new_coldkey": 0.005761207000013258, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_new_hotkey": 0.003966625999993312, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_regen_coldkey": 0.00497241600000109, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_regen_coldkeypub": 0.00346216599999849, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_regen_hotkey": 0.004310167000014076, + "tests/integration_tests/test_cli_no_network.py::TestCLINoNetwork::test_register_cuda_use_cuda_flag": 2.813618584000004, + "tests/integration_tests/test_dataset.py::test_change_data_size": 9.975283208999997, + "tests/integration_tests/test_dataset.py::test_construct_text_corpus": 5.504439667999989, + "tests/integration_tests/test_dataset.py::test_fail_IPFS_server": 2.991185999999985, + "tests/integration_tests/test_dataset.py::test_mock": 0.11688258300000598, + "tests/integration_tests/test_dataset.py::test_mock_function": 0.11185374999999453, + "tests/integration_tests/test_dataset.py::test_next": 5.809825165999982, + "tests/integration_tests/test_dataset.py::test_text_dataset": 0.003949084000012704, + "tests/integration_tests/test_dendrite.py::test_dendrite_backoff": 0.3834034169999967, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor": 0.005605251000005751, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_endpoint_len_error": 0.0010508339999972804, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_endpoint_type_error": 0.0009945420000008198, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_input_len_error": 0.0010635420000113527, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_mismatch_len_error": 0.0009768319999921005, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_shape_error": 0.0010397920000002614, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_tensor_type_error": 0.0020723339999904056, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text": 0.005868083999999385, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_endpoints_tensor": 0.04405566500001612, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_list_string": 0.01698745900000631, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_multiple_endpoints_tensor": 0.01505404200000271, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_multiple_endpoints_tensor_list": 0.01597050000000877, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_non_list": 0.0058105829999988146, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_singular": 0.016635499999992476, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_singular_no_batch_size": 0.01967587499999013, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_singular_string": 0.02379695900000911, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_tensor_list": 0.00768116700000121, + "tests/integration_tests/test_dendrite.py::test_dendrite_forward_text_tensor_list_singular": 0.007751000000013164, + "tests/integration_tests/test_dendrite.py::test_dendrite_to_df": 0.6830525419999987, + "tests/integration_tests/test_dendrite.py::test_failing_synapse": 0.652249334000004, + "tests/integration_tests/test_dendrite.py::test_successful_synapse": 0.5847192090000135, + "tests/integration_tests/test_ipfs.py::test_ipfs_init": 0.005554707999998243, + "tests/integration_tests/test_ipfs.py::test_retrieve_directory": 0.20729179199999237, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_create": 0.08020704100000131, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_decrypt_keyfile_data_legacy": 3.0671192910000045, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_keyfile_mock": 0.018454082999994625, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_keyfile_mock_func": 0.019594999999995366, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_legacy_coldkey": 0.030612376000000552, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_overwriting": 0.031093917000006854, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_user_interface": 0.017205207999992922, + "tests/integration_tests/test_keyfile.py::TestKeyFiles::test_validate_password": 0.01777775099999701, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_full_sync": 3.6405804169999954, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_lite_sync": 3.6356975829999953, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_load_sync_save": 3.243659209999997, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_parameters": 3.0838419149999936, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_print_empty": 2.6707623749999954, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_properties": 3.287473416999994, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_state_dict": 3.296576874000003, + "tests/integration_tests/test_metagraph_integration.py::TestMetagraph::test_sync_block_0": 4.055834208, + "tests/integration_tests/test_priority_thread_pool.py::test_priority_thread_pool": 0.002472417000006999, + "tests/integration_tests/test_prometheus.py::TestPrometheus::test_init_prometheus_failed": 1.491444625000014, + "tests/integration_tests/test_prometheus.py::TestPrometheus::test_init_prometheus_success": 1.6381353319999903, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_get_balance": 2.5954937909999956, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_get_balances": 1.9654992910000004, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_get_current_block": 0.3812910839999972, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_get_uid_by_hotkey_on_subnet": 0.6584294999999969, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_hotkey_register": 0.46409241699998915, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_hotkey_register_failed": 0.3542701670000099, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_network_overrides": 0.953627209000004, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_registration_failed": 1.788183917000012, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_registration_multiprocessed_already_registered": 0.9777173749999974, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_registration_partly_failed": 1.5698486670000023, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_registration_stale_then_continue": 0.781868541999998, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_set_weights": 0.6006925410000008, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_set_weights_failed": 0.3889112079999961, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_set_weights_inclusion": 0.4296055830000114, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_stake": 0.1843938319999836, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_stake_failed": 0.3917970010000005, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_stake_inclusion": 0.38589883299999883, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_transfer": 2.0724527499999965, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_transfer_dest_as_bytes": 1.2727416259999842, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_transfer_failed": 1.2812408760000125, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_transfer_inclusion": 1.2405266240000117, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_transfer_invalid_dest": 0.4117500419999942, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_unstake": 0.4006357079999958, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_unstake_failed": 0.4873798340000093, + "tests/integration_tests/test_subtensor_integration.py::TestSubtensor::test_unstake_inclusion": 0.3860250829999927, + "tests/unit_tests/bittensor_tests/test_axon.py::TestExternalAxon::test_external_ip_not_set_dont_use_internal_ip": 0.006879416000003857, + "tests/unit_tests/bittensor_tests/test_axon.py::TestExternalAxon::test_external_ip_port_set_full_address_internal": 0.004500209000006805, + "tests/unit_tests/bittensor_tests/test_axon.py::TestExternalAxon::test_external_ip_set_full_address_internal": 0.08792841500000037, + "tests/unit_tests/bittensor_tests/test_axon.py::TestExternalAxon::test_external_port_not_set_use_internal_port": 0.004651376000000873, + "tests/unit_tests/bittensor_tests/test_axon.py::TestExternalAxon::test_external_port_set_full_address_internal": 0.00591749999999891, + "tests/unit_tests/bittensor_tests/test_axon.py::test_axon_is_destroyed": 0.040033332000000144, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_causal_lm_next_shape_error": 0.0009744579999990677, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_causal_lm_shape_error": 0.001580541999999241, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_deserialization_error": 0.0005970819999987498, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_grads_shape_error": 0.001092959000000171, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_invalid_request": 0.0007582499999996273, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_last_hidden_shape_error": 0.0008626240000007002, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_exception": 0.0010987509999997869, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_success_causal_lm": 0.0032578749999991885, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_success_causal_lm_next": 0.002431750000001287, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_success_hidden": 0.001287251000000822, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_success_text_priority": 0.0034178330000074197, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_response_timeout": 0.0009528730000010199, + "tests/unit_tests/bittensor_tests/test_axon.py::test_backward_seq_2_seq_shape_error": 0.0010720409999995795, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_batch_shape_error": 0.0007811660000003329, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causal_lm_next_state_exception": 0.0009985000000014566, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causal_lm_state_exception": 0.002173708000000829, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causallm_shape_error": 0.0006132079999998652, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causallm_success": 0.019581957999998956, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causallmnext_shape_error": 0.0007552919999991303, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_causallmnext_success": 0.022651415999999536, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_deserialization_empty": 0.0009227910000007, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_deserialization_error": 0.0008193749999989564, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_empty_request": 0.0011124170000007538, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_joint_faulty_synapse": 0.01353250000000017, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_joint_missing_synapse": 0.013988917000000711, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_joint_success": 0.0509341249999995, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_last_hidden_shape_error": 0.0008222500000005795, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_last_hidden_state_exception": 0.0009832080000000687, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_last_hidden_success": 0.0017997490000007943, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_not_implemented": 0.001580126000000348, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_priority_2nd_request_timeout": 2.009712416999996, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_priority_timeout": 27.006205707000003, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_response_deserialization_error": 0.0009404579999996443, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_seq_2_seq_shape_error": 0.0009308739999998039, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_seq_2_seq_state_exception": 0.0013031659999995782, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_seq_2_seq_success": 0.0018539589999990724, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_seq_shape_error": 0.0008392500000002912, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_tensor_success_priority": 0.07963441700000029, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_timeout": 0.0021218760000003556, + "tests/unit_tests/bittensor_tests/test_axon.py::test_forward_unknown_error": 0.000990500999999533, + "tests/unit_tests/bittensor_tests/test_axon.py::test_grpc_backward_fails": 0.006330292000001236, + "tests/unit_tests/bittensor_tests/test_axon.py::test_grpc_backward_works": 0.012263416000003247, + "tests/unit_tests/bittensor_tests/test_axon.py::test_grpc_forward_fails": 0.004834957999989342, + "tests/unit_tests/bittensor_tests/test_axon.py::test_grpc_forward_works": 0.015886249999994106, + "tests/unit_tests/bittensor_tests/test_axon.py::test_sign_v2": 0.0025120420000011023, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_add": 0.18219254200000012, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_add_invalid_type": 0.12365654300000006, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_add_other_not_balance": 0.14650508300000098, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_div_invalid_type": 0.12069516600000174, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_eq_invalid_type": 0.1321914169999996, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_eq_other_not_balance": 0.13415275000000015, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_floordiv": 0.2226764569999995, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_floordiv_other_not_balance": 0.23913508399999994, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_init": 0.12514987600000005, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_init_from_invalid_value": 0.0004109170000008433, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_mul": 0.19085399900000066, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_mul_invalid_type": 0.16508675100000048, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_mul_other_not_balance": 0.2507777079999993, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_neq_none": 0.12535729200000034, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_not_eq_none": 0.14622908400000068, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_radd_other_not_balance": 0.1727647920000006, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_rfloordiv_other_not_balance": 0.21285375000000073, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_rmul_other_not_balance": 0.17940537499999998, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_rsub_other_not_balance": 0.19510154200000063, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_rtruediv_other_not_balance": 0.32300358299999843, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_sub": 0.20487529099999868, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_sub_invalid_type": 0.13107362499999908, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_sub_other_not_balance": 0.20876896000000222, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_truediv": 0.20615204100000106, + "tests/unit_tests/bittensor_tests/test_balance.py::TestBalance::test_balance_truediv_other_not_balance": 0.20203299999999835, + "tests/unit_tests/bittensor_tests/test_config.py::test_loaded_config": 0.000341875000000158, + "tests/unit_tests/bittensor_tests/test_config.py::test_prefix": 1.4881067080000019, + "tests/unit_tests/bittensor_tests/test_config.py::test_strict": 0.003527500000000572, + "tests/unit_tests/bittensor_tests/test_config.py::test_to_defaults": 0.0006572089999998809, + "tests/unit_tests/bittensor_tests/test_endpoint.py::test_create_endpoint": 0.0035975830000012365, + "tests/unit_tests/bittensor_tests/test_endpoint.py::test_endpoint_fails_checks": 0.0009294989999997227, + "tests/unit_tests/bittensor_tests/test_endpoint.py::test_endpoint_to_tensor": 0.0014645410000007075, + "tests/unit_tests/bittensor_tests/test_endpoint.py::test_thrash_equality_of_endpoint": 0.5774439579999999, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_axon_receptor_forward_works": 0.0101347909999987, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_backward": 0.01403204099999833, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_backward_large": 0.0014666259999991382, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_backward_multiple": 0.0015117080000006666, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_backward_no_grad": 0.001954291000000552, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_call_time": 0.029393998999999837, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_del": 0.0004828739999975795, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_causal_lm_next_shape_error": 0.00045083400000045515, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_causal_lm_shape_error": 0.0004375410000001523, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_last_hidden_shape_error": 0.00042408300000218446, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_seq_2_seq_shape_error": 0.000591667000000129, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_tensor_pass_through_text_causal_lm": 0.0019801239999992504, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_tensor_pass_through_text_causal_lm_next": 0.0015587079999992426, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_tensor_pass_through_text_last_hidden": 0.0014038749999993883, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_tensor_pass_through_text_seq_2_seq": 0.0012167919999974686, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_text_causal_lm": 0.0020301259999992993, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_text_causal_lm_next": 0.0013322070000008068, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_text_last_hidden": 0.0011474169999985406, + "tests/unit_tests/bittensor_tests/test_forward_backward.py::test_dendrite_forward_text_seq_2_seq": 0.0011787070000028876, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_create_ed25519_keypair": 0.001834499999999295, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_create_keypair_from_private_key": 0.0005444169999986315, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_create_sr25519_keypair": 0.0015333330000011358, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_generate_mnemonic": 0.0003291669999967439, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_default_to_dev_mnemonic": 0.0019820840000015494, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_hard_path": 0.0019323339999992584, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_nested_hard_soft_path": 0.0018494169999989651, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_nested_soft_hard_path": 0.0020734170000000773, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_path_gt_32_bytes": 0.001790332999998867, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_soft_path": 0.0016932490000005629, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_hdkd_unsupported_password": 0.00044658299999866813, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_incorrect_private_key_length_sr25519": 0.00047804200000101105, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_incorrect_public_key": 0.0003666670000015415, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_invalid_mnemic": 0.0004930830000002828, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_only_provide_public_key": 0.00045920699999868475, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_only_provide_ss58_address": 0.000522709000001953, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_provide_no_ss58_address_and_public_key": 0.0005050830000019602, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify": 0.0016591679999979903, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_ed25519": 0.0016544579999990816, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_hex_data": 0.001937792000001437, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_incorrect_signature": 0.001960749000000206, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_invalid_message": 0.00183941700000112, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_invalid_signature": 0.0016063319999997105, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_invalid_signature_ed25519": 0.001609873999999678, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_and_verify_scale_bytes": 0.00196662400000136, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_missing_private_key": 0.0006992090000004225, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_sign_unsupported_crypto_type": 0.0004697499999988253, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_unsupport_crypto_type": 0.0004740830000002916, + "tests/unit_tests/bittensor_tests/test_keypair.py::KeyPairTestCase::test_verify_unsupported_crypto_type": 0.0007947079999990336, + "tests/unit_tests/bittensor_tests/test_metagraph.py::TestMetagraph::test_from_neurons": 0.8742741239999994, + "tests/unit_tests/bittensor_tests/test_neuron.py::TestCoreServer::test_coreserver_reregister_flag_false_exit": 0.006013750000001039, + "tests/unit_tests/bittensor_tests/test_neuron.py::TestCoreServer::test_coreserver_reregister_flag_true": 0.006052874999999958, + "tests/unit_tests/bittensor_tests/test_neuron.py::TestCoreServer::test_model_output_check": 9.921326915999998, + "tests/unit_tests/bittensor_tests/test_neuron.py::TestCoreServer::test_set_fine_tuning_params": 6.299140666000003, + "tests/unit_tests/bittensor_tests/test_neuron.py::TestCoreValidator::test_corevalidator_reregister_flag_false_exit": 0.008880706999999433 +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..011a1464d4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,1101 @@ +# Changelog + +## 8.0.0 /2024-09-25 + +## What's Changed + +Removes Bittensor CLI and Wallet functionalities and changes the Bittensor SDK package to be light while maintaining backwards compatibility + +* Update README.md by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/2320 +* remove unused code (tensor.py-> class tensor), remove old tests, add new tests by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2311 +* Updating/improving/creating docstring codebase by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2310 +* README updates for SDK by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/2309 +* Improved logic for concatenating message, prefix, and suffix in bittensor logging + test by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2306 +* BTSDK: Implementation of substrait custom errors handler for bittensor by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2305 +* btsdk cleanup by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2303 +* Fix mypy error for btlogging by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2299 +* Integrate `bt_decode` into BTSDK by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2298 +* BTSDK: Corrected arguments order in logging methods + test by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2292 +* BTSDK: removed exit sys call for ConnectionRefusedError in _get_substrate by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2288 +* BTSDK: Move `do*` methods to related extrinsic by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2286 +* add reconnection logic for correctly closed connection by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2283 +* Move extrinsics, update `deprecated.py` module. by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2278 +* Add substrate reconnection logic by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2269 +* Prod requirements cleanup by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2266 +* Decoupling chain_data.py to sub-package by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2264 +* Increase Bittensor SDK test coverage by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2262 +* Increase SDK test coverage (Part3) by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2257 +* Increase bittensor SDK test coverage by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2256 +* Increase test coverage for subtensor.py by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2252 +* Adds e2e and fixes metagraph save()/load() by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2231 +* feat/roman/reafctoring-before-test-coverage by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2230 +* Enhance: Switch from format() to f-strings by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2228 +* Commit-reveal re-added & e2e coverage by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2224 +* Adds e2e setup & tests by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2221 +* Updates after review session by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2220 +* Fix the usage of env vars in default settings. by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2218 +* Add dendrite reference to backwords compatibility by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2217 +* Bringing `btsdk` up-to-date with `staging` branch. by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2210 +* Part 3: Create new 'bittensor-sdk` package by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2206 +* Part 2: Redesign, fix namespace conflicts, remove btcli by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2204 +* Part1: Removing content related to the wallet. Start use the pip installable package. by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2191 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.4.0...v8.0.0 + +## 7.4.0 /2024-08-29 + +## What's Changed +* [Fix] Allow unstake below network min by @camfairchild in https://github.com/opentensor/bittensor/pull/2016 +* Tests/e2e tests staging by @open-junius in https://github.com/opentensor/bittensor/pull/1943 +* Chore: Backmerge 7.2 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2020 +* Fix broken tests and Enforce BTCLI usage by @opendansor in https://github.com/opentensor/bittensor/pull/2027 +* Add time delay to faucet by @opendansor in https://github.com/opentensor/bittensor/pull/2030 +* Skip faucet test by @opendansor in https://github.com/opentensor/bittensor/pull/2031 +* Adds normalization for alpha hyperparams by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2035 +* Revert info logging in processing response by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2043 +* Pin numpy version to 1.26.4 in prod.txt by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/2045 +* Test hot key Swap by @opendansor in https://github.com/opentensor/bittensor/pull/2044 +* Do not run Circle-CI on drafts by @thewhaleking in https://github.com/opentensor/bittensor/pull/1959 +* Enhancement: Detailed nonce information in-case of failures by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2050 +* fix bittensor not installing under Python 3.13 by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/2053 +* Enable Faucet Test by @opendansor in https://github.com/opentensor/bittensor/pull/2056 +* Add back BT_SUBTENSOR_CHAIN_ENDPOINT env variable by @bradleytf in https://github.com/opentensor/bittensor/pull/2034 +* Fix: Logging configs not being set by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2065 +* Feature/gus/liquid alpha params by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2012 +* Test Emissions E2E by @opendansor in https://github.com/opentensor/bittensor/pull/2036 +* Prevent e2e draft by @opendansor in https://github.com/opentensor/bittensor/pull/2072 +* Fix e2e to only run when PR is ready for review by @opendansor in https://github.com/opentensor/bittensor/pull/2077 +* Fix Faucet and fastblocks interaction by @opendansor in https://github.com/opentensor/bittensor/pull/2083 +* Float normalization for child hotkeys by @opendansor in https://github.com/opentensor/bittensor/pull/2093 +* Fix e2e test hanging by @open-junius in https://github.com/opentensor/bittensor/pull/2118 +* Fixes leaked semaphores by @thewhaleking in https://github.com/opentensor/bittensor/pull/2125 +* Backmerge master -> staging by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2136 +* fix: coldkeypub usage instead of coldkey for arbitration_stats by @Rapiiidooo in https://github.com/opentensor/bittensor/pull/2132 +* Removes extra no_prompts in commands by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2140 +* Adds timeout for e2e tests by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2141 +* fix: updates test_axon verify body async tests by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2142 +* test: fix mocksubtensor query previous blocks by @timabilov in https://github.com/opentensor/bittensor/pull/2139 +* Adds E2E for Metagraph command by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2143 +* feat: Enhance dendrite error messaging by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2117 +* Adds E2E Tests for wallet creation commands by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2145 +* [Ledger Integration] [Feature] bump pysub to 1.7.9+ by @camfairchild in https://github.com/opentensor/bittensor/pull/2156 +* Ruff complains about an extra line by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2158 +* support Wallet names with hyphens when passing password through ENV vars by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1949 +* Fix naming convention of swap hotkey test by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2162 +* Adds E2E test for wallet regenerations + fixes input bug for regen hotkey by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2149 +* Backmerge Master -> Staging (7.4) by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2170 +* ci: auto assigns cortex to opened PRs by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2184 +* CI/E2E test improvements by @mvds00 in https://github.com/opentensor/bittensor/pull/2168 +* Fix multiprocessing POW errors and No Torch logging errors by @thewhaleking in https://github.com/opentensor/bittensor/pull/2186 +* ci: update reviewers by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2189 +* Adds updated type in timeouts dendrite by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2196 +* Bumps setuptools ~=70.0.0 by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2150 +* Bump black from 23.7.0 to 24.3.0 in /requirements by @dependabot in https://github.com/opentensor/bittensor/pull/2197 +* btlogging/loggingmachine.py: Fix bw compat API. by @mvds00 in https://github.com/opentensor/bittensor/pull/2155 +* Check for participation before nomination call by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2193 +* test: subnet list e2e by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2198 +* ensure msg is str in _concat_msg by @thewhaleking in https://github.com/opentensor/bittensor/pull/2200 +* Fixes tests depending on explicit line numbers by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2211 +* Merge streaming fix to staging by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2183 +* Multiple bittensor versions e2e workflow by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2212 +* Changes name of workflow file by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2213 +* Enhances e2e tests to contain assertions & logging by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2192 +* Security fix: Bumps ansible and certifi by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2214 +* Wallet List Command e2e test by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2207 +* fix Synapse base performance (more than 10x speed up) by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/2161 +* Child Hotkeys by @opendansor in https://github.com/opentensor/bittensor/pull/2071 +* Improve child hotkeys QOL by @opendansor in https://github.com/opentensor/bittensor/pull/2225 +* Child hotkeys handle excess normalization by @opendansor in https://github.com/opentensor/bittensor/pull/2229 +* Fixes chain compilation timeouts by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2238 +* Update Child Hotkey commands by @opendansor in https://github.com/opentensor/bittensor/pull/2245 +* feat: return error message instead of raising exception by @gus-opentensor in https://github.com/opentensor/bittensor/pull/2244 +* Backmerge master to staging (7.3.1) by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2254 + +## New Contributors +* @bradleytf made their first contribution in https://github.com/opentensor/bittensor/pull/2034 +* @Rapiiidooo made their first contribution in https://github.com/opentensor/bittensor/pull/2132 +* @timabilov made their first contribution in https://github.com/opentensor/bittensor/pull/2139 +* @mvds00 made their first contribution in https://github.com/opentensor/bittensor/pull/2168 +* @dependabot made their first contribution in https://github.com/opentensor/bittensor/pull/2197 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.3.1...v7.4.0 + +## 7.3.1 / 2024-08-19 + +## What's Changed +* https://github.com/opentensor/bittensor/pull/2156 by @camfairchild + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.3.0...v7.3.1 + +## 7.3.0 / 2024-07-12 + +## What's Changed +* Liquid Alpha by @opendansor & @gus-opentensor in https://github.com/opentensor/bittensor/pull/2012 +* check_coldkey_swap by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2126 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.2.0...v7.3.0 + + +## 7.2.0 / 2024-06-12 + +## What's Changed +* less verbose handled synapse exceptions by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1928 +* Clean up the imports in commands/stake.py by @thewhaleking in https://github.com/opentensor/bittensor/pull/1951 +* Fix E2E test for Commit/Reveal with Salt flag by @opendansor in https://github.com/opentensor/bittensor/pull/1952 +* `bittensor.chain_data.py` module refactoring. by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1955 +* ci: e2e tests by @orriin in https://github.com/opentensor/bittensor/pull/1915 +* Dependency cleanup by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1967 +* replace `black` with `ruff` by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1968 +* post-black to ruff migration cleanup by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1979 +* Revert Axon IP decoding changes by @camfairchild in https://github.com/opentensor/bittensor/pull/1981 +* A wrapper for presenting extrinsics errors in a human-readable form. by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1980 +* Feat: Added normalized hyperparams by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1891 +* deprecate nest_asyncio use by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1974 +* Add e2e test for axon by @opendansor in https://github.com/opentensor/bittensor/pull/1984 +* Dendrite E2E test by @opendansor in https://github.com/opentensor/bittensor/pull/1988 +* fix __version_as_int__ for >10 minor/patch release vers (resolves #1982) by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1993 +* Test Incentive E2E by @opendansor in https://github.com/opentensor/bittensor/pull/2002 +* Add E2E faucet test by @opendansor in https://github.com/opentensor/bittensor/pull/1987 +* Allow unstake below network min by @camfairchild in https://github.com/opentensor/bittensor/pull/2016 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.1.1...v7.2.0 + + +## 7.1.1 / 2024-06-11 + +## What's Changed +* commit_reveal_weights_enabled argument parsing hotfix by @camfairchild in https://github.com/opentensor/bittensor/pull/2003 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.1.0...v7.1.1 + +## 7.1.0 / 2024-06-05 + +## What's Changed +* Added _do_set_root_weights by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1838 +* Release/7.0.1 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1963 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.0.1...v7.1.0 + +## 7.0.1 / 2024-05-31 + +## What's Changed +* Release/7.0.0 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1899 +* Fix return of ip version. by @opendansor in https://github.com/opentensor/bittensor/pull/1961 +* Fix trigger use_torch() by @renesweet24 https://github.com/opentensor/bittensor/pull/1960 + +## New Contributors +* @renesweet24 made their first contribution in https://github.com/opentensor/bittensor/pull/1960 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v7.0.0...v7.0.1 + + +## 7.0.0 / 2024-05-29 + +## What's Changed +* replace torch with numpy by @andreea-popescu-reef in https://github.com/opentensor/bittensor/pull/1777 +* Fix broken link in contrib/RELEASE_GUIDELINES #1821 by @thewhaleking in https://github.com/opentensor/bittensor/pull/1823 +* Tests: Added coverage for set_weights by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1825 +* Remove irrelevant call to get_delegates method. by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1826 +* Support for string mnemonic thru cli when regenerating coldkeys by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1815 +* Logging: Added _primary_loggers by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1797 +* Add in check for minimum stake for unstaking by @thewhaleking in https://github.com/opentensor/bittensor/pull/1832 +* Cache get_decoder_class by @thewhaleking in https://github.com/opentensor/bittensor/pull/1834 +* Warmfix/change decoder cacheing by @thewhaleking in https://github.com/opentensor/bittensor/pull/1842 +* Fix typo in warmfix by @thewhaleking in https://github.com/opentensor/bittensor/pull/1844 +* Add the command btcli root list_delegates_lite to handle the Delegate… by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1840 +* Change: console.error => console.print by @thewhaleking in https://github.com/opentensor/bittensor/pull/1849 +* Small fix with receiving delegates based on a 4-hour archive block by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1854 +* Replace torch with numpy by @sepehr-opentensor in https://github.com/opentensor/bittensor/pull/1786 +* Versioning: Enforcement for eth-utils by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1852 +* Versioning: Dependencies for FastAPI for Apple M's by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1855 +* Retrieving error types from the metadata of the Substrate palette SubtensorModule for the btcli console (logic) by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1862 +* Add version check caching, fix version comparison by @olzhasar-reef in https://github.com/opentensor/bittensor/pull/1835 +* Tests: Added coverage for root.py by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1877 +* Tests: Added coverage for network.py by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1879 +* Tests: extends coverage for overview cmd part 1 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1873 +* Tests: Added coverage for Unstaking by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1878 +* Tests: Added coverage for staking by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1837 +* Tests: Added coverage for Delegation by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1874 +* Updated error message and a test typo. by @thewhaleking in https://github.com/opentensor/bittensor/pull/1871 +* fix: deprecated usage of `Balances::transfer` method by @orriin in https://github.com/opentensor/bittensor/pull/1886 +* Fix Type Annotation by @opendansor in https://github.com/opentensor/bittensor/pull/1895 +* Docstrings updates for list delegate lite feature by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1890 +* Add Pre-commit Checker in scripts. Helps reduce CI calls. by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1893 +* fix get_coldkey_password_from_environment resolving wrong password by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1843 +* Drop python 3.8 support by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1892 +* feat: Refactor phase 2 overview cmd & add test cov. Adds factories by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1887 +* Add setting delegate take by @gztensor in https://github.com/opentensor/bittensor/pull/1903 +* E2E Test Patterns by @orriin in https://github.com/opentensor/bittensor/pull/1885 +* chore: correct method types by @distributedstatemachine in https://github.com/opentensor/bittensor/pull/1907 +* bittensor.btlogging refactoring by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1896 +* Part 1 for refactoring bittensor/subtensor.py by @RomanCh-OT in https://github.com/opentensor/bittensor/pull/1911 +* Update: Pydantic V2 by @opendansor in https://github.com/opentensor/bittensor/pull/1889 +* Add back compatibility with torch by @thewhaleking in https://github.com/opentensor/bittensor/pull/1904 +* Release/6.12.2 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1910 +* Chore: Updated dev requirements by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1946 + +## New Contributors +* @andreea-popescu-reef made their first contribution in https://github.com/opentensor/bittensor/pull/1777 +* @thewhaleking made their first contribution in https://github.com/opentensor/bittensor/pull/1823 +* @RomanCh-OT made their first contribution in https://github.com/opentensor/bittensor/pull/1826 +* @olzhasar-reef made their first contribution in https://github.com/opentensor/bittensor/pull/1835 +* @orriin made their first contribution in https://github.com/opentensor/bittensor/pull/1886 +* @opendansor made their first contribution in https://github.com/opentensor/bittensor/pull/1895 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.12.2...v7.0.0 + +## 6.12.2 / 2024-05-20 + +## What's Changed +* Add setting delegate take +* fix: deprecated transfer method usage + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.12.1...54eee604c00ac4f04a31d5d7bc663124731a34d8 + + +## 6.12.1 / 2024-05-17 + +## What's Changed +* Hotfix if the subnet UID is not in the Subnets + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.12.0...fd2442db8bb8aad55ced2ac3b748b04ebdc73292 + + + +## 6.12.0 / 2024-04-29 + +## What's Changed +* Tests: Axon to_string patch import by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1785 +* Tests: Extends coverage on Serving extrinsics methods by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1783 +* Fix: CVE-2024-24762 FastAPI by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1800 +* Fix: CVE-2024-26130 | vulnerability cryptography by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1801 +* fix PR templates by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1778 +* Fix: SNYK-PYTHON-CERTIFI-5805047 | Vulnerability Certifi by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1816 +* Tests: Extends test coverage on Registration methods by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1814 +* Fix: Wallet overwrite functionality by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1802 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.11.0...v6.12.0 + +## 6.11.0 / 2024-04-11 + +## What's Changed +* Tests: Adds coverage to subtensor help method & determine_chain_endpoint_and_network by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1761 +* [bug fix] Fix import json by @camfairchild in https://github.com/opentensor/bittensor/pull/1759 +* Remove context management for substrate in subtensor by @sepehr-opentensor in https://github.com/opentensor/bittensor/pull/1766 +* Tests: Extends coverage on axon methods by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1769 +* Revert nonce implementation fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1774 +* remove tests from package distribution by @mjurbanski-reef in https://github.com/opentensor/bittensor/pull/1779 +* Tests: Extends test coverage on Senate methods by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/1781 + +## New Contributors +* @mjurbanski-reef made their first contribution in https://github.com/opentensor/bittensor/pull/1779 +* @ibraheem-opentensor made their first contribution in https://github.com/opentensor/bittensor/pull/1781 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.10.1...v6.11.0 +## 6.10.1 / 2024-04-05 +## What's Changed +* Revert nonce implementation fix #1774: Breaking change needs to telegraphed in next release. + +## 6.10.0 / 2024-03-25 + +## What's Changed +* handle req args by parsing and raising by @ifrit98 in https://github.com/opentensor/bittensor/pull/1733 +* Replace wildcard imports with specific imports by @brueningf in https://github.com/opentensor/bittensor/pull/1724 +* Logging Refactor by @sepehr-opentensor in https://github.com/opentensor/bittensor/pull/1751 +* Update DEBUGGING.md by @e-gons in https://github.com/opentensor/bittensor/pull/1755 +* fix: nonce implementation by @GentikSolm in https://github.com/opentensor/bittensor/pull/1754 + +## New Contributors +* @sepehr-opentensor made their first contribution in https://github.com/opentensor/bittensor/pull/1751 +* @e-gons made their first contribution in https://github.com/opentensor/bittensor/pull/1755 +* @GentikSolm made their first contribution in https://github.com/opentensor/bittensor/pull/1754 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.9.3...v6.10.0 + +## 6.9.3 / 2024-03-12 + +## What's Changed +* Release/6.9.2 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1743 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.9.2...v6.9.3 + + +## 6.9.2 / 2024-03-08 + +## What's Changed +* Change error into a warning if not using archive. Impossible to tell if local is lite or full node. + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.9.1...v6.9.2 + + +## 6.9.1 / 2024-03-08 + +## What's Changed +* Hotfix for reversing comparison operator for block checking to raise error if not using archive nodes + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.9.0...v6.9.1 + + +## 6.9.0 / 2024-03-07 + +## What's Changed +* Doc: Updates WalletBalanceCommand docstring by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1716 +* feature: metapgraph.py now passing type check by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1721 +* fix: Updates `btcli wallet balance --all` to get proper Wallet Name & Coldkey Address sets by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1720 +* Feature/prompt set identity on btcli/phil by @ifrit98 in https://github.com/opentensor/bittensor/pull/1719 +* Fix: Raises error when exceeding block max on metagraph by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1722 +* Release/6.8.2 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1730 +* Expands type checking to subtensor by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1731 +* Feature: Synapse passing type check by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1725 +* bump req for security vulnerability in crpytography by @ifrit98 in https://github.com/opentensor/bittensor/pull/1718 +* Fix: proper association with wallet dir and coldkey addr #1739 by @gus-opentensor & @sepehr-opentensor +* Fixed event lookup on new network added #1741 by @shibshib + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.8.2...v6.9.0 + + +## 6.8.2 / 2024-03-01 + +## What's Changed +* Set weights fix retry and check mechanism by @ifrit98 in https://github.com/opentensor/bittensor/pull/1729 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.8.1...v6.8.2 + + +## 6.8.1 / 2024-02-22 + +## What's Changed +* Hotfix revert dendrite streaming call to use `synapse.process_streaming_response` func instead of Starlette `iter_any()` from response object. + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.8.0...v6.8.1 + + +## 6.8.0 / 2024-02-16 + +## What's Changed +* Release/6.7.2 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1695 +* close synchronosuly on __del__ by @ifrit98 in https://github.com/opentensor/bittensor/pull/1700 +* CI: Flake8 by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1701 +* logging off switch by @ifrit98 in https://github.com/opentensor/bittensor/pull/1704 +* Extrinsic update by @ifrit98 in https://github.com/opentensor/bittensor/pull/1703 +* Bittensor shared request layer by @ifrit98 in https://github.com/opentensor/bittensor/pull/1698 +* Add no_prompt argument to help printout in https://github.com/opentensor/bittensor/pull/1707 +* Adds mypi typechecking to circleci by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1705 +* Remove set weights ttl now that we have a better extrinsic method by @ifrit98 +* Bug fix in overview command for dereg stake with outdated `stake_info` object fields by @ifrit98 in https://github.com/opentensor/bittensor/pull/1712 +* Moves mock wallet creation to temp dir by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1711 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.7.2...v6.8.0 + + +## 6.7.2 / 2024-02-08 + +## What's Changed +* Release/6.7.1 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1688 +* Increases test coverage for cli & chain_data by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1690 +* Subtensor/update pysubstrate latest/phil by @ifrit98 in https://github.com/opentensor/bittensor/pull/1684 +* Update staging to latest master by @ifrit98 in https://github.com/opentensor/bittensor/pull/1691 +* return messages with subtensor extrinsic to set weights by @ifrit98 in https://github.com/opentensor/bittensor/pull/1692 +* Logging/debug to trace axon by @ifrit98 in https://github.com/opentensor/bittensor/pull/1694 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.7.1...v6.7.2 + + +## 6.7.1 / 2024-02-02 + +## What's Changed +* Release/6.7.0 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1674 +* Eighth (final) docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1678 +* Sixth docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1676 +* Seventh docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1677 +* Update README.md by @unconst in https://github.com/opentensor/bittensor/pull/1679 +* Update README.md by @unconst in https://github.com/opentensor/bittensor/pull/1680 +* black formatting by @ifrit98 in https://github.com/opentensor/bittensor/pull/1685 +* burn -> recycle for public facing code by @ifrit98 in https://github.com/opentensor/bittensor/pull/1681 +* Expands test coverage and coverts python unittest classes to pure pytest by @gus-opentensor in https://github.com/opentensor/bittensor/pull/1686 +* wrap set weights in a ttl multiprocessing call so we don't hang past TTL by @ifrit98 in https://github.com/opentensor/bittensor/pull/1687 + +## New Contributors +* @gus-opentensor made their first contribution in https://github.com/opentensor/bittensor/pull/1686 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.7.0...v6.7.1 + + + +## 6.7.0 / 2024-01-25 + +## What's Changed +* First docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1663 +* Second docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1665 +* Third docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1666 +* updated mac yaml mac yaml by @dougsillars in https://github.com/opentensor/bittensor/pull/1668 +* Fourth docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1670 +* Fifth docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1671 +* ensure branch off from staging and rm old docs by @ifrit98 in https://github.com/opentensor/bittensor/pull/1667 +* staging black format fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1669 +* wallet history url for taostats by @ifrit98 in https://github.com/opentensor/bittensor/pull/1672 +* take bt.config as a first argument regardless if specified by @ifrit98 in https://github.com/opentensor/bittensor/pull/1664 +* Hparams update by @ifrit98 in https://github.com/opentensor/bittensor/pull/1673 + +## New Contributors +* @rajkaramchedu made their first contribution in https://github.com/opentensor/bittensor/pull/1663 +* @dougsillars made their first contribution in https://github.com/opentensor/bittensor/pull/1668 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.6.1...v6.7.0 + + +## 6.6.1 / 2024-01-17 + +## What's Changed +* bittensor README update by @Jackalgirl in https://github.com/opentensor/bittensor/pull/1650 +* Bugfix btcli fix args by @ifrit98 in https://github.com/opentensor/bittensor/pull/1654 + +## New Contributors +* @Jackalgirl made their first contribution in https://github.com/opentensor/bittensor/pull/1650 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.6.0...v6.6.1 + + +## 6.6.0 / 2024-01-08 + +## What's Changed +* Add commitment support to MockSubtensor by @agoncharov-reef in https://github.com/opentensor/bittensor/pull/1635 +* don't prenormalize weights in btcli boost/slash by @ifrit98 in https://github.com/opentensor/bittensor/pull/1636 +* feat(wallets.py): add wallet history command by @saqib-codes-11 in https://github.com/opentensor/bittensor/pull/1638 +* Update taostats link by @mogmachine in https://github.com/opentensor/bittensor/pull/1641 +* update wallet history command to right justify and fmt 3 decimal places by @ifrit98 in https://github.com/opentensor/bittensor/pull/1639 + +## New Contributors +* @agoncharov-reef made their first contribution in https://github.com/opentensor/bittensor/pull/1635 +* @saqib-codes-11 made their first contribution in https://github.com/opentensor/bittensor/pull/1638 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.5.0...v6.6.0 + + +## 6.5.0 / 2023-12-19 + +## What's Changed +* Logging/axon handling refactor by @ifrit98 in https://github.com/opentensor/bittensor/pull/1627 +* Add decoding to get_commitment helper function to return original value by @ifrit98 in https://github.com/opentensor/bittensor/pull/1630 +* don't print subtensor message on cli by @ifrit98 in https://github.com/opentensor/bittensor/pull/1625 +* Add tab autocompletion to btcli by @ifrit98 in https://github.com/opentensor/bittensor/pull/1628 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.4.4...v6.5.0 + + +## 6.4.4 / 2023-12-14 + +## What's Changed + +* Merge/master642 staging no-ff by @ifrit98 in https://github.com/opentensor/bittensor/pull/1615 +* print help message on error for subcommands by @ifrit98 in https://github.com/opentensor/bittensor/pull/1618 +* Metadata/commitments by @ifrit98 in https://github.com/opentensor/bittensor/pull/1621 + +## New Contributors +* @omahs made their first contribution in https://github.com/opentensor/bittensor/pull/1553 +* @surcyf123 made their first contribution in https://github.com/opentensor/bittensor/pull/1569 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.4.2...v6.4.4 + + +## 6.4.2 / 2023-12-07 + +## What's Changed +* Fix broken explorer links https://github.com/opentensor/bittensor/pull/1607 +* Fix spamming bittensor subtensor logging https://github.com/opentensor/bittensor/pull/1608 +* Fix hanging subtensor websocket https://github.com/opentensor/bittensor/pull/1609 +* Hparam update to palette: https://github.com/opentensor/bittensor/pull/1612 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.4.1...v6.4.2 + + +## 6.4.1 / 2023-12-01 + +## What's Changed +* add helpful messages to signal coming changes in https://github.com/opentensor/bittensor/pull/1600/commits/86c0c3ccfcd91d0e3ff87f53bdc3e9c5e68661da +* revert default subtensor network to finney in https://github.com/opentensor/bittensor/pull/1600/commits/8c69a3c15cd556384d0309e951f0a9b164dd36cb + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.4.0...v6.4.1 + + +## 6.4.0 / 2023-11-29 + +## What's Changed +* (un)Staking multiple avoid tx limit by @camfairchild in https://github.com/opentensor/bittensor/pull/1244 +* additional logging for prometheus by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1246 +* Dataset fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1249 +* Grab delegates details from GitHub by @camfairchild in https://github.com/opentensor/bittensor/pull/1245 +* Add raw spec for local test and new bins by @camfairchild in https://github.com/opentensor/bittensor/pull/1243 +* Fix list_delegates on non-archive nodes by @camfairchild in https://github.com/opentensor/bittensor/pull/1232 +* Blacklist fixes + depreciation of old signatures by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1240 +* [BIT-636] Change u16 weight normalization to max-upscaling by @opentaco in https://github.com/opentensor/bittensor/pull/1241 +* remove duplicate command #1228 by @camfairchild in https://github.com/opentensor/bittensor/pull/1231 +* test_forward_priority_2nd_request_timeout fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1276 +* Remove btcli query and btcli set_weights by @camfairchild in https://github.com/opentensor/bittensor/pull/1144 +* Merge releases 4.0.0 and 4.0.1 back to staging by @camfairchild in https://github.com/opentensor/bittensor/pull/1306 +* Improve development workflow documentation by @quac88 in https://github.com/opentensor/bittensor/pull/1262 +* staging updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1540 +* Add root get_weights command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1536 +* Fix typo by @steffencruz in https://github.com/opentensor/bittensor/pull/1543 +* remove duplicated debug message in dendrite by @ifrit98 in https://github.com/opentensor/bittensor/pull/1544 +* Cli fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1541 +* update faucet helpstr by @ifrit98 in https://github.com/opentensor/bittensor/pull/1542 +* Added mechanism to sum all delegated tao by @shibshib in https://github.com/opentensor/bittensor/pull/1547 +* Dict hash fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1548 +* Release/6.1.0 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1550 +* Merge master by @ifrit98 in https://github.com/opentensor/bittensor/pull/1552 +* Streaming fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1551 +* Fix typos by @omahs in https://github.com/opentensor/bittensor/pull/1553 +* Normalize weights in r get weights table by @camfairchild in https://github.com/opentensor/bittensor/pull/1556 +* Dendrite & Synapse updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1555 +* rm root flag in metagraph by @ifrit98 in https://github.com/opentensor/bittensor/pull/1558 +* Max Faucet Runs == 3 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1560 +* replace unknown wallet params (chain mismatch) with key values by @ifrit98 in https://github.com/opentensor/bittensor/pull/1559 +* Remove PoW registration cli and associated extrinsic by @ifrit98 in https://github.com/opentensor/bittensor/pull/1557 +* Add btcli wallet balance by @ifrit98 in https://github.com/opentensor/bittensor/pull/1564 +* Dendrite fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1561 +* Master into staging by @ifrit98 in https://github.com/opentensor/bittensor/pull/1570 +* adding logging.exception by @surcyf123 in https://github.com/opentensor/bittensor/pull/1569 +* Update network.py by @wildcommunist in https://github.com/opentensor/bittensor/pull/1568 +* Subtensor Registry by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1562 +* add instructions for upgrading bittensor with outdated version check by @ifrit98 in https://github.com/opentensor/bittensor/pull/1571 +* Add identity commands to btcli by @ifrit98 in https://github.com/opentensor/bittensor/pull/1566 +* Add set_delegate_take command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1563 +* Subtensor archive by @ifrit98 in https://github.com/opentensor/bittensor/pull/1575 +* Bugfix/list delegates by @ifrit98 in https://github.com/opentensor/bittensor/pull/1577 +* don't return result twice in query() by @ifrit98 in https://github.com/opentensor/bittensor/pull/1574 +* rename logging.py so doesn't circ import by @ifrit98 in https://github.com/opentensor/bittensor/pull/1572 +* add AxonInfo._string() by @ifrit98 in https://github.com/opentensor/bittensor/pull/1565 +* don't print __is_set for recursive objects by @ifrit98 in https://github.com/opentensor/bittensor/pull/1573 +* Adds docstrings for CLI for Sphynx documentation by @ifrit98 in https://github.com/opentensor/bittensor/pull/1579 +* Master 630 into staging by @ifrit98 in https://github.com/opentensor/bittensor/pull/1590 +* Registry cost 0.1 tao by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1587 +* Add swap_hotkey command to wallet by @ifrit98 in https://github.com/opentensor/bittensor/pull/1580 +* Cuda fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1595 +* Feature/local subtensor default by @ifrit98 in https://github.com/opentensor/bittensor/pull/1591 +* Boost by @unconst in https://github.com/opentensor/bittensor/pull/1594 +* avoid aiohttp <3.9.0 potential security issue by @ifrit98 in https://github.com/opentensor/bittensor/pull/1597 +* update bittensor docstrings (overhaul) by @ifrit98 in https://github.com/opentensor/bittensor/pull/1592 + +## New Contributors +* @omahs made their first contribution in https://github.com/opentensor/bittensor/pull/1553 +* @surcyf123 made their first contribution in https://github.com/opentensor/bittensor/pull/1569 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.1...v6.4.0 + + +## 6.3.0 / 2023-11-16 + +## What's Changed +* (un)Staking multiple avoid tx limit by @camfairchild in https://github.com/opentensor/bittensor/pull/1244 +* additional logging for prometheus by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1246 +* Dataset fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1249 +* Grab delegates details from GitHub by @camfairchild in https://github.com/opentensor/bittensor/pull/1245 +* Add raw spec for local test and new bins by @camfairchild in https://github.com/opentensor/bittensor/pull/1243 +* Fix list_delegates on non-archive nodes by @camfairchild in https://github.com/opentensor/bittensor/pull/1232 +* Blacklist fixes + depreciation of old signatures by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1240 +* [BIT-636] Change u16 weight normalization to max-upscaling by @opentaco in https://github.com/opentensor/bittensor/pull/1241 +* remove duplicate command #1228 by @camfairchild in https://github.com/opentensor/bittensor/pull/1231 +* test_forward_priority_2nd_request_timeout fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1276 +* Remove btcli query and btcli set_weights by @camfairchild in https://github.com/opentensor/bittensor/pull/1144 +* Merge releases 4.0.0 and 4.0.1 back to staging by @camfairchild in https://github.com/opentensor/bittensor/pull/1306 +* Improve development workflow documentation by @quac88 in https://github.com/opentensor/bittensor/pull/1262 +* staging updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1540 +* Add root get_weights command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1536 +* Fix typo by @steffencruz in https://github.com/opentensor/bittensor/pull/1543 +* remove duplicated debug message in dendrite by @ifrit98 in https://github.com/opentensor/bittensor/pull/1544 +* Cli fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1541 +* update faucet helpstr by @ifrit98 in https://github.com/opentensor/bittensor/pull/1542 +* Added mechanism to sum all delegated tao by @shibshib in https://github.com/opentensor/bittensor/pull/1547 +* Dict hash fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1548 +* Release/6.1.0 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1550 +* Merge master by @ifrit98 in https://github.com/opentensor/bittensor/pull/1552 +* Streaming fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1551 +* Fix typos by @omahs in https://github.com/opentensor/bittensor/pull/1553 +* Normalize weights in r get weights table by @camfairchild in https://github.com/opentensor/bittensor/pull/1556 +* Dendrite & Synapse updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1555 +* rm root flag in metagraph by @ifrit98 in https://github.com/opentensor/bittensor/pull/1558 +* Max Faucet Runs == 3 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1560 +* replace unknown wallet params (chain mismatch) with key values by @ifrit98 in https://github.com/opentensor/bittensor/pull/1559 +* Remove PoW registration cli and associated extrinsic by @ifrit98 in https://github.com/opentensor/bittensor/pull/1557 +* Add btcli wallet balance by @ifrit98 in https://github.com/opentensor/bittensor/pull/1564 +* Dendrite fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1561 +* Release/6.2.0 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1567 +* Master into staging by @ifrit98 in https://github.com/opentensor/bittensor/pull/1570 +* adding logging.exception by @surcyf123 in https://github.com/opentensor/bittensor/pull/1569 +* Update network.py by @wildcommunist in https://github.com/opentensor/bittensor/pull/1568 +* Subtensor Registry by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1562 +* add instructions for upgrading bittensor with outdated version check by @ifrit98 in https://github.com/opentensor/bittensor/pull/1571 +* Add identity commands to btcli by @ifrit98 in https://github.com/opentensor/bittensor/pull/1566 +* Add set_delegate_take command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1563 +* Subtensor archive by @ifrit98 in https://github.com/opentensor/bittensor/pull/1575 +* Bugfix/list delegates by @ifrit98 in https://github.com/opentensor/bittensor/pull/1577 +* don't return result twice in query() by @ifrit98 in https://github.com/opentensor/bittensor/pull/1574 +* rename logging.py so doesn't circ import by @ifrit98 in https://github.com/opentensor/bittensor/pull/1572 +* add AxonInfo._string() by @ifrit98 in https://github.com/opentensor/bittensor/pull/1565 +* don't print __is_set for recursive objects by @ifrit98 in https://github.com/opentensor/bittensor/pull/1573 + +## New Contributors +* @omahs made their first contribution in https://github.com/opentensor/bittensor/pull/1553 +* @surcyf123 made their first contribution in https://github.com/opentensor/bittensor/pull/1569 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.1...v6.3.0 + + +## 6.2.0 / 2023-10-30 + +## What's Changed +* (un)Staking multiple avoid tx limit by @camfairchild in https://github.com/opentensor/bittensor/pull/1244 +* additional logging for prometheus by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1246 +* Dataset fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1249 +* Grab delegates details from GitHub by @camfairchild in https://github.com/opentensor/bittensor/pull/1245 +* Add raw spec for local test and new bins by @camfairchild in https://github.com/opentensor/bittensor/pull/1243 +* Fix list_delegates on non-archive nodes by @camfairchild in https://github.com/opentensor/bittensor/pull/1232 +* Blacklist fixes + depreciation of old signatures by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1240 +* [BIT-636] Change u16 weight normalization to max-upscaling by @opentaco in https://github.com/opentensor/bittensor/pull/1241 +* remove duplicate command #1228 by @camfairchild in https://github.com/opentensor/bittensor/pull/1231 +* test_forward_priority_2nd_request_timeout fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1276 +* Remove btcli query and btcli set_weights by @camfairchild in https://github.com/opentensor/bittensor/pull/1144 +* Merge releases 4.0.0 and 4.0.1 back to staging by @camfairchild in https://github.com/opentensor/bittensor/pull/1306 +* Improve development workflow documentation by @quac88 in https://github.com/opentensor/bittensor/pull/1262 +* staging updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1540 +* Add root get_weights command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1536 +* Fix typo by @steffencruz in https://github.com/opentensor/bittensor/pull/1543 +* remove duplicated debug message in dendrite by @ifrit98 in https://github.com/opentensor/bittensor/pull/1544 +* Cli fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1541 +* update faucet helpstr by @ifrit98 in https://github.com/opentensor/bittensor/pull/1542 +* Added mechanism to sum all delegated tao by @shibshib in https://github.com/opentensor/bittensor/pull/1547 +* Dict hash fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1548 +* Release/6.1.0 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1550 +* Merge master by @ifrit98 in https://github.com/opentensor/bittensor/pull/1552 +* Streaming fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1551 +* Fix typos by @omahs in https://github.com/opentensor/bittensor/pull/1553 +* Normalize weights in r get weights table by @camfairchild in https://github.com/opentensor/bittensor/pull/1556 +* Dendrite & Synapse updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1555 +* rm root flag in metagraph by @ifrit98 in https://github.com/opentensor/bittensor/pull/1558 +* Max Faucet Runs == 3 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1560 +* replace unknown wallet params (chain mismatch) with key values by @ifrit98 in https://github.com/opentensor/bittensor/pull/1559 +* Remove PoW registration cli and associated extrinsic by @ifrit98 in https://github.com/opentensor/bittensor/pull/1557 +* Add btcli wallet balance by @ifrit98 in https://github.com/opentensor/bittensor/pull/1564 +* Dendrite fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1561 + +## New Contributors +* @omahs made their first contribution in https://github.com/opentensor/bittensor/pull/1553 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.1...v6.2.0 + + +## 6.1.0 / 2023-10-17 + +## What's Changed +* (un)Staking multiple avoid tx limit by @camfairchild in https://github.com/opentensor/bittensor/pull/1244 +* additional logging for prometheus by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1246 +* Dataset fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1249 +* Grab delegates details from GitHub by @camfairchild in https://github.com/opentensor/bittensor/pull/1245 +* Add raw spec for local test and new bins by @camfairchild in https://github.com/opentensor/bittensor/pull/1243 +* Fix list_delegates on non-archive nodes by @camfairchild in https://github.com/opentensor/bittensor/pull/1232 +* Blacklist fixes + depreciation of old signatures by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1240 +* [BIT-636] Change u16 weight normalization to max-upscaling by @opentaco in https://github.com/opentensor/bittensor/pull/1241 +* remove duplicate command #1228 by @camfairchild in https://github.com/opentensor/bittensor/pull/1231 +* test_forward_priority_2nd_request_timeout fix by @isabella618033 in https://github.com/opentensor/bittensor/pull/1276 +* Remove btcli query and btcli set_weights by @camfairchild in https://github.com/opentensor/bittensor/pull/1144 +* Merge releases 4.0.0 and 4.0.1 back to staging by @camfairchild in https://github.com/opentensor/bittensor/pull/1306 +* Improve development workflow documentation by @quac88 in https://github.com/opentensor/bittensor/pull/1262 +* staging updates and fixes by @ifrit98 in https://github.com/opentensor/bittensor/pull/1540 +* Add root get_weights command to btcli by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1536 +* Fix typo by @steffencruz in https://github.com/opentensor/bittensor/pull/1543 +* remove duplicated debug message in dendrite by @ifrit98 in https://github.com/opentensor/bittensor/pull/1544 +* Cli fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1541 +* update faucet helpstr by @ifrit98 in https://github.com/opentensor/bittensor/pull/1542 +* Added mechanism to sum all delegated tao by @shibshib in https://github.com/opentensor/bittensor/pull/1547 +* Dict hash fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1548 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.1...v6.1.0 + + +## 6.0.1 / 2023-10-02 + +## What's Changed +* Fix requirements/prod.txt, we had a bad format dependency not allowed by PyPi by @eduardogr in https://github.com/opentensor/bittensor/pull/1537 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.0...v6.0.1 + + +## 6.0.0 / 2023-10-02 + +## What's Changed +* - Adjusted blacklist argument default to False by @Inquinim in https://github.com/opentensor/bittensor/pull/1448 +* Release/5.3.1 by @camfairchild in https://github.com/opentensor/bittensor/pull/1444 +* Release/5.3.2 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1462 +* [hotfix] Release v5.3.3 by @camfairchild in https://github.com/opentensor/bittensor/pull/1467 +* Update README.md by @unconst in https://github.com/opentensor/bittensor/pull/1477 +* Release/5.3.4 by @ifrit98 in https://github.com/opentensor/bittensor/pull/1483 +* Revolution by @unconst in https://github.com/opentensor/bittensor/pull/1450 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.3.0...v6.0.0 + + +## 6.0.1 / 2023-10-02 + +## What's Changed +* Fix requirements/prod.txt, we had a bad format dependency not allowed by PyPi by @eduardogr in https://github.com/opentensor/bittensor/pull/1537 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.0.0...v6.0.1 + + +## 5.3.4 / 2023-08-16 + +# What's Changed +* Removes miniupnpc by @ifrit98 (completely unused and requires a sudo install) +* Fixes blacklist vpermit_required by @inquinim e80d3d5 +* Add try/except and timeout to version checking with exception handles by @ifrit98 a6a89fd +* Further updates CONTRIBUTING.md and DEVELOPMENT_WORKFLOW.md by @gitphantomman 3fefdbb +* Adds automatic compatibility checks to circleci for all major python3 supported versions. add checks by @ifrit98 #1484 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.3.3...v5.3.4 + + +## 5.3.3 / 2023-07-26 + +## What's Changed +* Remove datasets requirement by @camfairchild in 2eabf0002b01 +* Relax bittensor-* requirements by @camfairchild in da9300ba5b2 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.3.2...v5.3.3 + + +## 5.3.2 / 2023-07-25 + +## What's Changed +* Btlm miner by @shibshib in https://github.com/opentensor/bittensor/pull/1463 +* Don't finalize set_weights ext by @camfairchild in https://github.com/opentensor/bittensor/pull/1461 +* Faster overview pull by @camfairchild in https://github.com/opentensor/bittensor/pull/1464 +* Contrib revamp by @ifrit98 in https://github.com/opentensor/bittensor/pull/1456 +* fix torch typehint on some neurons BT-1329 by @camfairchild in https://github.com/opentensor/bittensor/pull/1460 +* bump bittensor-wallet version to 0.0.5 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.3.1...v5.3.2 + + +## 5.3.1 / 2023-07-06 + + ## What's Changed + * bump bittensor-wallet req, update cryptography security req by @@ifrit98 in [91d13b0](https://github.com/opentensor/bittensor/commit/91d13b0fa711621cbf823708d4368b1b387e42c4) + * Fixes Discord Link Issue #1442 by @camfairchild in [54d6248](https://github.com/opentensor/bittensor/commit/54d62487d4cb59e0b5edcd53acdca013108d155b) + * move mocks to bittensor_wallet package by @camfairchild in https://github.com/opentensor/bittensor/pull/1441 + * Bump bittensor-wallet version to 0.0.4 + + **Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.3.0...v5.3.1 + +## 5.3.0 / 2023-07-04 + +## What's Changed +* [BIT-351] Ask for wallet name on btcli unstake by @camfairchild in https://github.com/opentensor/bittensor/pull/1387 +* Fix tests using pure-Python MockSubtensor by @camfairchild in https://github.com/opentensor/bittensor/pull/1349 +* Update README.md by @mostimasblunderbuss in https://github.com/opentensor/bittensor/pull/1397 +* Update authint version by @ifrit98 in https://github.com/opentensor/bittensor/pull/1395 +* Fix subtensor factory integration test by @camfairchild in https://github.com/opentensor/bittensor/pull/1400 +* Remove neurons by @ifrit98 in https://github.com/opentensor/bittensor/pull/1389 +* Merge pull request #1394 from opentensor/fix_axon_requests by @ifrit98 in https://github.com/opentensor/bittensor/pull/1406 +* remove hotkey from proto and dendrite by @ifrit98 in https://github.com/opentensor/bittensor/pull/1407 +* Weight Utils fix by @mrseeker in https://github.com/opentensor/bittensor/pull/1372 +* Extract config to new package by @camfairchild in https://github.com/opentensor/bittensor/pull/1401 +* Extract wallet by @camfairchild in https://github.com/opentensor/bittensor/pull/1403 +* BTCli integration with new governance protocol by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1398 +* Reverting unnecessary commits for next release. by @camfairchild in https://github.com/opentensor/bittensor/pull/1415 +* Extract wallet and config by @camfairchild in https://github.com/opentensor/bittensor/pull/1411 + +## New Contributors +* @mostimasblunderbuss made their first contribution in https://github.com/opentensor/bittensor/pull/1397 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.2.0...v5.3.0 + + +## 5.2.0 / 2023-06-28 + +## What's Changed +* add default 1024 max stake limit for querying UIDs with vpermit. by @ifrit98 in https://github.com/opentensor/bittensor/pull/1379 +* Fixes validator permit issue seen on master by @unconst in https://github.com/opentensor/bittensor/pull/1381 +* Added conda environment by @shibshib in https://github.com/opentensor/bittensor/pull/1386 +* Update package requirements (hotfix) by @ifrit98 in https://github.com/opentensor/bittensor/pull/1385 +* Merge master into new_staging by @ifrit98 in https://github.com/opentensor/bittensor/pull/1388 +* Fix axon requests signature using metadata by @unconst in https://github.com/opentensor/bittensor/pull/1394 +* Governance Protocol Release by @Rubberbandits in https://github.com/opentensor/bittensor/pull/1414 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.1.0...v5.2.0 + + +## 5.1.0 / 2023-05-30 + +## What's Changed +* update readme by @unconst in https://github.com/opentensor/bittensor/pull/1344 +* Reset scores for validators by @adriansmares in https://github.com/opentensor/bittensor/pull/1359 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v5.0.0...v5.1.0 + + +## 5.0.0 / 2023-05-17 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v4.0.1...v5.0.0 + + +## 4.0.1 / 2023-04-21 + +* Fix btcli my_delegates bug by @camfairchild in ef32a4da0d0827ab5977af1454d66ffe97cbc572 +* Fix endpoint protocol check bug by @camfairchild and @Eugene-hu in https://github.com/opentensor/bittensor/pull/1296 +* Fix changelog script and perms by @camfairchild in f5e7f1e9e9717d229fdec6875fdb9a3051c4bd6b and 1aed09a162ef0fe4d9def2faf261b15dc4c1fa8d + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v4.0.0...v4.0.1 + + +## 4.0.0 / 2023-04-20 + +## What's Changed +* add mnrv-ai to delegates.json by @SFuller4 in https://github.com/opentensor/bittensor/pull/1226 +* Update delegates list by @adriansmares in https://github.com/opentensor/bittensor/pull/1225 +* Update delegates.json by @whiterhinoTAO in https://github.com/opentensor/bittensor/pull/1230 +* Hotfix - Cli unstake fix by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1233 +* Fix permissions for release github script by @eduardogr in https://github.com/opentensor/bittensor/pull/1224 +* Staging into Release branch by @camfairchild in https://github.com/opentensor/bittensor/pull/1275 +* Remove codecov by @camfairchild in https://github.com/opentensor/bittensor/pull/1282 +* Use alt new preseal by @camfairchild in https://github.com/opentensor/bittensor/pull/1269 + +## New Contributors +* @SFuller4 made their first contribution in https://github.com/opentensor/bittensor/pull/1226 +* @whiterhinoTAO made their first contribution in https://github.com/opentensor/bittensor/pull/1230 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.7.0...v4.0.0 + + +## 3.6.3 / 2023-01-21 + +## What's Changed +* [hotfix][3.6.3] Fixing no version checking by @eduardogr in https://github.com/opentensor/bittensor/pull/1063 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.6.2...v3.6.3 + + +## 3.6.2 / 2023-01-19 + +## What's Changed +* Hotfix/3.6.2/validator logit parameters by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1057 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.6.1...v3.6.2 + + +## 3.6.1 / 2022-12-21 + +## What's Changed +* V3.6.0 nobunaga merge by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1028 +* Integration dendrite test fixes by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1029 +* Adding 3.6.0 release notes to CHANGELOG by @eduardogr in https://github.com/opentensor/bittensor/pull/1032 +* [BIT-612] Validator robustness improvements by @opentaco in https://github.com/opentensor/bittensor/pull/1034 +* [Hotfix 3.6.1] Validator robustness by @opentaco in https://github.com/opentensor/bittensor/pull/1035 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.6.0...v3.6.1 + + +## 3.6.0 / 2022-12-13 + +## What's Changed +* Removal of dendrite multiprocessing by @Eugene-hu in https://github.com/opentensor/bittensor/pull/1017 +* Merging back 3.5.1 fix to nobunaga by @eduardogr in https://github.com/opentensor/bittensor/pull/1018 +* Release/3.5.0 post release by @eduardogr in https://github.com/opentensor/bittensor/pull/1010 +* Fixes issue with --neuron.no_set_weights by @camfairchild in https://github.com/opentensor/bittensor/pull/1020 +* Removing GitHub workflow push docker by @eduardogr in https://github.com/opentensor/bittensor/pull/1011 +* [Fix] fix max stake for single by @camfairchild in https://github.com/opentensor/bittensor/pull/996 +* [Feature] mention balance if not no prompt by @camfairchild in https://github.com/opentensor/bittensor/pull/995 +* Add signature v2 format by @adriansmares in https://github.com/opentensor/bittensor/pull/983 +* Improving the way we manage requirements by @eduardogr in https://github.com/opentensor/bittensor/pull/1003 +* [BIT-601] Scaling law on EMA loss by @opentaco in https://github.com/opentensor/bittensor/pull/1022 +* [BIT-602] Update scaling power from subtensor by @opentaco in https://github.com/opentensor/bittensor/pull/1027 +* Release 3.6.0 by @eduardogr in https://github.com/opentensor/bittensor/pull/1023 + +## New Contributors +* @adriansmares made their first contribution in https://github.com/opentensor/bittensor/pull/976 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.5.1...v3.6.0 + + +## 3.5.1 / 2022-11-24 + +## What's Changed +* [hotfix] pin scalecodec lower by @camfairchild in https://github.com/opentensor/bittensor/pull/1013 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.5.0...v3.5.1 + +## 3.5.0 / 2022-11-24 + +## What's Changed + +- [Fix] allow synapse all (https://github.com/opentensor/bittensor/pull/988) + - allow set synapse All using flag + - add test + - use dot get + +- [Feature] Mark registration threads as daemons (https://github.com/opentensor/bittensor/pull/998) + - make solver processes daemons + +- [Feature] Validator debug response table (https://github.com/opentensor/bittensor/pull/999) + - Add response table to validator debugging + +- [Feature] Validator weight setting improvements (https://github.com/opentensor/bittensor/pull/1000) + - Remove responsive prioritization from validator weight calculation + - Move metagraph_sync just before weight setting + - Add metagraph register to validator + - Update validator epoch conditions + - Log epoch while condition details + - Consume validator nucleus UID queue fully + - Increase synergy table display precision + - Round before casting to int in phrase_cross_entropy +- small fix for changelog and version by @Eugene-hu in https://github.com/opentensor/bittensor/pull/993 +- release/3.5.0 by @eduardogr in https://github.com/opentensor/bittensor/pull/1006 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.4.3...v3.5.0 + + +## 3.4.3 / 2022-11-15 + +## What's Changed +* [Hotfix] Synapse security update by @opentaco in https://github.com/opentensor/bittensor/pull/991 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.4.2...v3.4.3 + +## 3.4.2 / 2022-11-09 + +## What's Changed +* Adding 3.4.0 changelog to CHANGELOG.md by @eduardogr in https://github.com/opentensor/bittensor/pull/953 +* Release 3.4.2 by @unconst in https://github.com/opentensor/bittensor/pull/970 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.4.1...v3.4.2 + +## 3.4.1 / 2022-10-13 + +## What's Changed +* [Hotfix] Fix CUDA Reg update block by @camfairchild in https://github.com/opentensor/bittensor/pull/954 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.4.0...v3.4.1 + +## 3.4.0 / 2022-10-13 + +## What's Changed +* Parameters update by @Eugene-hu #936 +* Bittensor Generate by @unconst #941 +* Prometheus by @unconst #928 +* [Tooling][Release] Adding release script by @eduardogr in https://github.com/opentensor/bittensor/pull/948 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.3.4...v3.4.0 + + +## 3.3.4 / 2022-10-03 + +### What's Changed +* [hot-fix] fix indent again. add test by @camfairchild in https://github.com/opentensor/bittensor/pull/907 +* Delete old gitbooks by @quac88 in https://github.com/opentensor/bittensor/pull/924 +* Release/3.3.4 by @Eugene-hu in https://github.com/opentensor/bittensor/pull/927 + +### New Contributors +* @quac88 made their first contribution in https://github.com/opentensor/bittensor/pull/924 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.3.3...v3.3.4 + + +## 3.3.3 / 2022-09-06 + +### What's Changed +* [feature] cpu register faster by @camfairchild in https://github.com/opentensor/bittensor/pull/854 +* [hotfix] fix flags for multiproc register limit by @camfairchild in https://github.com/opentensor/bittensor/pull/876 +* Fix/diff unpack bit shift by @camfairchild in https://github.com/opentensor/bittensor/pull/878 +* [Feature] [cubit] CUDA registration solver by @camfairchild in https://github.com/opentensor/bittensor/pull/868 +* Fix/move overview args to cli by @camfairchild in https://github.com/opentensor/bittensor/pull/867 +* Add/address CUDA reg changes by @camfairchild in https://github.com/opentensor/bittensor/pull/879 +* [Fix] --help command by @camfairchild in https://github.com/opentensor/bittensor/pull/884 +* Validator hotfix min allowed weights by @Eugene-hu in https://github.com/opentensor/bittensor/pull/885 +* [BIT-552] Validator improvements (nucleus permute, synergy avg) by @opentaco in https://github.com/opentensor/bittensor/pull/889 +* Bit 553 bug fixes by @isabella618033 in https://github.com/opentensor/bittensor/pull/886 +* add check to add ws:// if needed by @camfairchild in https://github.com/opentensor/bittensor/pull/896 +* [BIT-572] Exclude lowest quantile from weight setting by @opentaco in https://github.com/opentensor/bittensor/pull/895 +* [BIT-573] Improve validator epoch and responsives handling by @opentaco in https://github.com/opentensor/bittensor/pull/901 +* Nobunaga Release V3.3.3 by @Eugene-hu in https://github.com/opentensor/bittensor/pull/899 + + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.3.2...v3.3.3 + +## 3.3.2 / 2022-08-18 + +### SynapseType fix in dendrite +### What's Changed +* SynapseType fix in dendrite by @robertalanm in https://github.com/opentensor/bittensor/pull/874 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.3.1...v3.3.2 + +## 3.3.1 / 2022-08-17 + +### What's Changed +* [hotfix] Fix GPU reg bug. bad indent by @camfairchild in https://github.com/opentensor/bittensor/pull/883 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.3.0...v3.3.1 + +## 3.3.0 / 2022-08-16 + +### CUDA registration +This release adds the ability to complete the registration using a CUDA-capable device. +See https://github.com/opentensor/cubit/releases/tag/v1.0.5 for the required `cubit` v1.0.5 release + +Also a few bug fixes for the CLI + +### What's Changed +* [hotfix] fix flags for run command, fix hotkeys flag for overview, and [feature] CUDA reg by @camfairchild in https://github.com/opentensor/bittensor/pull/877 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.2.0...v3.3.0 + +## 3.2.0 / 2022-08-12 + +### Validator saving and responsive-priority weight-setting + +### What's Changed +* [BIT-540] Choose responsive UIDs for setting weights in validator + validator save/load by @opentaco in https://github.com/opentensor/bittensor/pull/872 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.1.0...v3.2.0 + +## 3.1.0 / 2022-08-11 + +### Optimizing multi-processed CPU registration +This release refactors the registration code for CPU registration to improve solving performance. + +### What's Changed +* [feature] cpu register faster (#854) by @camfairchild in https://github.com/opentensor/bittensor/pull/875 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v3.0.0...v3.1.0 + +## 3.0.0 / 2022-08-08 + +### Synapse update + +## + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..5a355b5cf6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,40 @@ +# syntax=docker/dockerfile:1 +FROM python:3.11.8-bookworm + +LABEL bittensor.image.authors="bittensor.com" \ + bittensor.image.vendor="Bittensor" \ + bittensor.image.title="bittensor/bittensor" \ + bittensor.image.description="Bittensor: Incentivized Peer to Peer Neural Networks" \ + bittensor.image.source="https://github.com/opentensor/bittensor.git" \ + bittensor.image.revision="${VCS_REF}" \ + bittensor.image.created="${BUILD_DATE}" \ + bittensor.image.documentation="https://app.gitbook.com/@opentensor/s/bittensor/" +ARG DEBIAN_FRONTEND=noninteractive + +# Update the base image +RUN apt update && apt upgrade -y +# Install bittensor +## Install dependencies +RUN apt install -y curl sudo nano git htop netcat-openbsd wget unzip tmux apt-utils cmake build-essential +## Upgrade pip +RUN pip3 install --upgrade pip + +# Install nvm and pm2 +RUN curl -o install_nvm.sh https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh && \ + echo 'fabc489b39a5e9c999c7cab4d281cdbbcbad10ec2f8b9a7f7144ad701b6bfdc7 install_nvm.sh' | sha256sum --check && \ + bash install_nvm.sh + +RUN bash -c "source $HOME/.nvm/nvm.sh && \ + # use node 16 + nvm install 16 && \ + # install pm2 + npm install --location=global pm2" + +RUN mkdir -p /root/.bittensor/bittensor +COPY . /root/.bittensor/bittensor +RUN cd /root/.bittensor/bittensor && python3 -m pip install . + +# Increase ulimit to 1,000,000 +RUN prlimit --pid=$PPID --nofile=1000000 + +EXPOSE 8091 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..8d10866d56 --- /dev/null +++ b/LICENSE @@ -0,0 +1,16 @@ +The MIT License (MIT) +Copyright © 2021 Yuma Rao + +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. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..344c3e4184 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +SHELL:=/bin/bash + +init-venv: + python3 -m venv venv && source ./venv/bin/activate + +clean-venv: + source ./venv/bin/activate && \ + pip freeze > make_venv_to_uninstall.txt && \ + pip uninstall -r make_venv_to_uninstall.txt && \ + rm make_venv_to_uninstall.txt + +clean: + rm -rf dist/ && \ + rm -rf build/ && \ + rm -rf bittensor.egg-info/ && \ + rm -rf .pytest_cache/ && \ + rm -rf lib/ + +install: + python3 -m pip install . + +install-dev: + python3 -m pip install '.[dev]' + +install-cubit: + python3 -m pip install '.[cubit]' \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000..541b8ec6bb --- /dev/null +++ b/README.md @@ -0,0 +1,245 @@ +
+ +# **Bittensor SDK** +[![Discord Chat](https://img.shields.io/discord/308323056592486420.svg)](https://discord.gg/bittensor) +[![PyPI version](https://badge.fury.io/py/bittensor.svg)](https://badge.fury.io/py/bittensor) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +--- + +## Internet-scale Neural Networks + +[Discord](https://discord.gg/qasY3HA9F9) • [Network](https://taostats.io/) • [Research](https://bittensor.com/whitepaper) + +
+ +- [Overview of Bittensor](#overview-of-bittensor) +- [The Bittensor SDK](#the-bittensor-sdk) +- [Is Bittensor a blockchain or an AI platform?](#is-bittensor-a-blockchain-or-an-ai-platform) +- [Subnets](#subnets) +- [Subnet validators and subnet miners](#subnet-validators-and-subnet-miners) +- [Yuma Consensus](#yuma-consensus) +- [Release Notes](#release-notes) +- [Install Bittensor SDK](#install-bittensor-sdk) +- [Upgrade](#upgrade) +- [Install on macOS and Linux](#install-on-macos-and-linux) + - [Install using a Bash command](#install-using-a-bash-command) + - [Install using `pip3 install`](#install-using-pip3-install) + - [Install from source](#install-from-source) + - [Verify using Python interpreter](#verify-using-python-interpreter) + - [Verify by listing axon information](#verify-by-listing-axon-information) +- [Release Guidelines](#release-guidelines) +- [Contributions](#contributions) +- [License](#license) +- [Acknowledgments](#acknowledgments) + +--- + +## Overview of Bittensor + +Welcome! Bittensor is an open source platform on which you can produce competitive digital commodities. These digital commodities can be machine intelligence, storage space, compute power, protein folding, financial markets prediction, and many more. You are rewarded in **TAO** when you produce best digital commodities. + +## The Bittensor SDK + +The Opentensor Foundation (OTF) provides all the open source tools, including this Bittensor SDK, the codebase and the documentation, with step-by-step tutorials and guides, to enable you to participate in the Bittensor ecosystem. + +- **Developer documentation**: https://docs.bittensor.com. +- **A Beginner's Q and A on Bittensor**: https://docs.bittensor.com/questions-and-answers. +- **Bittensor whitepaper**: https://bittensor.com/whitepaper. + +This Bittensor SDK contains ready-to-use Python packages for interacting with the Bittensor ecosystem, writing subnet incentive mechanisms, subnet miners, subnet validators and querying the subtensor (the blockchain part of the Bittensor network). + +--- + +## Is Bittensor a blockchain or an AI platform? + +In Bittensor there is one blockchain, and many platforms that are connected to this one blockchain. We call these platforms as **subnets**, and this one blockchain **subtensor**. So, a subnet can be AI-related or it can be something else. The Bittensor network has a number of distinct subnets. All these subnets interact with subtensor blockchain. If you are thinking, "So, subnets are not part of the blockchain but only interact with it?" then the answer is "yes, exactly." + +## Subnets + +Each category of the digital commodity is produced in a distinct subnet. Applications are built on these specific subnets. End-users of these applications would be served by these applications. + +## Subnet validators and subnet miners + +Subnets, which exist outside the blockchain and are connected to it, are off-chain competitions where only the best producers are rewarded. A subnet consists of off-chain **subnet validators** who initiate the competition for a specific digital commodity, and off-chain **subnet miners** who compete and respond by producing the best quality digital commodity. + +## Yuma Consensus + +Scores are assigned to the top-performing subnet miners and subnet validators. The on-chain Yuma Consensus determines the TAO rewards for these top performers. The Bittensor blockchain, the subtensor, runs on decentralized validation nodes, just like any blockchain. + +**This SDK repo is for Bittensor platform only** +This Bittensor SDK codebase is for the Bittensor platform only, designed to help developers create subnets and build tools on Bittensor. For subnets and applications, refer to subnet-specific websites, which are maintained by subnet owners. + +## Release Notes + +See [Bittensor SDK Release Notes](https://docs.bittensor.com/bittensor-rel-notes). + +--- + +## Install Bittensor SDK + +Before you can start developing, you must install Bittensor SDK and then create Bittensor wallet. + +## Upgrade + +If you already installed Bittensor SDK, make sure you upgrade to the latest version. Run the below command: + +```bash +python3 -m pip install --upgrade bittensor +``` + +--- + +## Install on macOS and Linux + +You can install Bittensor SDK on your local machine in either of the following ways. **Make sure you verify your installation after you install**: +- [Install using a Bash command](#install-using-a-bash-command). +- [Install using `pip3 install`](#install-using-pip3-install) +- [Install from source](#install-from-source) + +### Install using a Bash command + +This is the most straightforward method. It is recommended for a beginner as it will pre-install requirements like Python, if they are not already present on your machine. Copy and paste the following `bash` command into your terminal: + +```bash +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/opentensor/bittensor/master/scripts/install.sh)" +``` + +**For Ubuntu-Linux users** +If you are using Ubuntu-Linux, the script will prompt for `sudo` access to install all required apt-get packages. + +### Install using `pip3 install` + +```bash +python3 -m venv bt_venv +source bt_venv/bin/activate +pip install bittensor +``` + +### Install from source + +1. Create and activate a virtual environment + + - Create Python virtual environment. Follow [this guide on python.org](https://docs.python.org/3/library/venv.html#creating-virtual-environments). + + - Activate the new environment. Follow [this guide on python.org](https://docs.python.org/3/library/venv.html#how-venvs-work) + +2. Clone the Bittensor SDK repo + +```bash +git clone https://github.com/opentensor/bittensor.git +``` + +3. Install + +You can install using any of the below options: + +- **Install only SDK**: Run the below command to install Bittensor SDK in the above virtual environment. + + ```python + pip install bittensor + ``` + +- **Install SDK with `btcli`**: Install Bittensor SDK with `btcli`. The `btcli` will be installed as an independent tool and its Python package is `bittensor-cli`. + + ```python + pip install bittensor[btcli] + ``` + +- **Install SDK with `torch`**: Install Bittensor SDK with [`torch`](https://pytorch.org/docs/stable/torch.html). + + ```python + pip install bittensor[torch] + ``` + +- **Install SDK with `cubit`**: Install Bittensor SDK with [`cubit`](https://github.com/opentensor/cubit). + + 1. Install `cubit` first. See the [Install](https://github.com/opentensor/cubit?tab=readme-ov-file#install) section. **Only Python 3.9 and 3.10 versions are supported**. + 2. Then install SDK with `pip install bittensor`. + +--- + +## Install on Windows + +To install and run Bittensor SDK on Windows you must install [**WSL 2** (Windows Subsystem for Linux)](https://learn.microsoft.com/en-us/windows/wsl/about) on Windows and select [Ubuntu Linux distribution](https://github.com/ubuntu/WSL/blob/main/docs/guides/install-ubuntu-wsl2.md). + +After you installed the above, follow the same installation steps described above in [Install on macOS and Linux](#install-on-macos-and-linux). + +**ALERT**: **Limited support on Windows** +While wallet transactions like delegating, transfer, registering, staking can be performed on a Windows machine using WSL 2, the mining and validating operations are not recommended and are not supported on Windows machines. + +--- + +## Verify the installation + +You can verify your installation in either of the below ways: + +### Verify using `btsdk` version + +```bash +python3 -m bittensor +``` + +The above command will show you the version of the `btsdk` you just installed. + +### Verify using Python interpreter + +1. Launch the Python interpreter on your terminal. + + ```bash + python3 + ``` +2. Enter the following two lines in the Python interpreter. + + ```python + import bittensor as bt + print( bt.__version__ ) + ``` + The Python interpreter output will look like below: + + ```python + Python 3.11.6 (main, Oct 2 2023, 13:45:54) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin + Type "help", "copyright", "credits" or "license" for more information. + >>> import bittensor as bt + >>> print( bt.__version__ ) + + ``` +You will see the version number you installed in place of ``. + +### Verify by listing axon information + +You can also verify the Bittensor SDK installation by listing the axon information for the neurons. Enter the following lines in the Python interpreter. + +```python +import bittensor +metagraph = bittensor.Metagraph(1) +metagraph.axons[:10] +``` +The Python interpreter output will look like below. + +```bash +[AxonInfo( /ipv4/3.139.80.241:11055, 5GqDsK6SAPyQtG243hbaKTsoeumjQQLhUu8GyrXikPTmxjn7, 5D7u5BTqF3j1XHnizp9oR67GFRr8fBEFhbdnuVQEx91vpfB5, 600 ), AxonInfo( /ipv4/8.222.132.190:5108, 5CwqDkDt1uk2Bngvf8avrapUshGmiUvYZjYa7bfA9Gv9kn1i, 5HQ9eTDorvovKTxBc9RUD22FZHZzpy1KRfaxCnRsT9QhuvR6, 600 ), AxonInfo( /ipv4/34.90.71.181:8091, 5HEo565WAy4Dbq3Sv271SAi7syBSofyfhhwRNjFNSM2gP9M2, 5ChuGqW2cxc5AZJ29z6vyTkTncg75L9ovfp8QN8eB8niSD75, 601 ), AxonInfo( /ipv4/64.247.206.79:8091, 5HK5tp6t2S59DywmHRWPBVJeJ86T61KjurYqeooqj8sREpeN, 5E7W9QXNoW7se7B11vWRMKRCSWkkAu9EYotG5Ci2f9cqV8jn, 601 ), AxonInfo( /ipv4/51.91.30.166:40203, 5EXYcaCdnvnMZbozeknFWbj6aKXojfBi9jUpJYHea68j4q1a, 5CsxoeDvWsQFZJnDCyzxaNKgA8pBJGUJyE1DThH8xU25qUMg, 601 ), AxonInfo( /ipv4/149.137.225.62:8091, 5F4tQyWrhfGVcNhoqeiNsR6KjD4wMZ2kfhLj4oHYuyHbZAc3, 5Ccmf1dJKzGtXX7h17eN72MVMRsFwvYjPVmkXPUaapczECf6, 600 ), AxonInfo( /ipv4/38.147.83.11:8091, 5Hddm3iBFD2GLT5ik7LZnT3XJUnRnN8PoeCFgGQgawUVKNm8, 5DCQw11aUW7bozAKkB8tB5bHqAjiu4F6mVLZBdgJnk8dzUoV, 610 ), AxonInfo( /ipv4/38.147.83.30:41422, 5HNQURvmjjYhTSksi8Wfsw676b4owGwfLR2BFAQzG7H3HhYf, 5EZUTdAbXyLmrs3oiPvfCM19nG6oRs4X7zpgxG5oL1iK4MAh, 610 ), AxonInfo( /ipv4/54.227.25.215:10022, 5DxrZuW8kmkZPKGKp1RBVovaP5zHtPLDHYc5Yu82Z1fWqK5u, 5FhXUSmSZ2ec7ozRSA8Bg3ywmGwrjoLLzsXjNcwmZme2GcSC, 601 ), AxonInfo( /ipv4/52.8.243.76:40033, 5EnZN591jjsKKbt3yBtfGKWHxhxRH9cJonqTKRT5yTRUyNon, 5ChzhHyGmWwEdHjuvAxoUifHEZ6xpUjR67fDd4a42UrPysyB, 601 )] +>>> +``` + +--- + +## Release Guidelines +Instructions for the release manager: [RELEASE_GUIDELINES.md](./contrib/RELEASE_GUIDELINES.md) document. + +## Contributions +Ready to contribute? Read the [contributing guide](./contrib/CONTRIBUTING.md) before making a pull request. + +## License +The MIT License (MIT) +Copyright © 2024 The 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. + + +## Acknowledgments +**learning-at-home/hivemind** diff --git a/VERSION b/VERSION new file mode 100644 index 0000000000..fa5fce04b3 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +8.0.0 \ No newline at end of file diff --git a/bittensor/__init__.py b/bittensor/__init__.py new file mode 100644 index 0000000000..5ddba2abe4 --- /dev/null +++ b/bittensor/__init__.py @@ -0,0 +1,53 @@ +# The MIT License (MIT) +# Copyright © 2024 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 warnings + +from .core.settings import __version__, version_split, DEFAULTS +from .utils.btlogging import logging +from .utils.deprecated import * + + +# Logging helpers. +def trace(on: bool = True): + """ + Enables or disables trace logging. + + Args: + on (bool): If True, enables trace logging. If False, disables trace logging. + """ + logging.set_trace(on) + + +def debug(on: bool = True): + """ + Enables or disables debug logging. + + Args: + on (bool): If True, enables debug logging. If False, disables debug logging. + """ + logging.set_debug(on) + + +def __getattr__(name): + if name == "version_split": + warnings.warn( + "version_split is deprecated and will be removed in future versions. Use __version__ instead.", + DeprecationWarning, + ) + return version_split + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/bittensor/__main__.py b/bittensor/__main__.py new file mode 100644 index 0000000000..05d664c9de --- /dev/null +++ b/bittensor/__main__.py @@ -0,0 +1,21 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from bittensor import __version__ + +if __name__ == "__main__": + print(f"Bittensor SDK version: {__version__}") diff --git a/bittensor/core/__init__.py b/bittensor/core/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/bittensor/core/axon.py b/bittensor/core/axon.py new file mode 100644 index 0000000000..63b79d49c8 --- /dev/null +++ b/bittensor/core/axon.py @@ -0,0 +1,1521 @@ +# The MIT License (MIT) +# Copyright © 2024 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. +"""Create and initialize Axon, which services the forward and backward requests from other neurons.""" + +import argparse +import asyncio +import contextlib +import copy +import inspect +import json +import threading +import time +import traceback +import typing +import uuid +import warnings +from inspect import signature, Signature, Parameter +from typing import Any, Awaitable, Callable, Optional, Tuple + +import uvicorn +from bittensor_wallet import Wallet +from fastapi import APIRouter, Depends, FastAPI +from fastapi.responses import JSONResponse +from fastapi.routing import serialize_response +from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint +from starlette.requests import Request +from starlette.responses import Response +from substrateinterface import Keypair + +from bittensor.core.chain_data import AxonInfo +from bittensor.core.config import Config +from bittensor.core.errors import ( + BlacklistedException, + InvalidRequestNameError, + NotVerifiedException, + PostProcessException, + PriorityException, + SynapseDendriteNoneException, + SynapseException, + SynapseParsingError, + UnknownSynapseError, +) +from bittensor.core.settings import DEFAULTS, version_as_int +from bittensor.core.stream import StreamingSynapse +from bittensor.core.synapse import Synapse, TerminalInfo +from bittensor.core.threadpool import PriorityThreadPoolExecutor +from bittensor.utils import networking +from bittensor.utils.axon_utils import allowed_nonce_window_ns, calculate_diff_seconds +from bittensor.utils.btlogging import logging + +# Just for annotation checker +if typing.TYPE_CHECKING: + from bittensor.core.subtensor import Subtensor + +# Latest version with old style nonce structure (this in not a current SDK version) +V_7_2_0 = 7002000 + + +class FastAPIThreadedServer(uvicorn.Server): + """ + The ``FastAPIThreadedServer`` class is a specialized server implementation for the Axon server in the Bittensor network. + + It extends the functionality of :func:`uvicorn.Server` to run the FastAPI application in a separate thread, allowing the Axon server to handle HTTP requests concurrently and non-blocking. + + This class is designed to facilitate the integration of FastAPI with the Axon's asynchronous architecture, ensuring efficient and scalable handling of network requests. + + Importance and Functionality + Threaded Execution + The class allows the FastAPI application to run in a separate thread, enabling concurrent handling of HTTP requests which is crucial for the performance and scalability of the Axon server. + + Seamless Integration + By running FastAPI in a threaded manner, this class ensures seamless integration of FastAPI's capabilities with the Axon server's asynchronous and multi-threaded architecture. + + Controlled Server Management + The methods start and stop provide controlled management of the server's lifecycle, ensuring that the server can be started and stopped as needed, which is vital for maintaining the Axon server's reliability and availability. + + Signal Handling + Overriding the default signal handlers prevents potential conflicts with the Axon server's main application flow, ensuring stable operation in various network conditions. + + Use Cases + Starting the Server + When the Axon server is initialized, it can use this class to start the FastAPI application in a separate thread, enabling it to begin handling HTTP requests immediately. + + Stopping the Server + During shutdown or maintenance of the Axon server, this class can be used to stop the FastAPI application gracefully, ensuring that all resources are properly released. + + Example Usage:: + + self.app = FastAPI() + log_level = "trace" + self.fast_config = uvicorn.Config(self.app, host="0.0.0.0", port=self.config.axon.port, log_level=log_level) + self.fast_server = FastAPIThreadedServer(config=self.fast_config) + self.fast_server.start() + # do something + self.fast_server.stop() + + Args: + should_exit (bool): Flag to indicate whether the server should stop running. + is_running (bool): Flag to indicate whether the server is currently running. + + The server overrides the default signal handlers to prevent interference with the main application flow and provides methods to start and stop the server in a controlled manner. + """ + + should_exit: bool = False + is_running: bool = False + + def install_signal_handlers(self): + """ + Overrides the default signal handlers provided by ``uvicorn.Server``. This method is essential to ensure that the signal handling in the threaded server does not interfere with the main application's flow, especially in a complex asynchronous environment like the Axon server. + """ + + @contextlib.contextmanager + def run_in_thread(self): + """ + Manages the execution of the server in a separate thread, allowing the FastAPI application to run asynchronously without blocking the main thread of the Axon server. This method is a key component in enabling concurrent request handling in the Axon server. + + Yields: + None: This method yields control back to the caller while the server is running in the background thread. + """ + thread = threading.Thread(target=self.run, daemon=True) + thread.start() + try: + while not self.started: + time.sleep(1e-3) + yield + finally: + self.should_exit = True + thread.join() + + def _wrapper_run(self): + """ + A wrapper method for the :func:`run_in_thread` context manager. This method is used internally by the ``start`` method to initiate the server's execution in a separate thread. + """ + with self.run_in_thread(): + while not self.should_exit: + time.sleep(1e-3) + + def start(self): + """ + Starts the FastAPI server in a separate thread if it is not already running. This method sets up the server to handle HTTP requests concurrently, enabling the Axon server to efficiently manage incoming network requests. + + The method ensures that the server starts running in a non-blocking manner, allowing the Axon server to continue its other operations seamlessly. + """ + if not self.is_running: + self.should_exit = False + thread = threading.Thread(target=self._wrapper_run, daemon=True) + thread.start() + self.is_running = True + + def stop(self): + """ + Signals the FastAPI server to stop running. This method sets the :func:`should_exit` flag to ``True``, indicating that the server should cease its operations and exit the running thread. + + Stopping the server is essential for controlled shutdowns and resource management in the Axon server, especially during maintenance or when redeploying with updated configurations. + """ + if self.is_running: + self.should_exit = True + + +class Axon: + """ + The ``Axon`` class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network. + + This class is responsible for managing + incoming requests from other neurons and implements various mechanisms to ensure efficient + and secure network interactions. + + An axon relies on a FastAPI router to create endpoints for different message types. These + endpoints are crucial for handling various request types that a neuron might receive. The + class is designed to be flexible and customizable, allowing users to specify custom rules + for forwarding, blacklisting, prioritizing, and verifying incoming requests. The class also + includes internal mechanisms to manage a thread pool, supporting concurrent handling of + requests with defined priority levels. + + Methods in this class are equipped to deal with incoming requests from various scenarios in the + network and serve as the server face for a neuron. It accepts multiple arguments, like wallet, + configuration parameters, ip address, server binding port, external ip, external port and max + workers. Key methods involve managing and operating the FastAPI application router, including + the attachment and operation of endpoints. + + Key Features: + + - FastAPI router integration for endpoint creation and management. + - Customizable request handling including forwarding, blacklisting, and prioritization. + - Verification of incoming requests against custom-defined functions. + - Thread pool management for concurrent request handling. + - Command-line argument support for user-friendly program interaction. + + Example Usage:: + + import bittensor + # Define your custom synapse class + class MySynapse( bittensor.Synapse ): + input: int = 1 + output: int = None + + # Define a custom request forwarding function using your synapse class + def forward( synapse: MySynapse ) -> MySynapse: + # Apply custom logic to synapse and return it + synapse.output = 2 + return synapse + + # Define a custom request verification function + def verify_my_synapse( synapse: MySynapse ): + # Apply custom verification logic to synapse + # Optionally raise Exception + assert synapse.input == 1 + ... + + # Define a custom request blacklist function + def blacklist_my_synapse( synapse: MySynapse ) -> bool: + # Apply custom blacklist + return False ( if non blacklisted ) or True ( if blacklisted ) + + # Define a custom request priority function + def prioritize_my_synapse( synapse: MySynapse ) -> float: + # Apply custom priority + return 1.0 + + # Initialize Axon object with a custom configuration + my_axon = bittensor.Axon( + config=my_config, + wallet=my_wallet, + port=9090, + ip="192.0.2.0", + external_ip="203.0.113.0", + external_port=7070 + ) + + # Attach the endpoint with the specified verification and forward functions. + my_axon.attach( + forward_fn = forward_my_synapse, + verify_fn = verify_my_synapse, + blacklist_fn = blacklist_my_synapse, + priority_fn = prioritize_my_synapse + ) + + # Serve and start your axon. + my_axon.serve( + netuid = ... + subtensor = ... + ).start() + + # If you have multiple forwarding functions, you can chain attach them. + my_axon.attach( + forward_fn = forward_my_synapse, + verify_fn = verify_my_synapse, + blacklist_fn = blacklist_my_synapse, + priority_fn = prioritize_my_synapse + ).attach( + forward_fn = forward_my_synapse_2, + verify_fn = verify_my_synapse_2, + blacklist_fn = blacklist_my_synapse_2, + priority_fn = prioritize_my_synapse_2 + ).serve( + netuid = ... + subtensor = ... + ).start() + + Args: + wallet (Optional[bittensor_wallet.Wallet]): Wallet with hotkey and coldkeypub. + config (Optional[bittensor.core.config.Config]): Configuration parameters for the axon. + port (Optional[int]): Port for server binding. + ip (Optional[str]): Binding IP address. + external_ip (Optional[str]): External IP address to broadcast. + external_port (Optional[int]): External port to broadcast. + max_workers (Optional[int]): Number of active threads for request handling. + + Returns: + bittensor.core.axon.Axon: An instance of the axon class configured as per the provided arguments. + + 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. + """ + + def __init__( + self, + wallet: Optional["Wallet"] = None, + config: Optional["Config"] = None, + port: Optional[int] = None, + ip: Optional[str] = None, + external_ip: Optional[str] = None, + external_port: Optional[int] = None, + max_workers: Optional[int] = None, + ): + """Creates a new bittensor.Axon object from passed arguments. + + Args: + config (:obj:`Optional[bittensor.core.config.Config]`): bittensor.Axon.config() + wallet (:obj:`Optional[bittensor_wallet.Wallet]`): bittensor wallet with hotkey and coldkeypub. + port (:type:`Optional[int]`): Binding port. + ip (:type:`Optional[str]`): Binding ip. + external_ip (:type:`Optional[str]`): The external ip of the server to broadcast to the network. + external_port (:type:`Optional[int]`): The external port of the server to broadcast to the network. + max_workers (:type:`Optional[int]`): Used to create the threadpool if not passed, specifies the number of active threads servicing requests. + """ + # Build and check config. + if config is None: + config = Axon.config() + config = copy.deepcopy(config) + config.axon.ip = ip or DEFAULTS.axon.ip + config.axon.port = port or DEFAULTS.axon.port + config.axon.external_ip = external_ip or DEFAULTS.axon.external_ip + config.axon.external_port = external_port or DEFAULTS.axon.external_port + config.axon.max_workers = max_workers or DEFAULTS.axon.max_workers + Axon.check_config(config) + self.config = config # type: ignore + + # Get wallet or use default. + self.wallet = wallet or Wallet() + + # Build axon objects. + self.uuid = str(uuid.uuid1()) + self.ip = self.config.axon.ip # type: ignore + self.port = self.config.axon.port # type: ignore + self.external_ip = ( + self.config.axon.external_ip # type: ignore + if self.config.axon.external_ip is not None # type: ignore + else networking.get_external_ip() + ) + self.external_port = ( + self.config.axon.external_port # type: ignore + if self.config.axon.external_port is not None # type: ignore + else self.config.axon.port # type: ignore + ) + self.full_address = str(self.config.axon.ip) + ":" + str(self.config.axon.port) # type: ignore + self.started = False + + # Build middleware + self.thread_pool = PriorityThreadPoolExecutor( + max_workers=self.config.axon.max_workers # type: ignore + ) + self.nonces: dict[str, int] = {} + + # Request default functions. + self.forward_class_types: dict[str, list[Signature]] = {} + self.blacklist_fns: dict[str, Optional[Callable]] = {} + self.priority_fns: dict[str, Optional[Callable]] = {} + self.forward_fns: dict[str, Optional[Callable]] = {} + self.verify_fns: dict[str, Optional[Callable]] = {} + + # Instantiate FastAPI + self.app = FastAPI() + log_level = "trace" if logging.__trace_on__ else "critical" + self.fast_config = uvicorn.Config( + self.app, host="0.0.0.0", port=self.config.axon.port, log_level=log_level + ) + self.fast_server = FastAPIThreadedServer(config=self.fast_config) + self.router = APIRouter() + self.app.include_router(self.router) + + # Build ourselves as the middleware. + self.middleware_cls = AxonMiddleware + self.app.add_middleware(self.middleware_cls, axon=self) + + # Attach default forward. + def ping(r: Synapse) -> Synapse: + return r + + self.attach( + forward_fn=ping, verify_fn=None, blacklist_fn=None, priority_fn=None + ) + + def info(self) -> "AxonInfo": + """Returns the axon info object associated with this axon.""" + return AxonInfo( + version=version_as_int, + ip=self.external_ip, + ip_type=networking.ip_version(self.external_ip), + port=self.external_port, + hotkey=self.wallet.hotkey.ss58_address, + coldkey=self.wallet.coldkeypub.ss58_address, + protocol=4, + placeholder1=0, + placeholder2=0, + ) + + def attach( + self, + forward_fn: Callable, + blacklist_fn: Optional[Callable] = None, + priority_fn: Optional[Callable] = None, + verify_fn: Optional[Callable] = None, + ) -> "Axon": + """ + + 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 :func:`forward_fn` function as the endpoint name. + + The :func:`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. + + Args: + forward_fn (Callable): Function to be called when the API endpoint is accessed. It should have at least one argument. + blacklist_fn (Optional[Callable]): Function to filter out undesired requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. Defaults to ``None``, meaning no blacklist filter will be used. + priority_fn (Optional[Callable]): Function to rank requests based on their priority. It should take the same arguments as :func:`forward_fn` and return a numerical value representing the request's priority. Defaults to ``None``, meaning no priority sorting will be applied. + verify_fn (Optional[Callable]): Function to verify requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. If ``None``, :func:`self.default_verify` function will be used. + + Note: + The methods :func:`forward_fn`, :func:`blacklist_fn`, :func:`priority_fn`, and :func:`verify_fn` should be designed to receive the same parameters. + + Raises: + AssertionError: If :func:`forward_fn` does not have the signature: ``forward( synapse: YourSynapse ) -> synapse``. + AssertionError: If :func:`blacklist_fn` does not have the signature: ``blacklist( synapse: YourSynapse ) -> bool``. + AssertionError: If :func:`priority_fn` does not have the signature: ``priority( synapse: YourSynapse ) -> float``. + AssertionError: If :func:`verify_fn` does not have the signature: ``verify( synapse: YourSynapse ) -> None``. + + Returns: + self: Returns the instance of the AxonServer class for potential method chaining. + + 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 :func:`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. + """ + forward_sig = signature(forward_fn) + try: + first_param = next(iter(forward_sig.parameters.values())) + except StopIteration: + raise ValueError( + "The forward_fn first argument must be a subclass of bittensor.Synapse, but it has no arguments" + ) + + param_class = first_param.annotation + assert issubclass( + param_class, Synapse + ), "The first argument of forward_fn must inherit from bittensor.Synapse" + request_name = param_class.__name__ + + async def endpoint(*args, **kwargs): + start_time = time.time() + response = forward_fn(*args, **kwargs) + if isinstance(response, Awaitable): + response = await response + if isinstance(response, Synapse): + return await self.middleware_cls.synapse_to_response( + synapse=response, start_time=start_time + ) + else: + response_synapse = getattr(response, "synapse", None) + if response_synapse is None: + warnings.warn( + "The response synapse is None. The input synapse will be used as the response synapse. " + "Reliance on forward_fn modifying input synapse as a side-effects is deprecated. " + "Explicitly set `synapse` on response object instead.", + DeprecationWarning, + ) + # Replace with `return response` in next major version + response_synapse = args[0] + + return await self.middleware_cls.synapse_to_response( + synapse=response_synapse, + start_time=start_time, + response_override=response, + ) + + return_annotation = forward_sig.return_annotation + + if isinstance(return_annotation, type) and issubclass( + return_annotation, Synapse + ): + if issubclass( + return_annotation, + StreamingSynapse, + ): + warnings.warn( + "The forward_fn return annotation is a subclass of bittensor.StreamingSynapse. " + "Most likely the correct return annotation would be BTStreamingResponse." + ) + else: + return_annotation = JSONResponse + + endpoint.__signature__ = Signature( # type: ignore + parameters=list(forward_sig.parameters.values()), + return_annotation=return_annotation, + ) + + # Add the endpoint to the router, making it available on both GET and POST methods + self.router.add_api_route( + path=f"/{request_name}", + endpoint=endpoint, + methods=["GET", "POST"], + dependencies=[Depends(self.verify_body_integrity)], + ) + self.app.include_router(self.router) + + # Check the signature of blacklist_fn, priority_fn and verify_fn if they are provided + expected_params = [ + Parameter( + name="synapse", + kind=Parameter.POSITIONAL_OR_KEYWORD, + annotation=forward_sig.parameters[ + list(forward_sig.parameters)[0] + ].annotation, + ) + ] + if blacklist_fn: + blacklist_sig = Signature( + expected_params, return_annotation=Tuple[bool, str] + ) + assert ( + signature(blacklist_fn) == blacklist_sig + ), f"The blacklist_fn function must have the signature: blacklist( synapse: {request_name} ) -> tuple[bool, str]" + if priority_fn: + priority_sig = Signature(expected_params, return_annotation=float) + assert ( + signature(priority_fn) == priority_sig + ), f"The priority_fn function must have the signature: priority( synapse: {request_name} ) -> float" + if verify_fn: + verify_sig = Signature(expected_params, return_annotation=None) + assert ( + signature(verify_fn) == verify_sig + ), f"The verify_fn function must have the signature: verify( synapse: {request_name} ) -> None" + + # Store functions in appropriate attribute dictionaries + self.forward_class_types[request_name] = param_class + self.blacklist_fns[request_name] = blacklist_fn + self.priority_fns[request_name] = priority_fn + self.verify_fns[request_name] = ( + verify_fn or self.default_verify + ) # Use 'default_verify' if 'verify_fn' is None + self.forward_fns[request_name] = forward_fn + + return self + + @classmethod + def config(cls) -> "Config": + """ + Parses the command-line arguments to form a Bittensor configuration object. + + Returns: + bittensor.core.config.Config: Configuration object with settings from command-line arguments. + """ + parser = argparse.ArgumentParser() + Axon.add_args(parser) # Add specific axon-related arguments + return Config(parser, args=[]) + + @classmethod + def help(cls): + """Prints the help text (list of command-line arguments and their descriptions) to stdout.""" + parser = argparse.ArgumentParser() + Axon.add_args(parser) # Add specific axon-related arguments + print(cls.__new__.__doc__) # Print docstring of the class + parser.print_help() # Print parser's help text + + @classmethod + def add_args(cls, parser: argparse.ArgumentParser, prefix: Optional[str] = None): + """ + Adds AxonServer-specific command-line arguments to the argument parser. + + Args: + parser (argparse.ArgumentParser): Argument parser to which the arguments will be added. + prefix (Optional[str]): Prefix to add to the argument names. Defaults to None. + + Note: + Environment variables are used to define default values for the arguments. + """ + prefix_str = "" if prefix is None else prefix + "." + try: + # Add command-line arguments to the parser + parser.add_argument( + "--" + prefix_str + "axon.port", + type=int, + help="The local port this axon endpoint is bound to. i.e. 8091", + default=DEFAULTS.axon.port, + ) + parser.add_argument( + "--" + prefix_str + "axon.ip", + type=str, + help="""The local ip this axon binds to. ie. [::]""", + default=DEFAULTS.axon.ip, + ) + parser.add_argument( + "--" + prefix_str + "axon.external_port", + type=int, + required=False, + help="""The public port this axon broadcasts to the network. i.e. 8091""", + default=DEFAULTS.axon.external_port, + ) + parser.add_argument( + "--" + prefix_str + "axon.external_ip", + type=str, + required=False, + help="""The external ip this axon broadcasts to the network to. ie. [::]""", + default=DEFAULTS.axon.external_ip, + ) + parser.add_argument( + "--" + prefix_str + "axon.max_workers", + type=int, + help="""The maximum number connection handler threads working simultaneously on this endpoint. + The grpc server distributes new worker threads to service requests up to this number.""", + default=DEFAULTS.axon.max_workers, + ) + + except argparse.ArgumentError: + # Exception handling for re-parsing arguments + pass + + async def verify_body_integrity(self, request: "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. + + Args: + request (Request): The incoming FastAPI request object containing both headers and the request body. + + Returns: + dict: 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. + + 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: + + 1. Decoding and loading the request body for inspection. + 2. Gathering required field names for hash comparison from the Axon configuration. + 3. Loading and parsing the request body into a dictionary. + 4. Reconstructing the Synapse object and recomputing the hash for verification and logging. + 5. 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. + """ + # Await and load the request body, so we can inspect it + body = await request.body() + request_body = body.decode() if isinstance(body, bytes) else body + + request_name = request.url.path.split("/")[1] + + # Load the body dict and check if all required field hashes match + body_dict = json.loads(request_body) + + # Reconstruct the synapse object from the body dict and recompute the hash + syn = self.forward_class_types[request_name](**body_dict) # type: ignore + parsed_body_hash = syn.body_hash # Rehash the body from request + + body_hash = request.headers.get("computed_body_hash", "") + if parsed_body_hash != body_hash: + raise ValueError( + f"Hash mismatch between header body hash {body_hash} and parsed body hash {parsed_body_hash}" + ) + + # If body is good, return the parsed body so that it can be passed onto the route function + return body_dict + + @classmethod + def check_config(cls, config: "Config"): + """ + This method checks the configuration for the axon's port and wallet. + + Args: + config (bittensor.core.config.Config): The config object holding axon settings. + + Raises: + AssertionError: If the axon or external ports are not in range [1024, 65535] + """ + assert ( + 1024 < config.axon.port < 65535 + ), "Axon port must be in range [1024, 65535]" + + assert config.axon.external_port is None or ( + 1024 < config.axon.external_port < 65535 + ), "External port must be in range [1024, 65535]" + + def to_string(self): + """Provides a human-readable representation of the AxonInfo for this Axon.""" + return self.info().to_string() + + def __str__(self) -> str: + """Provides a human-readable representation of the Axon instance.""" + _started = "started" if self.started else "stopped" + _keys = list(self.forward_fns.keys()) + return f"Axon({self.ip}, {self.port}, {self.wallet.hotkey.ss58_address}, {_started}, {_keys})" + + def __repr__(self) -> str: + """ + Provides a machine-readable (unambiguous) representation of the Axon instance. + It is made identical to __str__ in this case. + """ + return self.__str__() + + def __del__(self): + """ + This magic method is called when the Axon object is about to be destroyed. + It ensures that the Axon server shuts down properly. + """ + self.stop() + + def start(self) -> "Axon": + """ + 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: + bittensor.core.axon.Axon: The Axon instance in the 'started' state. + + 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. + """ + self.fast_server.start() + self.started = True + return self + + def stop(self) -> "Axon": + """ + 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: + bittensor.core.axon.Axon: The Axon instance in the 'stopped' state. + + 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. + """ + self.fast_server.stop() + self.started = False + return self + + def serve(self, netuid: int, subtensor: Optional["Subtensor"] = None) -> "Axon": + """ + 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. + + Args: + netuid (int): The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology. + subtensor (Optional[bittensor.core.subtensor.Subtensor]): The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations. + + Returns: + bittensor.core.axon.Axon: The Axon instance that is now actively serving on the specified subtensor. + + 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. + """ + if subtensor is not None and hasattr(subtensor, "serve_axon"): + subtensor.serve_axon(netuid=netuid, axon=self) + return self + + async def default_verify(self, synapse: "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 :func:`default_verify` method in the Bittensor framework is a critical security function within the + Axon server. It is designed to authenticate incoming messages by verifying their digital + signatures. This verification ensures the integrity of the message and confirms that it was + indeed sent by the claimed sender. The method plays a pivotal role in maintaining the trustworthiness + and reliability of the communication within the Bittensor network. + + Key Features + Security Assurance + The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access + and data manipulation. + + Preventing Replay Attacks + The method checks for increasing nonce values, which is a vital + step in preventing replay attacks. A replay attack involves an adversary reusing or + delaying the transmission of a valid data transmission to deceive the receiver. + The first time a nonce is seen, it is checked for freshness by ensuring it is + within an acceptable delta time range. + + Authenticity and Integrity Checks + By verifying that the message's digital signature matches + its content, the method ensures the message's authenticity (it comes from the claimed + sender) and integrity (it hasn't been altered during transmission). + + Trust in Communication + This method fosters trust in the network communication. Neurons + (nodes in the Bittensor network) can confidently interact, knowing that the messages they + receive are genuine and have not been tampered with. + + Cryptographic Techniques + The method's reliance on asymmetric encryption techniques is a + cornerstone of modern cryptographic security, ensuring that only entities with the correct + cryptographic keys can participate in secure communication. + + Args: + synapse(bittensor.core.synapse.Synapse): bittensor request synapse. + + Raises: + Exception: If the ``receiver_hotkey`` doesn't match with ``self.receiver_hotkey``. + Exception: If the nonce is not larger than the previous nonce for the same endpoint key. + Exception: If the signature verification fails. + + 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. + """ + # Build the keypair from the dendrite_hotkey + if synapse.dendrite is not None: + keypair = Keypair(ss58_address=synapse.dendrite.hotkey) + + # Build the signature messages. + message = f"{synapse.dendrite.nonce}.{synapse.dendrite.hotkey}.{self.wallet.hotkey.ss58_address}.{synapse.dendrite.uuid}.{synapse.computed_body_hash}" + + # Build the unique endpoint key. + endpoint_key = f"{synapse.dendrite.hotkey}:{synapse.dendrite.uuid}" + + # Requests must have nonces to be safe from replays + if synapse.dendrite.nonce is None: + raise Exception("Missing Nonce") + + # Newer nonce structure post v7.2 + if ( + synapse.dendrite.version is not None + and synapse.dendrite.version >= V_7_2_0 + ): + # If we don't have a nonce stored, ensure that the nonce falls within + # a reasonable delta. + current_time_ns = time.time_ns() + allowed_window_ns = allowed_nonce_window_ns( + current_time_ns, synapse.timeout + ) + + if ( + self.nonces.get(endpoint_key) is None + and synapse.dendrite.nonce <= allowed_window_ns + ): + diff_seconds, allowed_delta_seconds = calculate_diff_seconds( + current_time_ns, synapse.timeout, synapse.dendrite.nonce + ) + raise Exception( + f"Nonce is too old: acceptable delta is {allowed_delta_seconds:.2f} seconds but request was {diff_seconds:.2f} seconds old" + ) + + # If a nonce is stored, ensure the new nonce + # is greater than the previous nonce + if ( + self.nonces.get(endpoint_key) is not None + and synapse.dendrite.nonce <= self.nonces[endpoint_key] + ): + raise Exception("Nonce is too old, a newer one was last processed") + # Older nonce structure pre v7.2 + else: + if ( + self.nonces.get(endpoint_key) is not None + and synapse.dendrite.nonce <= self.nonces[endpoint_key] + ): + raise Exception("Nonce is too old, a newer one was last processed") + + if not keypair.verify(message, synapse.dendrite.signature): + raise Exception( + f"Signature mismatch with {message} and {synapse.dendrite.signature}" + ) + + # Success + self.nonces[endpoint_key] = synapse.dendrite.nonce # type: ignore + else: + raise SynapseDendriteNoneException(synapse=synapse) + + +def create_error_response(synapse: "Synapse") -> "JSONResponse": + """Creates an error response based on the provided synapse object. + + Args: + synapse (bittensor.core.synapse.Synapse): The synapse object containing details about the request and the associated axon. + + Returns: + JSONResponse: A JSON response with a status code and content indicating the error message. + """ + if synapse.axon is None: + return JSONResponse( + status_code=400, + headers=synapse.to_headers(), + content={"message": "Invalid request name"}, + ) + else: + return JSONResponse( + status_code=synapse.axon.status_code or 400, + headers=synapse.to_headers(), + content={"message": synapse.axon.status_message}, + ) + + +def log_and_handle_error( + synapse: "Synapse", + exception: Exception, + status_code: Optional[int] = None, + start_time: Optional[float] = None, +) -> "Synapse": + """ + Logs the error and updates the synapse object with the appropriate error details. + + Args: + synapse (bittensor.core.synapse.Synapse): The synapse object to be updated with error information. + exception (Exception): The exception that was raised and needs to be logged and handled. + status_code (Optional[int]): The HTTP status code to be set on the synapse object. Defaults to None. + start_time (Optional[float]): The timestamp marking the start of the processing, used to calculate process time. Defaults to None. + + Returns: + Synapse: The updated synapse object with error details. + """ + if isinstance(exception, SynapseException): + synapse = exception.synapse or synapse + + logging.trace(f"Forward handled exception: {exception}") + else: + logging.trace(f"Forward exception: {traceback.format_exc()}") + + if synapse.axon is None: + synapse.axon = TerminalInfo() + + # Set the status code of the synapse to the given status code. + error_id = str(uuid.uuid4()) + error_type = exception.__class__.__name__ + + # Log the detailed error message for internal use + logging.error(f"{error_type}#{error_id}: {exception}") + + if not status_code and synapse.axon.status_code != 100: + status_code = synapse.axon.status_code + status_message = synapse.axon.status_message + if isinstance(exception, SynapseException): + if not status_code: + if isinstance(exception, PriorityException): + status_code = 503 + elif isinstance(exception, UnknownSynapseError): + status_code = 404 + elif isinstance(exception, BlacklistedException): + status_code = 403 + elif isinstance(exception, NotVerifiedException): + status_code = 401 + elif isinstance(exception, (InvalidRequestNameError, SynapseParsingError)): + status_code = 400 + else: + status_code = 500 + status_message = status_message or str(exception) + else: + status_code = status_code or 500 + status_message = status_message or f"Internal Server Error #{error_id}" + + # Set a user-friendly error message + synapse.axon.status_code = status_code + synapse.axon.status_message = status_message + + if start_time: + # Calculate the processing time by subtracting the start time from the current time. + synapse.axon.process_time = str(time.time() - start_time) # type: ignore + + return synapse + + +class AxonMiddleware(BaseHTTPMiddleware): + """ + The `AxonMiddleware` class is a key component in the Axon server, responsible for processing all incoming requests. + + It handles the essential tasks of verifying requests, executing blacklist checks, + running priority functions, and managing the logging of messages and errors. Additionally, the class + is responsible for updating the headers of the response and executing the requested functions. + + This middleware acts as an intermediary layer in request handling, ensuring that each request is + processed according to the defined rules and protocols of the Bittensor network. It plays a pivotal + role in maintaining the integrity and security of the network communication. + + Args: + app (FastAPI): An instance of the FastAPI application to which this middleware is attached. + axon (bittensor.core.axon.Axon): The Axon instance that will process the requests. + + The middleware operates by intercepting incoming requests, performing necessary preprocessing + (like verification and priority assessment), executing the request through the Axon's endpoints, and + then handling any postprocessing steps such as response header updating and logging. + """ + + def __init__(self, app: "AxonMiddleware", axon: "Axon"): + """ + Initialize the AxonMiddleware class. + + Args: + app (bittensor.core.axon.AxonMiddleware): An instance of the application where the middleware processor is used. + axon (bittensor.core.axon.Axon): The axon instance used to process the requests. + """ + super().__init__(app) + self.axon = axon + + async def dispatch( + self, request: "Request", call_next: "RequestResponseEndpoint" + ) -> Response: + """ + Asynchronously processes incoming HTTP requests and returns the corresponding responses. This + method acts as the central processing unit of the AxonMiddleware, handling each step in the + request lifecycle. + + Args: + request (Request): The incoming HTTP request to be processed. + call_next (RequestResponseEndpoint): A callable that processes the request and returns a response. + + Returns: + Response: The HTTP response generated after processing the request. + + This method performs several key functions: + + 1. Request Preprocessing: Sets up Synapse object from request headers and fills necessary information. + 2. Logging: Logs the start of request processing. + 3. Blacklist Checking: Verifies if the request is blacklisted. + 4. Request Verification: Ensures the authenticity and integrity of the request. + 5. Priority Assessment: Evaluates and assigns priority to the request. + 6. Request Execution: Calls the next function in the middleware chain to process the request. + 7. Response Postprocessing: Updates response headers and logs the end of the request processing. + + The method also handles exceptions and errors that might occur during each stage, ensuring that + appropriate responses are returned to the client. + """ + # Records the start time of the request processing. + start_time = time.time() + + try: + # Set up the synapse from its headers. + try: + synapse: "Synapse" = await self.preprocess(request) + except Exception as exc: + if isinstance(exc, SynapseException) and exc.synapse is not None: + synapse = exc.synapse + else: + synapse = Synapse() + raise + + # Logs the start of the request processing + if synapse.dendrite is not None: + logging.trace( + f"axon | <-- | {request.headers.get('content-length', -1)} B | {synapse.name} | {synapse.dendrite.hotkey} | {synapse.dendrite.ip}:{synapse.dendrite.port} | 200 | Success " + ) + else: + logging.trace( + f"axon | <-- | {request.headers.get('content-length', -1)} B | {synapse.name} | None | None | 200 | Success " + ) + + # Call the blacklist function + await self.blacklist(synapse) + + # Call verify and return the verified request + await self.verify(synapse) + + # Call the priority function + await self.priority(synapse) + + # Call the run function + response = await self.run(synapse, call_next, request) + + # Handle errors related to preprocess. + except InvalidRequestNameError as e: + if synapse.axon is None: + synapse.axon = TerminalInfo() + synapse.axon.status_code = 400 + synapse.axon.status_message = str(e) + synapse = log_and_handle_error(synapse, e, start_time=start_time) + response = create_error_response(synapse) + + except SynapseException as e: + synapse = e.synapse or synapse + synapse = log_and_handle_error(synapse, e, start_time=start_time) + response = create_error_response(synapse) + + # Handle all other errors. + except Exception as e: + synapse = log_and_handle_error(synapse, e, start_time=start_time) + response = create_error_response(synapse) + + # Logs the end of request processing and returns the response + finally: + # Log the details of the processed synapse, including total size, name, hotkey, IP, port, + # status code, and status message, using the debug level of the logger. + if synapse.dendrite is not None and synapse.axon is not None: + logging.trace( + f"axon | --> | {response.headers.get('content-length', -1)} B | {synapse.name} | {synapse.dendrite.hotkey} | {synapse.dendrite.ip}:{synapse.dendrite.port} | {synapse.axon.status_code} | {synapse.axon.status_message}" + ) + elif synapse.axon is not None: + logging.trace( + f"axon | --> | {response.headers.get('content-length', -1)} B | {synapse.name} | None | None | {synapse.axon.status_code} | {synapse.axon.status_message}" + ) + else: + logging.trace( + f"axon | --> | {response.headers.get('content-length', -1)} B | {synapse.name} | None | None | 200 | Success " + ) + + # Return the response to the requester. + return response + + async def preprocess(self, request: "Request") -> "Synapse": + """ + Performs the initial processing of the incoming request. This method is responsible for + extracting relevant information from the request and setting up the Synapse object, which + represents the state and context of the request within the Axon server. + + Args: + request (Request): The incoming request to be preprocessed. + + Returns: + bittensor.core.synapse.Synapse: The Synapse object representing the preprocessed state of the request. + + The preprocessing involves: + + 1. Extracting the request name from the URL path. + 2. Creating a Synapse instance from the request headers using the appropriate class type. + 3. Filling in the Axon and Dendrite information into the Synapse object. + 4. Signing the Synapse from the Axon side using the wallet hotkey. + + This method sets the foundation for the subsequent steps in the request handling process, + ensuring that all necessary information is encapsulated within the Synapse object. + """ + # Extracts the request name from the URL path. + try: + request_name = request.url.path.split("/")[1] + except Exception: + raise InvalidRequestNameError( + f"Improperly formatted request. Could not parser request {request.url.path}." + ) + + # Creates a synapse instance from the headers using the appropriate forward class type + # based on the request name obtained from the URL path. + request_synapse = self.axon.forward_class_types.get(request_name) + if request_synapse is None: + raise UnknownSynapseError( + f"Synapse name '{request_name}' not found. Available synapses {list(self.axon.forward_class_types.keys())}" + ) + + try: + synapse = request_synapse.from_headers(request.headers) # type: ignore + except Exception: + raise SynapseParsingError( + f"Improperly formatted request. Could not parse headers {request.headers} into synapse of type {request_name}." + ) + synapse.name = request_name + + # Fills the local axon information into the synapse. + synapse.axon.__dict__.update( + { + "version": str(version_as_int), + "uuid": str(self.axon.uuid), + "nonce": time.time_ns(), + "status_code": 100, + } + ) + + # Fills the dendrite information into the synapse. + synapse.dendrite.__dict__.update( + {"port": str(request.client.port), "ip": str(request.client.host)} # type: ignore + ) + + # Signs the synapse from the axon side using the wallet hotkey. + message = f"{synapse.axon.nonce}.{synapse.dendrite.hotkey}.{synapse.axon.hotkey}.{synapse.axon.uuid}" + synapse.axon.signature = f"0x{self.axon.wallet.hotkey.sign(message).hex()}" + + # Return the setup synapse. + return synapse + + async def verify(self, synapse: "Synapse"): + """ + Verifies the authenticity and integrity of the request. This method ensures that the incoming + request meets the predefined security and validation criteria. + + Args: + synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. + + Raises: + Exception: If the verification process fails due to unmet criteria or security concerns. + + The verification process involves: + + 1. Retrieving the specific verification function for the request's Synapse type. + 2. Executing the verification function and handling any exceptions that arise. + + Successful verification allows the request to proceed further in the processing pipeline, while + failure results in an appropriate exception being raised. + """ + # Start of the verification process. Verification is the process where we ensure that + # the incoming request is from a trusted source or fulfills certain requirements. + # We get a specific verification function from 'verify_fns' dictionary that corresponds + # to our request's name. Each request name (synapse name) has its unique verification function. + verify_fn = ( + self.axon.verify_fns.get(synapse.name) if synapse.name is not None else None + ) + + # If a verification function exists for the request's name + if verify_fn: + try: + # We attempt to run the verification function using the synapse instance + # created from the request. If this function runs without throwing an exception, + # it means that the verification was successful. + ( + await verify_fn(synapse) + if inspect.iscoroutinefunction(verify_fn) + else verify_fn(synapse) + ) + except Exception as e: + # If there was an exception during the verification process, we log that + # there was a verification exception. + logging.trace(f"Verify exception {str(e)}") + + # Check if the synapse.axon object exists + if synapse.axon is not None: + # We set the status code of the synapse to "401" which denotes an unauthorized access. + synapse.axon.status_code = 401 + else: + # If the synapse.axon object doesn't exist, raise an exception. + raise Exception("Synapse.axon object is None") + + # We raise an exception to stop the process and return the error to the requester. + # The error message includes the original exception message. + raise NotVerifiedException( + f"Not Verified with error: {str(e)}", synapse=synapse + ) + + async def blacklist(self, synapse: "Synapse"): + """ + Checks if the request should be blacklisted. This method ensures that requests from disallowed + sources or with malicious intent are blocked from processing. This can be extremely useful for + preventing spam or other forms of abuse. The blacklist is a list of keys or identifiers that + are prohibited from accessing certain resources. + + Args: + synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. + + Raises: + Exception: If the request is found in the blacklist. + + The blacklist check involves: + + 1. Retrieving the blacklist checking function for the request's Synapse type. + 2. Executing the check and handling the case where the request is blacklisted. + + If a request is blacklisted, it is blocked, and an exception is raised to halt further processing. + """ + # A blacklist is a list of keys or identifiers + # that are prohibited from accessing certain resources. + # We retrieve the blacklist checking function from the 'blacklist_fns' dictionary + # that corresponds to the request's name (synapse name). + blacklist_fn = ( + self.axon.blacklist_fns.get(synapse.name) + if synapse.name is not None + else None + ) + + # If a blacklist checking function exists for the request's name + if blacklist_fn: + # We execute the blacklist checking function using the synapse instance as input. + # If the function returns True, it means that the key or identifier is blacklisted. + blacklisted, reason = ( + await blacklist_fn(synapse) + if inspect.iscoroutinefunction(blacklist_fn) + else blacklist_fn(synapse) + ) + if blacklisted: + # We log that the key or identifier is blacklisted. + logging.trace(f"Blacklisted: {blacklisted}, {reason}") + + # Check if the synapse.axon object exists + if synapse.axon is not None: + # We set the status code of the synapse to "403" which indicates a forbidden access. + synapse.axon.status_code = 403 + else: + # If the synapse.axon object doesn't exist, raise an exception. + raise Exception("Synapse.axon object is None") + + # We raise an exception to halt the process and return the error message to the requester. + raise BlacklistedException( + f"Forbidden. Key is blacklisted: {reason}.", synapse=synapse + ) + + async def priority(self, synapse: "Synapse"): + """ + Executes the priority function for the request. This method assesses and assigns a priority + level to the request, determining its urgency and importance in the processing queue. + + Args: + synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. + + Raises: + Exception: If the priority assessment process encounters issues, such as timeouts. + + The priority function plays a crucial role in managing the processing load and ensuring that + critical requests are handled promptly. + """ + # Retrieve the priority function from the 'priority_fns' dictionary that corresponds + # to the request's name (synapse name). + priority_fn = self.axon.priority_fns.get(str(synapse.name), None) + + async def submit_task( + executor: "PriorityThreadPoolExecutor", priority: float + ) -> tuple[float, Any]: + """ + Submits the given priority function to the specified executor for asynchronous execution. + The function will run in the provided executor and return the priority value along with the result. + + Args: + executor (bittensor.core.threadpool.PriorityThreadPoolExecutor): The executor in which the priority function will be run. + priority (float): The priority function to be executed. + + Returns: + tuple: A tuple containing the priority value and the result of the priority function execution. + """ + loop = asyncio.get_event_loop() + future = loop.run_in_executor(executor, lambda: priority) + result = await future + return priority, result + + # If a priority function exists for the request's name + if priority_fn: + try: + # Execute the priority function and get the priority value. + priority = ( + await priority_fn(synapse) + if inspect.iscoroutinefunction(priority_fn) + else priority_fn(synapse) + ) + + # Submit the task to the thread pool for execution with the given priority. + # The submit_task function will handle the execution and return the result. + _, result = await submit_task(self.axon.thread_pool, priority) + + except TimeoutError as e: + # If the execution of the priority function exceeds the timeout, + # it raises an exception to handle the timeout error. + logging.trace(f"TimeoutError: {str(e)}") + + # Set the status code of the synapse to 408 which indicates a timeout error. + if synapse.axon is not None: + synapse.axon.status_code = 408 + + # Raise an exception to stop the process and return an appropriate error message to the requester. + raise PriorityException( + f"Response timeout after: {synapse.timeout}s", synapse=synapse + ) + + async def run( + self, + synapse: "Synapse", + call_next: "RequestResponseEndpoint", + request: "Request", + ) -> "Response": + """ + Executes the requested function as part of the request processing pipeline. This method calls + the next function in the middleware chain to process the request and generate a response. + + Args: + synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. + call_next (RequestResponseEndpoint): The next function in the middleware chain to process requests. + request (Request): The original HTTP request. + + Returns: + Response: The HTTP response generated by processing the request. + + This method is a critical part of the request lifecycle, where the actual processing of the + request takes place, leading to the generation of a response. + """ + assert isinstance(synapse, Synapse) + + try: + # The requested function is executed by calling the 'call_next' function, + # passing the original request as an argument. This function processes the request + # and returns the response. + response = await call_next(request) + + except Exception as e: + # Log the exception for debugging purposes. + logging.trace(f"Run exception: {str(e)}") + raise + + # Return the starlet response + return response + + @classmethod + async def synapse_to_response( + cls, + synapse: "Synapse", + start_time: float, + *, + response_override: Optional["Response"] = None, + ) -> "Response": + """ + Converts the Synapse object into a JSON response with HTTP headers. + + Args: + synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. + start_time (float): The timestamp when the request processing started. + response_override: Instead of serializing the synapse, mutate the provided response object. This is only really useful for StreamingSynapse responses. + + Returns: + Response: The final HTTP response, with updated headers, ready to be sent back to the client. + + Postprocessing is the last step in the request handling process, ensuring that the response is + properly formatted and contains all necessary information. + """ + if synapse.axon is None: + synapse.axon = TerminalInfo() + + if synapse.axon.status_code is None: + synapse.axon.status_code = 200 + + if synapse.axon.status_code == 200 and not synapse.axon.status_message: + synapse.axon.status_message = "Success" + + synapse.axon.process_time = time.time() - start_time + + if response_override: + response = response_override + else: + serialized_synapse = await serialize_response(response_content=synapse) + response = JSONResponse( + status_code=synapse.axon.status_code, + content=serialized_synapse, + ) + + try: + updated_headers = synapse.to_headers() + except Exception as e: + raise PostProcessException( + f"Error while parsing response headers. Postprocess exception: {str(e)}.", + synapse=synapse, + ) from e + + try: + response.headers.update(updated_headers) + except Exception as e: + raise PostProcessException( + f"Error while updating response headers. Postprocess exception: {str(e)}.", + synapse=synapse, + ) from e + + return response diff --git a/bittensor/core/chain_data/__init__.py b/bittensor/core/chain_data/__init__.py new file mode 100644 index 0000000000..9ad1e38881 --- /dev/null +++ b/bittensor/core/chain_data/__init__.py @@ -0,0 +1,22 @@ +""" +This module provides data structures and functions for working with the Bittensor network, including neuron and subnet +information, SCALE encoding/decoding, and custom RPC type registry. +""" + +from scalecodec.types import GenericCall + +from .axon_info import AxonInfo +from .delegate_info import DelegateInfo +from .delegate_info_lite import DelegateInfoLite +from .ip_info import IPInfo +from .neuron_info import NeuronInfo +from .neuron_info_lite import NeuronInfoLite +from .prometheus_info import PrometheusInfo +from .proposal_vote_data import ProposalVoteData +from .scheduled_coldkey_swap_info import ScheduledColdkeySwapInfo +from .stake_info import StakeInfo +from .subnet_hyperparameters import SubnetHyperparameters +from .subnet_info import SubnetInfo +from .utils import custom_rpc_type_registry + +ProposalCallData = GenericCall diff --git a/bittensor/core/chain_data/axon_info.py b/bittensor/core/chain_data/axon_info.py new file mode 100644 index 0000000000..eee9cb82a1 --- /dev/null +++ b/bittensor/core/chain_data/axon_info.py @@ -0,0 +1,163 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +This module defines the `AxonInfo` class, a data structure used to represent information about an axon endpoint +in the bittensor network. +""" + +import json +from dataclasses import asdict, dataclass +from typing import Any, Union + +from bittensor.utils import networking +from bittensor.utils.btlogging import logging +from bittensor.utils.registration import torch, use_torch + + +@dataclass +class AxonInfo: + """ + The `AxonInfo` class represents information about an axon endpoint in the bittensor network. This includes + properties such as IP address, ports, and relevant keys. + + Attributes: + version (int): The version of the axon endpoint. + ip (str): The IP address of the axon endpoint. + port (int): The port number the axon endpoint uses. + ip_type (int): The type of IP protocol (e.g., IPv4 or IPv6). + hotkey (str): The hotkey associated with the axon endpoint. + coldkey (str): The coldkey associated with the axon endpoint. + protocol (int): The protocol version (default is 4). + placeholder1 (int): Reserved field (default is 0). + placeholder2 (int): Reserved field (default is 0). + """ + + version: int + ip: str + port: int + ip_type: int + hotkey: str + coldkey: str + protocol: int = 4 + placeholder1: int = 0 + placeholder2: int = 0 + + @property + def is_serving(self) -> bool: + """True if the endpoint is serving.""" + return self.ip != "0.0.0.0" + + def ip_str(self) -> str: + """Return the whole IP as string""" + return networking.ip__str__(self.ip_type, self.ip, self.port) + + def __eq__(self, other: "AxonInfo"): + if other is None: + return False + + if ( + self.version == other.version + and self.ip == other.ip + and self.port == other.port + and self.ip_type == other.ip_type + and self.coldkey == other.coldkey + and self.hotkey == other.hotkey + ): + return True + + return False + + def __str__(self): + return f"AxonInfo( {self.ip_str()}, {self.hotkey}, {self.coldkey}, {self.version} )" + + def __repr__(self): + return self.__str__() + + def to_string(self) -> str: + """Converts the `AxonInfo` object to a string representation using JSON.""" + try: + return json.dumps(asdict(self)) + except (TypeError, ValueError) as e: + logging.error(f"Error converting AxonInfo to string: {e}") + return AxonInfo(0, "", 0, 0, "", "").to_string() + + @classmethod + def from_string(cls, json_string: str) -> "AxonInfo": + """ + Creates an `AxonInfo` object from its string representation using JSON. + + Args: + json_string (str): The JSON string representation of the AxonInfo object. + + Returns: + AxonInfo: An instance of AxonInfo created from the JSON string. If decoding fails, returns a default `AxonInfo` object with default values. + + Raises: + json.JSONDecodeError: If there is an error in decoding the JSON string. + TypeError: If there is a type error when creating the AxonInfo object. + ValueError: If there is a value error when creating the AxonInfo object. + """ + try: + data = json.loads(json_string) + return cls(**data) + except json.JSONDecodeError as e: + logging.error(f"Error decoding JSON: {e}") + except TypeError as e: + logging.error(f"Type error: {e}") + except ValueError as e: + logging.error(f"Value error: {e}") + return AxonInfo(0, "", 0, 0, "", "") + + @classmethod + def from_neuron_info(cls, neuron_info: dict) -> "AxonInfo": + """ + Converts a dictionary to an `AxonInfo` object. + + Args: + neuron_info (dict): A dictionary containing the neuron information. + + Returns: + instance (AxonInfo): An instance of AxonInfo created from the dictionary. + """ + return cls( + version=neuron_info["axon_info"]["version"], + ip=networking.int_to_ip(int(neuron_info["axon_info"]["ip"])), + port=neuron_info["axon_info"]["port"], + ip_type=neuron_info["axon_info"]["ip_type"], + hotkey=neuron_info["hotkey"], + coldkey=neuron_info["coldkey"], + ) + + def to_parameter_dict( + self, + ) -> Union[dict[str, Union[int, str]], "torch.nn.ParameterDict"]: + """Returns a torch tensor or dict of the subnet info, depending on the USE_TORCH flag set.""" + if use_torch(): + return torch.nn.ParameterDict(self.__dict__) + else: + return self.__dict__ + + @classmethod + def from_parameter_dict( + cls, parameter_dict: Union[dict[str, Any], "torch.nn.ParameterDict"] + ) -> "AxonInfo": + """Returns an axon_info object from a torch parameter_dict or a parameter dict.""" + if use_torch(): + return cls(**dict(parameter_dict)) + else: + return cls(**parameter_dict) diff --git a/bittensor/core/chain_data/delegate_info.py b/bittensor/core/chain_data/delegate_info.py new file mode 100644 index 0000000000..d77f1e1412 --- /dev/null +++ b/bittensor/core/chain_data/delegate_info.py @@ -0,0 +1,105 @@ +from dataclasses import dataclass +from typing import Optional, Any + +from scalecodec.utils.ss58 import ss58_encode + +from bittensor.core.chain_data.utils import from_scale_encoding, ChainDataType +from bittensor.core.settings import SS58_FORMAT +from bittensor.utils import u16_normalized_float +from bittensor.utils.balance import Balance + + +@dataclass +class DelegateInfo: + """ + Dataclass for delegate information. For a lighter version of this class, see ``DelegateInfoLite``. + + Args: + hotkey_ss58 (str): Hotkey of the delegate for which the information is being fetched. + total_stake (int): Total stake of the delegate. + nominators (list[tuple[str, int]]): List of nominators of the delegate and their stake. + take (float): Take of the delegate as a percentage. + owner_ss58 (str): Coldkey of the owner. + registrations (list[int]): List of subnets that the delegate is registered on. + validator_permits (list[int]): List of subnets that the delegate is allowed to validate on. + return_per_1000 (int): Return per 1000 TAO, for the delegate over a day. + total_daily_return (int): Total daily return of the delegate. + + """ + + hotkey_ss58: str # Hotkey of delegate + total_stake: Balance # Total stake of the delegate + nominators: list[ + tuple[str, Balance] + ] # List of nominators of the delegate and their stake + owner_ss58: str # Coldkey of owner + take: float # Take of the delegate as a percentage + validator_permits: list[ + int + ] # List of subnets that the delegate is allowed to validate on + registrations: tuple[int] # List of subnets that the delegate is registered on + return_per_1000: Balance # Return per 1000 tao of the delegate over a day + total_daily_return: Balance # Total daily return of the delegate + + @classmethod + def fix_decoded_values(cls, decoded: Any) -> "DelegateInfo": + """Fixes the decoded values.""" + + return cls( + hotkey_ss58=ss58_encode(decoded["delegate_ss58"], SS58_FORMAT), + owner_ss58=ss58_encode(decoded["owner_ss58"], SS58_FORMAT), + take=u16_normalized_float(decoded["take"]), + nominators=[ + ( + ss58_encode(nom[0], SS58_FORMAT), + Balance.from_rao(nom[1]), + ) + for nom in decoded["nominators"] + ], + total_stake=Balance.from_rao( + sum([nom[1] for nom in decoded["nominators"]]) + ), + validator_permits=decoded["validator_permits"], + registrations=decoded["registrations"], + return_per_1000=Balance.from_rao(decoded["return_per_1000"]), + total_daily_return=Balance.from_rao(decoded["total_daily_return"]), + ) + + @classmethod + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["DelegateInfo"]: + """Returns a DelegateInfo object from a ``vec_u8``.""" + if len(vec_u8) == 0: + return None + + decoded = from_scale_encoding(vec_u8, ChainDataType.DelegateInfo) + if decoded is None: + return None + + return DelegateInfo.fix_decoded_values(decoded) + + @classmethod + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["DelegateInfo"]: + """Returns a list of DelegateInfo objects from a ``vec_u8``.""" + decoded = from_scale_encoding(vec_u8, ChainDataType.DelegateInfo, is_vec=True) + + if decoded is None: + return [] + + return [DelegateInfo.fix_decoded_values(d) for d in decoded] + + @classmethod + def delegated_list_from_vec_u8( + cls, vec_u8: list[int] + ) -> list[tuple["DelegateInfo", "Balance"]]: + """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. + """ + decoded = from_scale_encoding(vec_u8, ChainDataType.DelegatedInfo, is_vec=True) + if decoded is None: + return [] + + return [ + (DelegateInfo.fix_decoded_values(d), Balance.from_rao(s)) + for d, s in decoded + ] diff --git a/bittensor/core/chain_data/delegate_info_lite.py b/bittensor/core/chain_data/delegate_info_lite.py new file mode 100644 index 0000000000..bf693c1841 --- /dev/null +++ b/bittensor/core/chain_data/delegate_info_lite.py @@ -0,0 +1,29 @@ +from dataclasses import dataclass + + +@dataclass +class DelegateInfoLite: + """ + Dataclass for `DelegateLiteInfo`. This is a lighter version of :func:``DelegateInfo``. + + Args: + delegate_ss58 (str): Hotkey of the delegate for which the information is being fetched. + take (float): Take of the delegate as a percentage. + nominators (int): Count of the nominators of the delegate. + owner_ss58 (str): Coldkey of the owner. + registrations (list[int]): List of subnets that the delegate is registered on. + validator_permits (list[int]): List of subnets that the delegate is allowed to validate on. + return_per_1000 (int): Return per 1000 TAO, for the delegate over a day. + total_daily_return (int): Total daily return of the delegate. + """ + + delegate_ss58: str # Hotkey of delegate + take: float # Take of the delegate as a percentage + nominators: int # Count of the nominators of the delegate. + owner_ss58: str # Coldkey of owner + registrations: list[int] # List of subnets that the delegate is registered on + validator_permits: list[ + int + ] # List of subnets that the delegate is allowed to validate on + return_per_1000: int # Return per 1000 tao for the delegate over a day + total_daily_return: int # Total daily return of the delegate diff --git a/bittensor/core/chain_data/ip_info.py b/bittensor/core/chain_data/ip_info.py new file mode 100644 index 0000000000..6bbfabe02e --- /dev/null +++ b/bittensor/core/chain_data/ip_info.py @@ -0,0 +1,81 @@ +from dataclasses import dataclass +from typing import Optional, Any, Union + +from bittensor.core.chain_data.utils import from_scale_encoding, ChainDataType +from bittensor.utils import networking as net +from bittensor.utils.registration import torch, use_torch + + +@dataclass +class IPInfo: + """ + Dataclass representing IP information. + + Attributes: + ip (str): The IP address as a string. + ip_type (int): The type of the IP address (e.g., IPv4, IPv6). + protocol (int): The protocol associated with the IP (e.g., TCP, UDP). + """ + + ip: str + ip_type: int + protocol: int + + def encode(self) -> dict[str, Any]: + """Returns a dictionary of the IPInfo object that can be encoded.""" + return { + "ip": net.ip_to_int( + self.ip + ), # IP type and protocol are encoded together as a u8 + "ip_type_and_protocol": ((self.ip_type << 4) + self.protocol) & 0xFF, + } + + @classmethod + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["IPInfo"]: + """Returns a IPInfo object from a ``vec_u8``.""" + if len(vec_u8) == 0: + return None + + decoded = from_scale_encoding(vec_u8, ChainDataType.IPInfo) + if decoded is None: + return None + + return IPInfo.fix_decoded_values(decoded) + + @classmethod + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["IPInfo"]: + """Returns a list of IPInfo objects from a ``vec_u8``.""" + decoded = from_scale_encoding(vec_u8, ChainDataType.IPInfo, is_vec=True) + + if decoded is None: + return [] + + return [IPInfo.fix_decoded_values(d) for d in decoded] + + @classmethod + def fix_decoded_values(cls, decoded: dict) -> "IPInfo": + """Returns a SubnetInfo object from a decoded IPInfo dictionary.""" + return IPInfo( + ip=net.int_to_ip(decoded["ip"]), + ip_type=decoded["ip_type_and_protocol"] >> 4, + protocol=decoded["ip_type_and_protocol"] & 0xF, + ) + + def to_parameter_dict( + self, + ) -> Union[dict[str, Union[str, int]], "torch.nn.ParameterDict"]: + """Returns a torch tensor or dict of the subnet IP info.""" + if use_torch(): + return torch.nn.ParameterDict(self.__dict__) + else: + return self.__dict__ + + @classmethod + def from_parameter_dict( + cls, parameter_dict: Union[dict[str, Any], "torch.nn.ParameterDict"] + ) -> "IPInfo": + """Creates a IPInfo instance from a parameter dictionary.""" + if use_torch(): + return cls(**dict(parameter_dict)) + else: + return cls(**parameter_dict) diff --git a/bittensor/core/chain_data/neuron_info.py b/bittensor/core/chain_data/neuron_info.py new file mode 100644 index 0000000000..478cdfa4c9 --- /dev/null +++ b/bittensor/core/chain_data/neuron_info.py @@ -0,0 +1,176 @@ +from dataclasses import dataclass +from typing import Optional, TYPE_CHECKING + +import bt_decode +import netaddr + +from bittensor.core.chain_data.axon_info import AxonInfo +from bittensor.core.chain_data.prometheus_info import PrometheusInfo +from bittensor.core.chain_data.utils import decode_account_id, process_stake_data +from bittensor.utils import u16_normalized_float +from bittensor.utils.balance import Balance + +# for annotation purposes +if TYPE_CHECKING: + from bittensor.core.chain_data.neuron_info_lite import NeuronInfoLite + + +@dataclass +class NeuronInfo: + """Represents the metadata of a neuron including keys, UID, stake, rankings, and other attributes. + + Attributes: + hotkey (str): The hotkey associated with the neuron. + coldkey (str): The coldkey associated with the neuron. + uid (int): The unique identifier for the neuron. + netuid (int): The network unique identifier for the neuron. + active (int): The active status of the neuron. + stake (Balance): The balance staked to this neuron. + stake_dict (dict[str, Balance]): A dictionary mapping coldkey to the amount staked. + total_stake (Balance): The total amount of stake. + rank (float): The rank score of the neuron. + emission (float): The emission rate. + incentive (float): The incentive value. + consensus (float): The consensus score. + trust (float): The trust score. + validator_trust (float): The validation trust score. + dividends (float): The dividends value. + last_update (int): The timestamp of the last update. + validator_permit (bool): Validator permit status. + weights (list[list[int]]): List of weights associated with the neuron. + bonds (list[list[int]]): List of bonds associated with the neuron. + pruning_score (int): The pruning score of the neuron. + prometheus_info (Optional[PrometheusInfo]): Information related to Prometheus. + axon_info (Optional[AxonInfo]): Information related to Axon. + is_null (bool): Indicator if this is a null neuron. + """ + + hotkey: str + coldkey: str + uid: int + netuid: int + active: int + stake: "Balance" + # mapping of coldkey to amount staked to this Neuron + stake_dict: dict[str, "Balance"] + total_stake: "Balance" + rank: float + emission: float + incentive: float + consensus: float + trust: float + validator_trust: float + dividends: float + last_update: int + validator_permit: bool + weights: list[list[int]] + bonds: list[list[int]] + pruning_score: int + prometheus_info: Optional["PrometheusInfo"] = None + axon_info: Optional["AxonInfo"] = None + is_null: bool = False + + @classmethod + def from_weights_bonds_and_neuron_lite( + cls, + neuron_lite: "NeuronInfoLite", + weights_as_dict: dict[int, list[tuple[int, int]]], + bonds_as_dict: dict[int, list[tuple[int, int]]], + ) -> "NeuronInfo": + """ + Creates an instance of NeuronInfo from NeuronInfoLite and dictionaries of weights and bonds. + + Args: + neuron_lite (NeuronInfoLite): A lite version of the neuron containing basic attributes. + weights_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of weight tuples associated with the neuron. + bonds_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of bond tuples associated with the neuron. + + Returns: + NeuronInfo: An instance of NeuronInfo populated with the provided weights and bonds. + """ + n_dict = neuron_lite.__dict__ + n_dict["weights"] = weights_as_dict.get(neuron_lite.uid, []) + n_dict["bonds"] = bonds_as_dict.get(neuron_lite.uid, []) + + return cls(**n_dict) + + @staticmethod + def get_null_neuron() -> "NeuronInfo": + """Returns a null NeuronInfo instance.""" + neuron = NeuronInfo( + uid=0, + netuid=0, + active=0, + stake=Balance.from_rao(0), + stake_dict={}, + total_stake=Balance.from_rao(0), + rank=0, + emission=0, + incentive=0, + consensus=0, + trust=0, + validator_trust=0, + dividends=0, + last_update=0, + validator_permit=False, + weights=[], + bonds=[], + prometheus_info=None, + axon_info=None, + is_null=True, + coldkey="000000000000000000000000000000000000000000000000", + hotkey="000000000000000000000000000000000000000000000000", + pruning_score=0, + ) + return neuron + + @classmethod + def from_vec_u8(cls, vec_u8: bytes) -> "NeuronInfo": + """Instantiates NeuronInfo from a byte vector.""" + n = bt_decode.NeuronInfo.decode(bytes(vec_u8)) + stake_dict = process_stake_data(n.stake) + total_stake = sum(stake_dict.values()) if stake_dict else Balance(0) + axon_info = n.axon_info + coldkey = decode_account_id(n.coldkey) + hotkey = decode_account_id(n.hotkey) + return NeuronInfo( + hotkey=hotkey, + coldkey=coldkey, + uid=n.uid, + netuid=n.netuid, + active=n.active, + stake=total_stake, + stake_dict=stake_dict, + total_stake=total_stake, + rank=u16_normalized_float(n.rank), + emission=n.emission / 1e9, + incentive=u16_normalized_float(n.incentive), + consensus=u16_normalized_float(n.consensus), + trust=u16_normalized_float(n.trust), + validator_trust=u16_normalized_float(n.validator_trust), + dividends=u16_normalized_float(n.dividends), + last_update=n.last_update, + validator_permit=n.validator_permit, + weights=[[e[0], e[1]] for e in n.weights], + bonds=[[e[0], e[1]] for e in n.bonds], + pruning_score=n.pruning_score, + prometheus_info=PrometheusInfo( + block=n.prometheus_info.block, + version=n.prometheus_info.version, + ip=str(netaddr.IPAddress(n.prometheus_info.ip)), + port=n.prometheus_info.port, + ip_type=n.prometheus_info.ip_type, + ), + axon_info=AxonInfo( + version=axon_info.version, + ip=str(netaddr.IPAddress(axon_info.ip)), + port=axon_info.port, + ip_type=axon_info.ip_type, + placeholder1=axon_info.placeholder1, + placeholder2=axon_info.placeholder2, + protocol=axon_info.protocol, + hotkey=hotkey, + coldkey=coldkey, + ), + is_null=False, + ) diff --git a/bittensor/core/chain_data/neuron_info_lite.py b/bittensor/core/chain_data/neuron_info_lite.py new file mode 100644 index 0000000000..48d9ed4ca1 --- /dev/null +++ b/bittensor/core/chain_data/neuron_info_lite.py @@ -0,0 +1,171 @@ +from dataclasses import dataclass +from typing import Optional + +import bt_decode +import netaddr + +from bittensor.core.chain_data.axon_info import AxonInfo +from bittensor.core.chain_data.prometheus_info import PrometheusInfo +from bittensor.core.chain_data.utils import decode_account_id, process_stake_data +from bittensor.utils import u16_normalized_float +from bittensor.utils.balance import Balance + + +@dataclass +class NeuronInfoLite: + """ + NeuronInfoLite is a dataclass representing neuron metadata without weights and bonds. + + Attributes: + hotkey (str): The hotkey string for the neuron. + coldkey (str): The coldkey string for the neuron. + uid (int): A unique identifier for the neuron. + netuid (int): Network unique identifier for the neuron. + active (int): Indicates whether the neuron is active. + stake (Balance): The stake amount associated with the neuron. + stake_dict (dict): Mapping of coldkey to the amount staked to this Neuron. + total_stake (Balance): Total amount of the stake. + rank (float): The rank of the neuron. + emission (float): The emission value of the neuron. + incentive (float): The incentive value of the neuron. + consensus (float): The consensus value of the neuron. + trust (float): Trust value of the neuron. + validator_trust (float): Validator trust value of the neuron. + dividends (float): Dividends associated with the neuron. + last_update (int): Timestamp of the last update. + validator_permit (bool): Indicates if the neuron has a validator permit. + prometheus_info (Optional[PrometheusInfo]): Prometheus information associated with the neuron. + axon_info (Optional[AxonInfo]): Axon information associated with the neuron. + pruning_score (int): The pruning score of the neuron. + is_null (bool): Indicates whether the neuron is null. + + Methods: + get_null_neuron: Returns a NeuronInfoLite object representing a null neuron. + list_from_vec_u8: Decodes a bytes object into a list of NeuronInfoLite instances. + """ + + hotkey: str + coldkey: str + uid: int + netuid: int + active: int + stake: "Balance" + # mapping of coldkey to amount staked to this Neuron + stake_dict: dict[str, "Balance"] + total_stake: "Balance" + rank: float + emission: float + incentive: float + consensus: float + trust: float + validator_trust: float + dividends: float + last_update: int + validator_permit: bool + prometheus_info: Optional["PrometheusInfo"] + axon_info: Optional["AxonInfo"] + pruning_score: int + is_null: bool = False + + @staticmethod + def get_null_neuron() -> "NeuronInfoLite": + """Returns a null NeuronInfoLite instance.""" + neuron = NeuronInfoLite( + uid=0, + netuid=0, + active=0, + stake=Balance.from_rao(0), + stake_dict={}, + total_stake=Balance.from_rao(0), + rank=0, + emission=0, + incentive=0, + consensus=0, + trust=0, + validator_trust=0, + dividends=0, + last_update=0, + validator_permit=False, + prometheus_info=None, + axon_info=None, + is_null=True, + coldkey="000000000000000000000000000000000000000000000000", + hotkey="000000000000000000000000000000000000000000000000", + pruning_score=0, + ) + return neuron + + @classmethod + def list_from_vec_u8(cls, vec_u8: bytes) -> list["NeuronInfoLite"]: + """ + Decodes a bytes object into a list of NeuronInfoLite instances. + + Args: + vec_u8 (bytes): The bytes object to decode into NeuronInfoLite instances. + + Returns: + list[NeuronInfoLite]: A list of NeuronInfoLite instances decoded from the provided bytes object. + """ + decoded = bt_decode.NeuronInfoLite.decode_vec(vec_u8) + results = [] + for item in decoded: + active = item.active + axon_info = item.axon_info + coldkey = decode_account_id(item.coldkey) + consensus = item.consensus + dividends = item.dividends + emission = item.emission + hotkey = decode_account_id(item.hotkey) + incentive = item.incentive + last_update = item.last_update + netuid = item.netuid + prometheus_info = item.prometheus_info + pruning_score = item.pruning_score + rank = item.rank + stake_dict = process_stake_data(item.stake) + stake = sum(stake_dict.values()) if stake_dict else Balance(0) + trust = item.trust + uid = item.uid + validator_permit = item.validator_permit + validator_trust = item.validator_trust + results.append( + NeuronInfoLite( + active=active, + axon_info=AxonInfo( + version=axon_info.version, + ip=str(netaddr.IPAddress(axon_info.ip)), + port=axon_info.port, + ip_type=axon_info.ip_type, + placeholder1=axon_info.placeholder1, + placeholder2=axon_info.placeholder2, + protocol=axon_info.protocol, + hotkey=hotkey, + coldkey=coldkey, + ), + coldkey=coldkey, + consensus=u16_normalized_float(consensus), + dividends=u16_normalized_float(dividends), + emission=emission / 1e9, + hotkey=hotkey, + incentive=u16_normalized_float(incentive), + last_update=last_update, + netuid=netuid, + prometheus_info=PrometheusInfo( + version=prometheus_info.version, + ip=str(netaddr.IPAddress(prometheus_info.ip)), + port=prometheus_info.port, + ip_type=prometheus_info.ip_type, + block=prometheus_info.block, + ), + pruning_score=pruning_score, + rank=u16_normalized_float(rank), + stake_dict=stake_dict, + stake=stake, + total_stake=stake, + trust=u16_normalized_float(trust), + uid=uid, + validator_permit=validator_permit, + validator_trust=u16_normalized_float(validator_trust), + ) + ) + return results diff --git a/bittensor/core/chain_data/prometheus_info.py b/bittensor/core/chain_data/prometheus_info.py new file mode 100644 index 0000000000..7cdccf83fa --- /dev/null +++ b/bittensor/core/chain_data/prometheus_info.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass + +from bittensor.utils import networking + + +@dataclass +class PrometheusInfo: + """ + Dataclass representing information related to Prometheus. + + Attributes: + block (int): The block number associated with the Prometheus data. + version (int): The version of the Prometheus data. + ip (str): The IP address associated with Prometheus. + port (int): The port number for Prometheus. + ip_type (int): The type of IP address (e.g., IPv4, IPv6). + """ + + block: int + version: int + ip: str + port: int + ip_type: int + + @classmethod + def fix_decoded_values(cls, prometheus_info_decoded: dict) -> "PrometheusInfo": + """Returns a PrometheusInfo object from a prometheus_info_decoded dictionary.""" + prometheus_info_decoded["ip"] = networking.int_to_ip( + int(prometheus_info_decoded["ip"]) + ) + return cls(**prometheus_info_decoded) diff --git a/bittensor/core/chain_data/proposal_vote_data.py b/bittensor/core/chain_data/proposal_vote_data.py new file mode 100644 index 0000000000..493bc2d79f --- /dev/null +++ b/bittensor/core/chain_data/proposal_vote_data.py @@ -0,0 +1,21 @@ +from typing import TypedDict + + +# Senate / Proposal data +class ProposalVoteData(TypedDict): + """ + This TypedDict represents the data structure for a proposal vote in the Senate. + + Attributes: + index (int): The index of the proposal. + threshold (int): The threshold required for the proposal to pass. + ayes (List[str]): List of senators who voted 'aye'. + nays (List[str]): List of senators who voted 'nay'. + end (int): The ending timestamp of the voting period. + """ + + index: int + threshold: int + ayes: list[str] + nays: list[str] + end: int diff --git a/bittensor/core/chain_data/scheduled_coldkey_swap_info.py b/bittensor/core/chain_data/scheduled_coldkey_swap_info.py new file mode 100644 index 0000000000..7c0f6e7f88 --- /dev/null +++ b/bittensor/core/chain_data/scheduled_coldkey_swap_info.py @@ -0,0 +1,65 @@ +from dataclasses import dataclass +from typing import Optional, Any + +from scalecodec.utils.ss58 import ss58_encode + +from bittensor.core.chain_data.utils import from_scale_encoding, ChainDataType +from bittensor.core.settings import SS58_FORMAT + + +@dataclass +class ScheduledColdkeySwapInfo: + """ + The `ScheduledColdkeySwapInfo` class is a dataclass representing information about scheduled cold key swaps. + + Attributes: + old_coldkey (str): The old cold key before the swap. + new_coldkey (str): The new cold key after the swap. + arbitration_block (int): The block number at which the arbitration of the swap will take place. + """ + + old_coldkey: str + new_coldkey: str + arbitration_block: int + + @classmethod + def fix_decoded_values(cls, decoded: Any) -> "ScheduledColdkeySwapInfo": + """Fixes the decoded values.""" + return cls( + old_coldkey=ss58_encode(decoded["old_coldkey"], SS58_FORMAT), + new_coldkey=ss58_encode(decoded["new_coldkey"], SS58_FORMAT), + arbitration_block=decoded["arbitration_block"], + ) + + @classmethod + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["ScheduledColdkeySwapInfo"]: + """Returns a ScheduledColdkeySwapInfo object from a ``vec_u8``.""" + if len(vec_u8) == 0: + return None + + decoded = from_scale_encoding(vec_u8, ChainDataType.ScheduledColdkeySwapInfo) + if decoded is None: + return None + + return ScheduledColdkeySwapInfo.fix_decoded_values(decoded) + + @classmethod + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["ScheduledColdkeySwapInfo"]: + """Returns a list of ScheduledColdkeySwapInfo objects from a ``vec_u8``.""" + decoded = from_scale_encoding( + vec_u8, ChainDataType.ScheduledColdkeySwapInfo, is_vec=True + ) + if decoded is None: + return [] + + return [ScheduledColdkeySwapInfo.fix_decoded_values(d) for d in decoded] + + @classmethod + def decode_account_id_list(cls, vec_u8: list[int]) -> Optional[list[str]]: + """Decodes a list of AccountIds from vec_u8.""" + decoded = from_scale_encoding( + vec_u8, ChainDataType.ScheduledColdkeySwapInfo.AccountId, is_vec=True + ) + if decoded is None: + return None + return [ss58_encode(account_id, SS58_FORMAT) for account_id in decoded] diff --git a/bittensor/core/chain_data/stake_info.py b/bittensor/core/chain_data/stake_info.py new file mode 100644 index 0000000000..8d3b5020fb --- /dev/null +++ b/bittensor/core/chain_data/stake_info.py @@ -0,0 +1,79 @@ +from dataclasses import dataclass +from typing import Optional, Any + +from scalecodec.utils.ss58 import ss58_encode + +from bittensor.core.chain_data.utils import ( + from_scale_encoding, + from_scale_encoding_using_type_string, + ChainDataType, +) +from bittensor.core.settings import SS58_FORMAT +from bittensor.utils.balance import Balance + + +@dataclass +class StakeInfo: + """ + Dataclass for representing stake information linked to hotkey and coldkey pairs. + + Attributes: + hotkey_ss58 (str): The SS58 encoded hotkey address. + coldkey_ss58 (str): The SS58 encoded coldkey address. + stake (Balance): The stake associated with the hotkey-coldkey pair, represented as a Balance object. + """ + + hotkey_ss58: str # Hotkey address + coldkey_ss58: str # Coldkey address + stake: Balance # Stake for the hotkey-coldkey pair + + @classmethod + def fix_decoded_values(cls, decoded: Any) -> "StakeInfo": + """Fixes the decoded values.""" + return cls( + hotkey_ss58=ss58_encode(decoded["hotkey"], SS58_FORMAT), + coldkey_ss58=ss58_encode(decoded["coldkey"], SS58_FORMAT), + stake=Balance.from_rao(decoded["stake"]), + ) + + @classmethod + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["StakeInfo"]: + """Returns a StakeInfo object from a ``vec_u8``.""" + if len(vec_u8) == 0: + return None + + decoded = from_scale_encoding(vec_u8, ChainDataType.StakeInfo) + if decoded is None: + return None + + return StakeInfo.fix_decoded_values(decoded) + + @classmethod + def list_of_tuple_from_vec_u8( + cls, vec_u8: list[int] + ) -> dict[str, list["StakeInfo"]]: + """Returns a list of StakeInfo objects from a ``vec_u8``.""" + decoded: Optional[list[tuple[str, list[object]]]] = ( + from_scale_encoding_using_type_string( + input_=vec_u8, type_string="Vec<(AccountId, Vec)>" + ) + ) + + if decoded is None: + return {} + + return { + ss58_encode(address=account_id, ss58_format=SS58_FORMAT): [ + StakeInfo.fix_decoded_values(d) for d in stake_info + ] + for account_id, stake_info in decoded + } + + @classmethod + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["StakeInfo"]: + """Returns a list of StakeInfo objects from a ``vec_u8``.""" + decoded = from_scale_encoding(vec_u8, ChainDataType.StakeInfo, is_vec=True) + if decoded is None: + return [] + + return [StakeInfo.fix_decoded_values(d) for d in decoded] diff --git a/bittensor/core/chain_data/subnet_hyperparameters.py b/bittensor/core/chain_data/subnet_hyperparameters.py new file mode 100644 index 0000000000..c28f802cfc --- /dev/null +++ b/bittensor/core/chain_data/subnet_hyperparameters.py @@ -0,0 +1,112 @@ +from dataclasses import dataclass +from typing import Optional + +import bt_decode + + +@dataclass +class SubnetHyperparameters: + """ + This class represents the hyperparameters for a subnet. + + Attributes: + rho (int): The rate of decay of some value. + kappa (int): A constant multiplier used in calculations. + immunity_period (int): The period during which immunity is active. + min_allowed_weights (int): Minimum allowed weights. + max_weight_limit (float): Maximum weight limit. + tempo (int): The tempo or rate of operation. + min_difficulty (int): Minimum difficulty for some operations. + max_difficulty (int): Maximum difficulty for some operations. + weights_version (int): The version number of the weights used. + weights_rate_limit (int): Rate limit for processing weights. + adjustment_interval (int): Interval at which adjustments are made. + activity_cutoff (int): Activity cutoff threshold. + registration_allowed (bool): Indicates if registration is allowed. + target_regs_per_interval (int): Target number of registrations per interval. + min_burn (int): Minimum burn value. + max_burn (int): Maximum burn value. + bonds_moving_avg (int): Moving average of bonds. + max_regs_per_block (int): Maximum number of registrations per block. + serving_rate_limit (int): Limit on the rate of service. + max_validators (int): Maximum number of validators. + adjustment_alpha (int): Alpha value for adjustments. + difficulty (int): Difficulty level. + commit_reveal_weights_interval (int): Interval for commit-reveal weights. + commit_reveal_weights_enabled (bool): Flag indicating if commit-reveal weights are enabled. + alpha_high (int): High value of alpha. + alpha_low (int): Low value of alpha. + liquid_alpha_enabled (bool): Flag indicating if liquid alpha is enabled. + """ + + rho: int + kappa: int + immunity_period: int + min_allowed_weights: int + max_weight_limit: float + tempo: int + min_difficulty: int + max_difficulty: int + weights_version: int + weights_rate_limit: int + adjustment_interval: int + activity_cutoff: int + registration_allowed: bool + target_regs_per_interval: int + min_burn: int + max_burn: int + bonds_moving_avg: int + max_regs_per_block: int + serving_rate_limit: int + max_validators: int + adjustment_alpha: int + difficulty: int + commit_reveal_weights_interval: int + commit_reveal_weights_enabled: bool + alpha_high: int + alpha_low: int + liquid_alpha_enabled: bool + + @classmethod + def from_vec_u8(cls, vec_u8: bytes) -> Optional["SubnetHyperparameters"]: + """ + Create a `SubnetHyperparameters` instance from a vector of bytes. + + This method decodes the given vector of bytes using the `bt_decode` module and creates a new instance of `SubnetHyperparameters` with the decoded values. + + Args: + vec_u8 (bytes): A vector of bytes to decode into `SubnetHyperparameters`. + + Returns: + Optional[SubnetHyperparameters]: An instance of `SubnetHyperparameters` if decoding is successful, None otherwise. + """ + decoded = bt_decode.SubnetHyperparameters.decode(vec_u8) + return SubnetHyperparameters( + rho=decoded.rho, + kappa=decoded.kappa, + immunity_period=decoded.immunity_period, + min_allowed_weights=decoded.min_allowed_weights, + max_weight_limit=decoded.max_weights_limit, + tempo=decoded.tempo, + min_difficulty=decoded.min_difficulty, + max_difficulty=decoded.max_difficulty, + weights_version=decoded.weights_version, + weights_rate_limit=decoded.weights_rate_limit, + adjustment_interval=decoded.adjustment_interval, + activity_cutoff=decoded.activity_cutoff, + registration_allowed=decoded.registration_allowed, + target_regs_per_interval=decoded.target_regs_per_interval, + min_burn=decoded.min_burn, + max_burn=decoded.max_burn, + bonds_moving_avg=decoded.bonds_moving_avg, + max_regs_per_block=decoded.max_regs_per_block, + serving_rate_limit=decoded.serving_rate_limit, + max_validators=decoded.max_validators, + adjustment_alpha=decoded.adjustment_alpha, + difficulty=decoded.difficulty, + commit_reveal_weights_interval=decoded.commit_reveal_weights_interval, + commit_reveal_weights_enabled=decoded.commit_reveal_weights_enabled, + alpha_high=decoded.alpha_high, + alpha_low=decoded.alpha_low, + liquid_alpha_enabled=decoded.liquid_alpha_enabled, + ) diff --git a/bittensor/core/chain_data/subnet_info.py b/bittensor/core/chain_data/subnet_info.py new file mode 100644 index 0000000000..f1ce151872 --- /dev/null +++ b/bittensor/core/chain_data/subnet_info.py @@ -0,0 +1,103 @@ +from dataclasses import dataclass +from typing import Any, Optional, Union + +from scalecodec.utils.ss58 import ss58_encode + +from bittensor.core.chain_data.utils import from_scale_encoding, ChainDataType +from bittensor.core.settings import SS58_FORMAT +from bittensor.utils import u16_normalized_float +from bittensor.utils.balance import Balance +from bittensor.utils.registration import torch, use_torch + + +@dataclass +class SubnetInfo: + """Dataclass for subnet info.""" + + netuid: int + rho: int + kappa: int + difficulty: int + immunity_period: int + max_allowed_validators: int + min_allowed_weights: int + max_weight_limit: float + scaling_law_power: float + subnetwork_n: int + max_n: int + blocks_since_epoch: int + tempo: int + modality: int + # netuid -> topk percentile prunning score requirement (u16:MAX normalized.) + connection_requirements: dict[str, float] + emission_value: float + burn: Balance + owner_ss58: str + + @classmethod + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["SubnetInfo"]: + """Returns a SubnetInfo object from a ``vec_u8``.""" + if len(vec_u8) == 0: + return None + + decoded = from_scale_encoding(vec_u8, ChainDataType.SubnetInfo) + if decoded is None: + return None + + return SubnetInfo.fix_decoded_values(decoded) + + @classmethod + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["SubnetInfo"]: + """Returns a list of SubnetInfo objects from a ``vec_u8``.""" + decoded = from_scale_encoding( + vec_u8, ChainDataType.SubnetInfo, is_vec=True, is_option=True + ) + + if decoded is None: + return [] + + return [SubnetInfo.fix_decoded_values(d) for d in decoded] + + @classmethod + def fix_decoded_values(cls, decoded: dict) -> "SubnetInfo": + """Returns a SubnetInfo object from a decoded SubnetInfo dictionary.""" + return SubnetInfo( + netuid=decoded["netuid"], + rho=decoded["rho"], + kappa=decoded["kappa"], + difficulty=decoded["difficulty"], + immunity_period=decoded["immunity_period"], + max_allowed_validators=decoded["max_allowed_validators"], + min_allowed_weights=decoded["min_allowed_weights"], + max_weight_limit=decoded["max_weights_limit"], + scaling_law_power=decoded["scaling_law_power"], + subnetwork_n=decoded["subnetwork_n"], + max_n=decoded["max_allowed_uids"], + blocks_since_epoch=decoded["blocks_since_last_step"], + tempo=decoded["tempo"], + modality=decoded["network_modality"], + connection_requirements={ + str(int(netuid)): u16_normalized_float(int(req)) + for netuid, req in decoded["network_connect"] + }, + emission_value=decoded["emission_values"], + burn=Balance.from_rao(decoded["burn"]), + owner_ss58=ss58_encode(decoded["owner"], SS58_FORMAT), + ) + + def to_parameter_dict(self) -> Union[dict[str, Any], "torch.nn.ParameterDict"]: + """Returns a torch tensor or dict of the subnet info.""" + if use_torch(): + return torch.nn.ParameterDict(self.__dict__) + else: + return self.__dict__ + + @classmethod + def from_parameter_dict( + cls, parameter_dict: Union[dict[str, Any], "torch.nn.ParameterDict"] + ) -> "SubnetInfo": + """Creates a SubnetInfo instance from a parameter dictionary.""" + if use_torch(): + return cls(**dict(parameter_dict)) + else: + return cls(**parameter_dict) diff --git a/bittensor/core/chain_data/utils.py b/bittensor/core/chain_data/utils.py new file mode 100644 index 0000000000..0544ca85a2 --- /dev/null +++ b/bittensor/core/chain_data/utils.py @@ -0,0 +1,291 @@ +"""Chain data helper functions and data.""" + +from enum import Enum +from typing import Optional, Union + +from scalecodec.base import RuntimeConfiguration, ScaleBytes +from scalecodec.type_registry import load_type_registry_preset +from scalecodec.utils.ss58 import ss58_encode + +from bittensor.core.settings import SS58_FORMAT +from bittensor.utils.balance import Balance + + +class ChainDataType(Enum): + NeuronInfo = 1 + SubnetInfo = 2 + DelegateInfo = 3 + NeuronInfoLite = 4 + DelegatedInfo = 5 + StakeInfo = 6 + IPInfo = 7 + SubnetHyperparameters = 8 + ScheduledColdkeySwapInfo = 9 + AccountId = 10 + + +def from_scale_encoding( + input_: Union[list[int], bytes, "ScaleBytes"], + type_name: "ChainDataType", + is_vec: bool = False, + is_option: bool = False, +) -> Optional[dict]: + """ + Decodes input_ data from SCALE encoding based on the specified type name and modifiers. + + Args: + input_ (Union[List[int], bytes, ScaleBytes]): The input_ data to decode. + type_name (ChainDataType): The type of data being decoded. + is_vec (bool): Whether the data is a vector of the specified type. Default is ``False``. + is_option (bool): Whether the data is an optional value of the specified type. Default is ``False``. + + Returns: + Optional[dict]: The decoded data as a dictionary, or ``None`` if the decoding fails. + """ + type_string = type_name.name + if type_name == ChainDataType.DelegatedInfo: + # DelegatedInfo is a tuple of (DelegateInfo, Compact) + type_string = f"({ChainDataType.DelegateInfo.name}, Compact)" + if is_option: + type_string = f"Option<{type_string}>" + if is_vec: + type_string = f"Vec<{type_string}>" + + return from_scale_encoding_using_type_string(input_, type_string) + + +def from_scale_encoding_using_type_string( + input_: Union[list[int], bytes, ScaleBytes], type_string: str +) -> Optional[dict]: + """ + Decodes SCALE encoded data to a dictionary based on the provided type string. + + Args: + input_ (Union[List[int], bytes, ScaleBytes]): The SCALE encoded input data. + type_string (str): The type string defining the structure of the data. + + Returns: + Optional[dict]: The decoded data as a dictionary, or ``None`` if the decoding fails. + + Raises: + TypeError: If the input_ is not a list[int], bytes, or ScaleBytes. + """ + if isinstance(input_, ScaleBytes): + as_scale_bytes = input_ + else: + if isinstance(input_, list) and all([isinstance(i, int) for i in input_]): + vec_u8 = input_ + as_bytes = bytes(vec_u8) + elif isinstance(input_, bytes): + as_bytes = input_ + else: + raise TypeError("input_ must be a list[int], bytes, or ScaleBytes") + + as_scale_bytes = ScaleBytes(as_bytes) + + rpc_runtime_config = RuntimeConfiguration() + rpc_runtime_config.update_type_registry(load_type_registry_preset("legacy")) + rpc_runtime_config.update_type_registry(custom_rpc_type_registry) + + obj = rpc_runtime_config.create_scale_object(type_string, data=as_scale_bytes) + + return obj.decode() + + +custom_rpc_type_registry = { + "types": { + "SubnetInfo": { + "type": "struct", + "type_mapping": [ + ["netuid", "Compact"], + ["rho", "Compact"], + ["kappa", "Compact"], + ["difficulty", "Compact"], + ["immunity_period", "Compact"], + ["max_allowed_validators", "Compact"], + ["min_allowed_weights", "Compact"], + ["max_weights_limit", "Compact"], + ["scaling_law_power", "Compact"], + ["subnetwork_n", "Compact"], + ["max_allowed_uids", "Compact"], + ["blocks_since_last_step", "Compact"], + ["tempo", "Compact"], + ["network_modality", "Compact"], + ["network_connect", "Vec<[u16; 2]>"], + ["emission_values", "Compact"], + ["burn", "Compact"], + ["owner", "AccountId"], + ], + }, + "DelegateInfo": { + "type": "struct", + "type_mapping": [ + ["delegate_ss58", "AccountId"], + ["take", "Compact"], + ["nominators", "Vec<(AccountId, Compact)>"], + ["owner_ss58", "AccountId"], + ["registrations", "Vec>"], + ["validator_permits", "Vec>"], + ["return_per_1000", "Compact"], + ["total_daily_return", "Compact"], + ], + }, + "NeuronInfo": { + "type": "struct", + "type_mapping": [ + ["hotkey", "AccountId"], + ["coldkey", "AccountId"], + ["uid", "Compact"], + ["netuid", "Compact"], + ["active", "bool"], + ["axon_info", "axon_info"], + ["prometheus_info", "PrometheusInfo"], + ["stake", "Vec<(AccountId, Compact)>"], + ["rank", "Compact"], + ["emission", "Compact"], + ["incentive", "Compact"], + ["consensus", "Compact"], + ["trust", "Compact"], + ["validator_trust", "Compact"], + ["dividends", "Compact"], + ["last_update", "Compact"], + ["validator_permit", "bool"], + ["weights", "Vec<(Compact, Compact)>"], + ["bonds", "Vec<(Compact, Compact)>"], + ["pruning_score", "Compact"], + ], + }, + "NeuronInfoLite": { + "type": "struct", + "type_mapping": [ + ["hotkey", "AccountId"], + ["coldkey", "AccountId"], + ["uid", "Compact"], + ["netuid", "Compact"], + ["active", "bool"], + ["axon_info", "axon_info"], + ["prometheus_info", "PrometheusInfo"], + ["stake", "Vec<(AccountId, Compact)>"], + ["rank", "Compact"], + ["emission", "Compact"], + ["incentive", "Compact"], + ["consensus", "Compact"], + ["trust", "Compact"], + ["validator_trust", "Compact"], + ["dividends", "Compact"], + ["last_update", "Compact"], + ["validator_permit", "bool"], + ["pruning_score", "Compact"], + ], + }, + "axon_info": { + "type": "struct", + "type_mapping": [ + ["block", "u64"], + ["version", "u32"], + ["ip", "u128"], + ["port", "u16"], + ["ip_type", "u8"], + ["protocol", "u8"], + ["placeholder1", "u8"], + ["placeholder2", "u8"], + ], + }, + "PrometheusInfo": { + "type": "struct", + "type_mapping": [ + ["block", "u64"], + ["version", "u32"], + ["ip", "u128"], + ["port", "u16"], + ["ip_type", "u8"], + ], + }, + "IPInfo": { + "type": "struct", + "type_mapping": [ + ["ip", "Compact"], + ["ip_type_and_protocol", "Compact"], + ], + }, + "StakeInfo": { + "type": "struct", + "type_mapping": [ + ["hotkey", "AccountId"], + ["coldkey", "AccountId"], + ["stake", "Compact"], + ], + }, + "SubnetHyperparameters": { + "type": "struct", + "type_mapping": [ + ["rho", "Compact"], + ["kappa", "Compact"], + ["immunity_period", "Compact"], + ["min_allowed_weights", "Compact"], + ["max_weights_limit", "Compact"], + ["tempo", "Compact"], + ["min_difficulty", "Compact"], + ["max_difficulty", "Compact"], + ["weights_version", "Compact"], + ["weights_rate_limit", "Compact"], + ["adjustment_interval", "Compact"], + ["activity_cutoff", "Compact"], + ["registration_allowed", "bool"], + ["target_regs_per_interval", "Compact"], + ["min_burn", "Compact"], + ["max_burn", "Compact"], + ["bonds_moving_avg", "Compact"], + ["max_regs_per_block", "Compact"], + ["serving_rate_limit", "Compact"], + ["max_validators", "Compact"], + ["adjustment_alpha", "Compact"], + ["difficulty", "Compact"], + ["commit_reveal_weights_interval", "Compact"], + ["commit_reveal_weights_enabled", "bool"], + ["alpha_high", "Compact"], + ["alpha_low", "Compact"], + ["liquid_alpha_enabled", "bool"], + ], + }, + "ScheduledColdkeySwapInfo": { + "type": "struct", + "type_mapping": [ + ["old_coldkey", "AccountId"], + ["new_coldkey", "AccountId"], + ["arbitration_block", "Compact"], + ], + }, + } +} + + +def decode_account_id(account_id_bytes: list) -> str: + """ + Decodes an AccountId from bytes to a Base64 string using SS58 encoding. + + Args: + account_id_bytes (bytes): The AccountId in bytes that needs to be decoded. + + Returns: + str: The decoded AccountId as a Base64 string. + """ + # Convert the AccountId bytes to a Base64 string + return ss58_encode(bytes(account_id_bytes).hex(), SS58_FORMAT) + + +def process_stake_data(stake_data: list) -> dict: + """ + Processes stake data to decode account IDs and convert stakes from rao to Balance objects. + + Args: + stake_data (list): A list of tuples where each tuple contains an account ID in bytes and a stake in rao. + + Returns: + dict: A dictionary with account IDs as keys and their corresponding Balance objects as values. + """ + decoded_stake_data = {} + for account_id_bytes, stake_ in stake_data: + account_id = decode_account_id(account_id_bytes) + decoded_stake_data.update({account_id: Balance.from_rao(stake_)}) + return decoded_stake_data diff --git a/bittensor/core/config.py b/bittensor/core/config.py new file mode 100644 index 0000000000..5027bbecb5 --- /dev/null +++ b/bittensor/core/config.py @@ -0,0 +1,396 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +"""Implementation of the config class, which manages the configuration of different Bittensor modules.""" + +import argparse +import copy +import os +import sys +from copy import deepcopy +from typing import Any, TypeVar, Type, Optional + +import yaml +from munch import DefaultMunch + + +class InvalidConfigFile(Exception): + """In place of YAMLError""" + + +class Config(DefaultMunch): + """ + Implementation of the config class, which manages the configuration of different Bittensor modules. + + Translates the passed parser into a nested Bittensor config. + + Args: + parser (argparse.ArgumentParser): Command line parser object. + strict (bool): If ``true``, the command line arguments are strictly parsed. + args (list of str): Command line arguments. + default (Optional[Any]): Default value for the Config. Defaults to ``None``. This default will be returned for attributes that are undefined. + + Returns: + config (bittensor.core.config.Config): Nested config object created from parser arguments. + """ + + __is_set: dict[str, bool] + + def __init__( + self, + parser: argparse.ArgumentParser = None, + args: Optional[list[str]] = None, + strict: bool = False, + default: Optional[Any] = None, + ) -> None: + super().__init__(default) + + self["__is_set"] = {} + + if parser is None: + return + + # Optionally add config specific arguments + try: + parser.add_argument( + "--config", + type=str, + help="If set, defaults are overridden by passed file.", + ) + except Exception: + # this can fail if --config has already been added. + pass + + try: + parser.add_argument( + "--strict", + action="store_true", + help="""If flagged, config will check that only exact arguments have been set.""", + default=False, + ) + except Exception: + # this can fail if --strict has already been added. + pass + + try: + parser.add_argument( + "--no_version_checking", + action="store_true", + help="Set ``true`` to stop cli version checking.", + default=False, + ) + except Exception: + # this can fail if --no_version_checking has already been added. + pass + + try: + parser.add_argument( + "--no_prompt", + dest="no_prompt", + action="store_true", + help="Set ``true`` to stop cli from prompting the user.", + default=False, + ) + except Exception: + # this can fail if --no_version_checking has already been added. + pass + + # Get args from argv if not passed in. + if args is None: + args = sys.argv[1:] + + # Check for missing required arguments before proceeding + missing_required_args = self.__check_for_missing_required_args(parser, args) + if missing_required_args: + # Handle missing required arguments gracefully + raise ValueError( + f"Missing required arguments: {', '.join(missing_required_args)}" + ) + + # 1.1 Optionally load defaults if the --config is set. + try: + config_file_path = ( + str(os.getcwd()) + + "/" + + vars(parser.parse_known_args(args)[0])["config"] + ) + except Exception as e: + config_file_path = None + + # Parse args not strict + config_params = Config.__parse_args__(args=args, parser=parser, strict=False) + + # 2. Optionally check for --strict + # strict=True when passed in OR when --strict is set + strict = config_params.strict or strict + + if config_file_path is not None: + config_file_path = os.path.expanduser(config_file_path) + try: + with open(config_file_path) as f: + params_config = yaml.safe_load(f) + print(f"Loading config defaults from: {config_file_path}") + parser.set_defaults(**params_config) + except Exception as e: + print(f"Error in loading: {e} using default parser settings") + + # 2. Continue with loading in params. + params = Config.__parse_args__(args=args, parser=parser, strict=strict) + + _config = self + + # Splits params and add to config + Config.__split_params__(params=params, _config=_config) + + # Make the is_set map + _config["__is_set"] = {} + + # Reparse args using default of unset + parser_no_defaults = copy.deepcopy(parser) + + # Only command as the arg, else no args + default_param_args = ( + [_config.get("command")] + if _config.get("command") is not None and _config.get("subcommand") is None + else [] + ) + if _config.get("command") is not None and _config.get("subcommand") is not None: + default_param_args = [_config.get("command"), _config.get("subcommand")] + + # Get all args by name + default_params = parser.parse_args(args=default_param_args) + + all_default_args = default_params.__dict__.keys() | [] + # Make a dict with keys as args and values as argparse.SUPPRESS + defaults_as_suppress = {key: argparse.SUPPRESS for key in all_default_args} + # Set the defaults to argparse.SUPPRESS, should remove them from the namespace + parser_no_defaults.set_defaults(**defaults_as_suppress) + parser_no_defaults._defaults.clear() # Needed for quirk of argparse + + # Check for subparsers and do the same + if parser_no_defaults._subparsers is not None: + for action in parser_no_defaults._subparsers._actions: + # Should only be the "command" subparser action + if isinstance(action, argparse._SubParsersAction): + # Set the defaults to argparse.SUPPRESS, should remove them from the namespace + # Each choice is the keyword for a command, we need to set the defaults for each of these + # Note: we also need to clear the _defaults dict for each, this is a quirk of argparse + cmd_parser: argparse.ArgumentParser + for cmd_parser in action.choices.values(): + # If this choice is also a subparser, set defaults recursively + if cmd_parser._subparsers: + for action in cmd_parser._subparsers._actions: + # Should only be the "command" subparser action + if isinstance(action, argparse._SubParsersAction): + cmd_parser: argparse.ArgumentParser + for cmd_parser in action.choices.values(): + cmd_parser.set_defaults(**defaults_as_suppress) + cmd_parser._defaults.clear() # Needed for quirk of argparse + else: + cmd_parser.set_defaults(**defaults_as_suppress) + cmd_parser._defaults.clear() # Needed for quirk of argparse + + # Reparse the args, but this time with the defaults as argparse.SUPPRESS + params_no_defaults = Config.__parse_args__( + args=args, parser=parser_no_defaults, strict=strict + ) + + # Diff the params and params_no_defaults to get the is_set map + _config["__is_set"] = { + arg_key: True + for arg_key in [ + k + for k, _ in filter( + lambda kv: kv[1] != argparse.SUPPRESS, + params_no_defaults.__dict__.items(), + ) + ] + } + + @staticmethod + def __split_params__(params: argparse.Namespace, _config: "Config"): + # Splits params on dot syntax i.e. neuron.axon_port and adds to _config + for arg_key, arg_val in params.__dict__.items(): + split_keys = arg_key.split(".") + head = _config + keys = split_keys + while len(keys) > 1: + if ( + hasattr(head, keys[0]) and head[keys[0]] is not None + ): # Needs to be Config + head = getattr(head, keys[0]) + keys = keys[1:] + else: + head[keys[0]] = Config() + head = head[keys[0]] + keys = keys[1:] + if len(keys) == 1: + head[keys[0]] = arg_val + + @staticmethod + def __parse_args__( + args: list[str], parser: argparse.ArgumentParser = None, strict: bool = False + ) -> argparse.Namespace: + """Parses the passed args use the passed parser. + + Args: + 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: Namespace object created from parser arguments. + """ + if not strict: + params, unrecognized = parser.parse_known_args(args=args) + params_list = list(params.__dict__) + # bug within argparse itself, does not correctly set value for boolean flags + for unrec in unrecognized: + if unrec.startswith("--") and unrec[2:] in params_list: + # Set the missing boolean value to true + setattr(params, unrec[2:], True) + else: + params = parser.parse_args(args=args) + + return params + + def __deepcopy__(self, memo) -> "Config": + _default = self.__default__ + + config_state = self.__getstate__() + config_copy = Config() + memo[id(self)] = config_copy + + config_copy.__setstate__(config_state) + config_copy.__default__ = _default + + config_copy["__is_set"] = deepcopy(self["__is_set"], memo) + + return config_copy + + def __repr__(self) -> str: + return self.__str__() + + @staticmethod + def _remove_private_keys(d): + if "__parser" in d: + d.pop("__parser", None) + if "__is_set" in d: + d.pop("__is_set", None) + for k, v in list(d.items()): + if isinstance(v, dict): + Config._remove_private_keys(v) + return d + + def __str__(self) -> str: + # remove the parser and is_set map from the visible config + visible = copy.deepcopy(self.toDict()) + visible.pop("__parser", None) + visible.pop("__is_set", None) + cleaned = Config._remove_private_keys(visible) + return "\n" + yaml.dump(cleaned, sort_keys=False) + + def copy(self) -> "Config": + return copy.deepcopy(self) + + @staticmethod + def to_string(items) -> str: + """Get string from items.""" + return "\n" + yaml.dump(items.toDict()) + + def update_with_kwargs(self, kwargs): + """Add config to self""" + for key, val in kwargs.items(): + self[key] = val + + @classmethod + def _merge(cls, a, b): + """ + Merge two configurations recursively. + If there is a conflict, the value from the second configuration will take precedence. + """ + for key in b: + if key in a: + if isinstance(a[key], dict) and isinstance(b[key], dict): + a[key] = cls._merge(a[key], b[key]) + else: + a[key] = b[key] + else: + a[key] = b[key] + return a + + def merge(self, b: "Config"): + """ + Merges the current config with another config. + + Args: + b (bittensor.core.config.Config): Another config to merge. + """ + self._merge(self, b) + + @classmethod + def merge_all(cls, configs: list["Config"]) -> "Config": + """ + 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. + + Args: + configs (list[bittensor.core.config.Config]): List of configs to be merged. + + Returns: + config (bittensor.core.config.Config): Merged config object. + """ + result = cls() + for cfg in configs: + result.merge(cfg) + return result + + def is_set(self, param_name: str) -> bool: + """Returns a boolean indicating whether the parameter has been set or is still the default.""" + if param_name not in self.get("__is_set"): + return False + else: + return self.get("__is_set")[param_name] + + def __check_for_missing_required_args( + self, parser: argparse.ArgumentParser, args: list[str] + ) -> list[str]: + required_args = self.__get_required_args_from_parser(parser) + missing_args = [arg for arg in required_args if not any(arg in s for s in args)] + return missing_args + + @staticmethod + def __get_required_args_from_parser(parser: argparse.ArgumentParser) -> list[str]: + required_args = [] + for action in parser._actions: + if action.required: + # Prefix the argument with '--' if it's a long argument, or '-' if it's short + prefix = "--" if len(action.dest) > 1 else "-" + required_args.append(prefix + action.dest) + return required_args + + +T = TypeVar("T", bound="DefaultConfig") + + +class DefaultConfig(Config): + """A Config with a set of default values.""" + + @classmethod + def default(cls: Type[T]) -> T: + """Get default config.""" + raise NotImplementedError("Function default is not implemented.") diff --git a/bittensor/core/dendrite.py b/bittensor/core/dendrite.py new file mode 100644 index 0000000000..0b9bc5381f --- /dev/null +++ b/bittensor/core/dendrite.py @@ -0,0 +1,832 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from __future__ import annotations + +import asyncio +import time +import uuid +from typing import Any, AsyncGenerator, Optional, Union, Type + +import aiohttp +from bittensor_wallet import Wallet +from substrateinterface import Keypair + +from bittensor.core.axon import Axon +from bittensor.core.chain_data import AxonInfo +from bittensor.core.settings import version_as_int +from bittensor.core.stream import StreamingSynapse +from bittensor.core.synapse import Synapse, TerminalInfo +from bittensor.utils import networking +from bittensor.utils.btlogging import logging +from bittensor.utils.registration import torch, use_torch + +DENDRITE_ERROR_MAPPING: dict[Type[Exception], tuple] = { + aiohttp.ClientConnectorError: ("503", "Service unavailable"), + asyncio.TimeoutError: ("408", "Request timeout"), + aiohttp.ClientResponseError: (None, "Client response error"), + aiohttp.ClientPayloadError: ("400", "Payload error"), + aiohttp.ClientError: ("500", "Client error"), + aiohttp.ServerTimeoutError: ("504", "Server timeout error"), + aiohttp.ServerDisconnectedError: ("503", "Service disconnected"), + aiohttp.ServerConnectionError: ("503", "Service connection error"), +} +DENDRITE_DEFAULT_ERROR = ("422", "Failed to parse response") + + +class DendriteMixin: + """ + The Dendrite class represents the abstracted implementation of a network client module. + + In the brain analogy, dendrites receive signals + from other neurons (in this case, network servers or axons), and the Dendrite class here is designed + to send requests to those endpoint to receive inputs. + + This class includes a wallet or keypair used for signing messages, and methods for making + HTTP requests to the network servers. It also provides functionalities such as logging + network requests and processing server responses. + + Args: + keypair (Option[Union[bittensor_wallet.Wallet, substrateinterface.Keypair]]): The wallet or keypair used for signing messages. + external_ip (str): The external IP address of the local system. + synapse_history (list): A list of Synapse objects representing the historical responses. + + Methods: + __str__(): Returns a string representation of the Dendrite object. + __repr__(): Returns a string representation of the Dendrite object, acting as a fallback for __str__(). + query(self, *args, **kwargs) -> Union[Synapse, list[Synapse]]: Makes synchronous requests to one or multiple target Axons and returns responses. + forward(self, axons, synapse=Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) -> Synapse: Asynchronously sends requests to one or multiple Axons and collates their responses. + call(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> Synapse: Asynchronously sends a request to a specified Axon and processes the response. + call_stream(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> AsyncGenerator[Synapse, None]: Sends a request to a specified Axon and yields an AsyncGenerator that contains streaming response chunks before finally yielding the filled Synapse as the final element. + preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) -> Synapse: Preprocesses the synapse for making a request, including building headers and signing. + process_server_response(self, server_response, json_response, local_synapse): Processes the server response, updates the local synapse state, and merges headers. + close_session(self): Synchronously closes the internal aiohttp client session. + aclose_session(self): Asynchronously closes the internal aiohttp client session. + + NOTE: + When working with async `aiohttp `_ client sessions, it is recommended to use a context manager. + + Example with a context manager:: + + async with dendrite(wallet = bittensor_wallet.Wallet()) as d: + print(d) + d( ) # ping axon + d( [] ) # ping multiple + d( Axon(), Synapse ) + + However, you are able to safely call :func:`dendrite.query()` without a context manager in a synchronous setting. + + Example without a context manager:: + + d = dendrite(wallet = bittensor_wallet.Wallet() ) + print(d) + d( ) # ping axon + d( [] ) # ping multiple + d( bittensor.core.axon.Axon, bittensor.core.synapse.Synapse ) + """ + + def __init__(self, wallet: Optional[Union["Wallet", "Keypair"]] = None): + """ + Initializes the Dendrite object, setting up essential properties. + + Args: + wallet (Optional[Union[bittensor_wallet.Wallet, substrateinterface.Keypair]]): The user's wallet or keypair used for signing messages. Defaults to ``None``, in which case a new :func:`bittensor_wallet.Wallet().hotkey` is generated and used. + """ + # Initialize the parent class + super(DendriteMixin, self).__init__() + + # Unique identifier for the instance + self.uuid = str(uuid.uuid1()) + + # Get the external IP + self.external_ip = networking.get_external_ip() + + # If a wallet or keypair is provided, use its hotkey. If not, generate a new one. + self.keypair = ( + wallet.hotkey if isinstance(wallet, Wallet) else wallet + ) or Wallet().hotkey + + self.synapse_history: list = [] + + self._session: Optional[aiohttp.ClientSession] = None + + @property + async def session(self) -> 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: + aiohttp.ClientSession: 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. + + Example usage:: + + import bittensor # Import bittensor + wallet = bittensor.Wallet( ... ) # Initialize a wallet + dendrite = bittensor.Dendrite(wallet=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 + + """ + if self._session is None: + self._session = aiohttp.ClientSession() + return self._session + + def close_session(self): + """ + 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 + :func:`dendrite_instance.close_session()`. + """ + if self._session: + loop = asyncio.get_event_loop() + loop.run_until_complete(self._session.close()) + self._session = None + + async def aclose_session(self): + """ + Asynchronously closes the internal `aiohttp `_ client session. + + This method is the asynchronous counterpart to the :func:`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. + + Example: + Usage:: + When finished with dendrite in an asynchronous context + await :func:`dendrite_instance.aclose_session()`. + + Example: + Usage:: + async with dendrite_instance: + # Operations using dendrite + pass + # The session will be closed automatically after the above block + """ + if self._session: + await self._session.close() + self._session = None + + def _get_endpoint_url(self, 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. + + Args: + target_axon: The target axon object containing IP and port information. + request_name: The specific name of the request being made. + + Returns: + str: A string representing the complete HTTP URL for the request. + """ + endpoint = ( + f"0.0.0.0:{str(target_axon.port)}" + if target_axon.ip == str(self.external_ip) + else f"{target_axon.ip}:{str(target_axon.port)}" + ) + return f"http://{endpoint}/{request_name}" + + def log_exception(self, exception: Exception): + """ + Logs an exception with a unique identifier. + + This method generates a unique UUID for the error, extracts the error type, + and logs the error message using Bittensor's logging system. + + Args: + exception (Exception): The exception object to be logged. + + Returns: + None + """ + error_id = str(uuid.uuid4()) + error_type = exception.__class__.__name__ + logging.error(f"{error_type}#{error_id}: {exception}") + + def process_error_message( + self, + synapse: Union["Synapse", "StreamingSynapse"], + request_name: str, + exception: Exception, + ) -> Union["Synapse", "StreamingSynapse"]: + """ + 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. + + Args: + synapse (bittensor.core.synapse.Synapse): The synapse object associated with the request. + request_name (str): The name of the request during which the exception occurred. + exception (Exception): The exception object caught during the request. + + Returns: + Synapse (bittensor.core.synapse.Synapse): The updated synapse object with the error status code and message. + + Note: + This method updates the synapse object in-place. + """ + + self.log_exception(exception) + + error_info = DENDRITE_ERROR_MAPPING.get(type(exception), DENDRITE_DEFAULT_ERROR) + status_code, status_message = error_info + + if status_code: + synapse.dendrite.status_code = status_code # type: ignore + elif isinstance(exception, aiohttp.ClientResponseError): + synapse.dendrite.status_code = str(exception.code) # type: ignore + + message = f"{status_message}: {str(exception)}" + if isinstance(exception, aiohttp.ClientConnectorError): + message = f"{status_message} at {synapse.axon.ip}:{synapse.axon.port}/{request_name}" # type: ignore + elif isinstance(exception, asyncio.TimeoutError): + message = f"{status_message} after {synapse.timeout} seconds" + + synapse.dendrite.status_message = message # type: ignore + + return synapse + + def _log_outgoing_request(self, synapse: "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:: + + Example:: + + import bittensor + bittensor.debug() + + Args: + synapse (bittensor.core.synapse.Synapse): The synapse object representing the request being sent. + """ + if synapse.axon is not None: + logging.trace( + f"dendrite | --> | {synapse.get_total_size()} B | {synapse.name} | {synapse.axon.hotkey} | {synapse.axon.ip}:{str(synapse.axon.port)} | 0 | Success" + ) + + def _log_incoming_response(self, synapse: "Synapse"): + """ + Logs information about incoming responses for debugging and monitoring. + + Similar to :func:`_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. + + Args: + synapse (bittensor.core.synapse.Synapse): The synapse object representing the received response. + """ + if synapse.axon is not None and synapse.dendrite is not None: + logging.trace( + f"dendrite | <-- | {synapse.get_total_size()} B | {synapse.name} | {synapse.axon.hotkey} | {synapse.axon.ip}:{str(synapse.axon.port)} | {synapse.dendrite.status_code} | {synapse.dendrite.status_message}" + ) + + def query( + self, *args, **kwargs + ) -> list[Union["AsyncGenerator[Any, Any]", "Synapse", "StreamingSynapse"]]: + """ + Makes a synchronous request to multiple target Axons and returns the server responses. + + Cleanup is automatically handled and sessions are closed upon completed requests. + + Args: + axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, 'bittensor.core.axon.Axon']], Union['bittensor.core.chain_data.axon_info.AxonInfo', 'bittensor.core.axon.Axon']]): The list of target Axon information. + synapse (Optional[bittensor.core.synapse.Synapse]): The Synapse object. Defaults to :func:`Synapse()`. + timeout (Optional[float]): The request timeout duration in seconds. Defaults to ``12.0`` seconds. + + Returns: + Union[bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: 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. + """ + result = None + try: + loop = asyncio.get_event_loop() + result = loop.run_until_complete(self.forward(*args, **kwargs)) + except Exception: + new_loop = asyncio.new_event_loop() + asyncio.set_event_loop(new_loop) + result = new_loop.run_until_complete(self.forward(*args, **kwargs)) + new_loop.close() + finally: + self.close_session() + return result # type: ignore + + async def forward( + self, + axons: Union[list[Union["AxonInfo", "Axon"]], Union["AxonInfo", "Axon"]], + synapse: "Synapse" = Synapse(), + timeout: float = 12, + deserialize: bool = True, + run_async: bool = True, + streaming: bool = False, + ) -> list[Union["AsyncGenerator[Any, Any]", "Synapse", "StreamingSynapse"]]: + """ + 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:: + + ... + import bittensor + wallet = bittensor.Wallet() # Initialize a wallet + synapse = bittensor.Synapse(...) # Create a synapse object that contains query data + dendrite = bittensor.Dendrite(wallet = wallet) # Initialize a dendrite instance + netuid = ... # Provide subnet ID + metagraph = bittensor.Metagraph(netuid) # Initialize a metagraph 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:: + + ... + dendrite = bittensor.Dendrite(wallet = wallet) + async for chunk in dendrite.forward(axons, synapse, timeout, deserialize, run_async, streaming): + # Process each chunk here + print(chunk) + + Args: + axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]], Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]]): The target Axons to send requests to. Can be a single Axon or a list of Axons. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. + timeout (float): Maximum duration to wait for a response from an Axon in seconds. Defaults to ``12.0``. + deserialize (bool): Determines if the received response should be deserialized. Defaults to ``True``. + run_async (bool): If ``True``, sends requests concurrently. Otherwise, sends requests sequentially. Defaults to ``True``. + streaming (bool): Indicates if the response is expected to be in streaming format. Defaults to ``False``. + + Returns: + Union[AsyncGenerator, bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: If a single `Axon` is targeted, returns its response. + If multiple Axons are targeted, returns a list of their responses. + """ + is_list = True + # If a single axon is provided, wrap it in a list for uniform processing + if not isinstance(axons, list): + is_list = False + axons = [axons] + + # Check if synapse is an instance of the StreamingSynapse class or if streaming flag is set. + is_streaming_subclass = issubclass(synapse.__class__, StreamingSynapse) + if streaming != is_streaming_subclass: + logging.warning( + f"Argument streaming is {streaming} while issubclass(synapse, StreamingSynapse) is {synapse.__class__.__name__}. This may cause unexpected behavior." + ) + streaming = is_streaming_subclass or streaming + + async def query_all_axons( + is_stream: bool, + ) -> Union["AsyncGenerator[Any, Any]", "Synapse", "StreamingSynapse"]: + """ + Handles the processing of requests to all targeted axons, accommodating both streaming and non-streaming responses. + + This function manages the concurrent or sequential dispatch of requests to a list of axons. + It utilizes the ``is_stream`` parameter to determine the mode of response handling (streaming + or non-streaming). For each axon, it calls ``single_axon_response`` and aggregates the responses. + + Args: + is_stream (bool): Flag indicating whether the axon responses are expected to be streamed. + If ``True``, responses are handled in streaming mode. + + Returns: + list[Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]]: A list containing the responses from each axon. The type of each response depends on the streaming mode and the type of synapse used. + """ + + async def single_axon_response( + target_axon: Union["AxonInfo", "Axon"], + ) -> Union["AsyncGenerator[Any, Any]", "Synapse", "StreamingSynapse"]: + """ + Manages the request and response process for a single axon, supporting both streaming and non-streaming modes. + + This function is responsible for initiating a request to a single axon. Depending on the ``is_stream`` flag, it either uses ``call_stream`` for streaming responses or ``call`` for standard responses. The function handles the response processing, catering to the specifics of streaming or non-streaming data. + + Args: + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon): The target axon object to which the request is to be sent. This object contains the necessary information like IP address and port to formulate the request. + + Returns: + Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]: The response from the targeted axon. In streaming mode, an AsyncGenerator is returned, yielding data chunks. In non-streaming mode, a Synapse or StreamingSynapse object is returned containing the response. + """ + if is_stream: + # If in streaming mode, return the async_generator + return self.call_stream( + target_axon=target_axon, + synapse=synapse.model_copy(), # type: ignore + timeout=timeout, + deserialize=deserialize, + ) + else: + # If not in streaming mode, simply call the axon and get the response. + return await self.call( + target_axon=target_axon, + synapse=synapse.model_copy(), # type: ignore + timeout=timeout, + deserialize=deserialize, + ) + + # If run_async flag is False, get responses one by one. + if not run_async: + return [ + await single_axon_response(target_axon) for target_axon in axons + ] # type: ignore + # If run_async flag is True, get responses concurrently using asyncio.gather(). + return await asyncio.gather( + *(single_axon_response(target_axon) for target_axon in axons) + ) # type: ignore + + # Get responses for all axons. + responses = await query_all_axons(streaming) + # Return the single response if only one axon was targeted, else return all responses + return responses[0] if len(responses) == 1 and not is_list else responses # type: ignore + + async def call( + self, + target_axon: Union["AxonInfo", "Axon"], + synapse: "Synapse" = Synapse(), + timeout: float = 12.0, + deserialize: bool = True, + ) -> "Synapse": + """ + 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. + + Args: + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon to send the request to. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. + timeout (float): Maximum duration to wait for a response from the Axon in seconds. Defaults to ``12.0``. + deserialize (bool): Determines if the received response should be deserialized. Defaults to ``True``. + + Returns: + bittensor.core.synapse.Synapse: The Synapse object, updated with the response data from the Axon. + """ + + # Record start time + start_time = time.time() + target_axon = ( + target_axon.info() if isinstance(target_axon, Axon) else target_axon + ) + + # Build request endpoint from the synapse class + request_name = synapse.__class__.__name__ + url = self._get_endpoint_url(target_axon, request_name=request_name) + + # Preprocess synapse for making a request + synapse = self.preprocess_synapse_for_request(target_axon, synapse, timeout) + + try: + # Log outgoing request + self._log_outgoing_request(synapse) + + # Make the HTTP POST request + async with (await self.session).post( + url=url, + headers=synapse.to_headers(), + json=synapse.model_dump(), + timeout=aiohttp.ClientTimeout(total=timeout), + ) as response: + # Extract the JSON response from the server + json_response = await response.json() + # Process the server response and fill synapse + self.process_server_response(response, json_response, synapse) + + # Set process time and log the response + synapse.dendrite.process_time = str(time.time() - start_time) # type: ignore + + except Exception as e: + synapse = self.process_error_message(synapse, request_name, e) + + finally: + self._log_incoming_response(synapse) + + # Log synapse event history + self.synapse_history.append(Synapse.from_headers(synapse.to_headers())) + + # Return the updated synapse object after deserializing if requested + return synapse.deserialize() if deserialize else synapse + + async def call_stream( + self, + target_axon: Union["AxonInfo", "Axon"], + synapse: "StreamingSynapse" = Synapse(), # type: ignore + timeout: float = 12.0, + deserialize: bool = True, + ) -> "AsyncGenerator[Any, Any]": + """ + 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. + + Args: + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon to send the request to. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. + timeout (float): Maximum duration to wait for a response (or a chunk of the response) from the Axon in seconds. Defaults to ``12.0``. + deserialize (bool): 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.core.synapse.Synapse: After the AsyncGenerator has been exhausted, yields the final filled Synapse. + """ + + # Record start time + start_time = time.time() + target_axon = ( + target_axon.info() if isinstance(target_axon, Axon) else target_axon + ) + + # Build request endpoint from the synapse class + request_name = synapse.__class__.__name__ + endpoint = ( + f"0.0.0.0:{str(target_axon.port)}" + if target_axon.ip == str(self.external_ip) + else f"{target_axon.ip}:{str(target_axon.port)}" + ) + url = f"http://{endpoint}/{request_name}" + + # Preprocess synapse for making a request + synapse = self.preprocess_synapse_for_request(target_axon, synapse, timeout) # type: ignore + + try: + # Log outgoing request + self._log_outgoing_request(synapse) + + # Make the HTTP POST request + async with (await self.session).post( + url, + headers=synapse.to_headers(), + json=synapse.model_dump(), + timeout=aiohttp.ClientTimeout(total=timeout), + ) as response: + # Use synapse subclass' process_streaming_response method to yield the response chunks + async for chunk in synapse.process_streaming_response(response): # type: ignore + yield chunk # Yield each chunk as it's processed + json_response = synapse.extract_response_json(response) + + # Process the server response + self.process_server_response(response, json_response, synapse) + + # Set process time and log the response + synapse.dendrite.process_time = str(time.time() - start_time) # type: ignore + + except Exception as e: + synapse = self.process_error_message(synapse, request_name, e) # type: ignore + + finally: + self._log_incoming_response(synapse) + + # Log synapse event history + self.synapse_history.append(Synapse.from_headers(synapse.to_headers())) + + # Return the updated synapse object after deserializing if requested + if deserialize: + yield synapse.deserialize() + else: + yield synapse + + def preprocess_synapse_for_request( + self, + target_axon_info: "AxonInfo", + synapse: "Synapse", + timeout: float = 12.0, + ) -> "Synapse": + """ + Preprocesses the synapse for making a request. This includes building headers for Dendrite and Axon and signing the request. + + Args: + target_axon_info (bittensor.core.chain_data.axon_info.AxonInfo): The target axon information. + synapse (bittensor.core.synapse.Synapse): The synapse object to be preprocessed. + timeout (float): The request timeout duration in seconds. Defaults to ``12.0`` seconds. + + Returns: + bittensor.core.synapse.Synapse: The preprocessed synapse. + """ + # Set the timeout for the synapse + synapse.timeout = timeout + synapse.dendrite = TerminalInfo( + ip=self.external_ip, + version=version_as_int, + nonce=time.time_ns(), + uuid=self.uuid, + hotkey=self.keypair.ss58_address, + ) + + # Build the Axon headers using the target axon's details + synapse.axon = TerminalInfo( + ip=target_axon_info.ip, + port=target_axon_info.port, + hotkey=target_axon_info.hotkey, + ) + + # Sign the request using the dendrite, axon info, and the synapse body hash + message = f"{synapse.dendrite.nonce}.{synapse.dendrite.hotkey}.{synapse.axon.hotkey}.{synapse.dendrite.uuid}.{synapse.body_hash}" + synapse.dendrite.signature = f"0x{self.keypair.sign(message).hex()}" + + return synapse + + def process_server_response( + self, + server_response: "aiohttp.ClientResponse", + json_response: dict, + local_synapse: "Synapse", + ): + """ + Processes the server response, updates the local synapse state with the server's state and merges headers set by the server. + + Args: + server_response (object): The `aiohttp `_ response object from the server. + json_response (dict): The parsed JSON response from the server. + local_synapse (bittensor.core.synapse.Synapse): The local synapse object to be updated. + + Raises: + None: But errors in attribute setting are silently ignored. + """ + # Check if the server responded with a successful status code + if server_response.status == 200: + # If the response is successful, overwrite local synapse state with + # server's state only if the protocol allows mutation. To prevent overwrites, + # the protocol must set Frozen = True + server_synapse = local_synapse.__class__(**json_response) + for key in local_synapse.model_dump().keys(): + try: + # Set the attribute in the local synapse from the corresponding + # attribute in the server synapse + setattr(local_synapse, key, getattr(server_synapse, key)) + except Exception: + # Ignore errors during attribute setting + pass + else: + # If the server responded with an error, update the local synapse state + if local_synapse.axon is None: + local_synapse.axon = TerminalInfo() + local_synapse.axon.status_code = server_response.status + local_synapse.axon.status_message = json_response.get("message") + + # Extract server headers and overwrite None values in local synapse headers + server_headers = Synapse.from_headers(server_response.headers) # type: ignore + + # Merge dendrite headers + local_synapse.dendrite.__dict__.update( + { + **local_synapse.dendrite.model_dump(exclude_none=True), # type: ignore + **server_headers.dendrite.model_dump(exclude_none=True), # type: ignore + } + ) + + # Merge axon headers + local_synapse.axon.__dict__.update( + { + **local_synapse.axon.model_dump(exclude_none=True), # type: ignore + **server_headers.axon.model_dump(exclude_none=True), # type: ignore + } + ) + + # Update the status code and status message of the dendrite to match the axon + local_synapse.dendrite.status_code = local_synapse.axon.status_code # type: ignore + local_synapse.dendrite.status_message = local_synapse.axon.status_message # type: ignore + + def __str__(self) -> str: + """ + Returns a string representation of the Dendrite object. + + Returns: + str: The string representation of the Dendrite object in the format :func:`dendrite()`. + """ + return f"dendrite({self.keypair.ss58_address})" + + def __repr__(self) -> str: + """ + Returns a string representation of the Dendrite object, acting as a fallback for :func:`__str__()`. + + Returns: + str: The string representation of the Dendrite object in the format :func:`dendrite()`. + """ + return self.__str__() + + async def __aenter__(self): + """ + 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: + Dendrite: The current instance of the Dendrite class. + + Usage:: + async with Dendrite() as dendrite: + await dendrite.some_async_method() + """ + return self + + async def __aexit__(self, 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. + + Args: + exc_type (Type[BaseException]): The type of exception that was raised. + exc_value (BaseException): The instance of exception that was raised. + traceback (TracebackType): A traceback object encapsulating the call stack at the point where the exception was raised. + + Usage:: + import bittensor + + wallet = bittensor.Wallet() + async with bittensor.Dendrite(wallet=wallet) as dendrite: + await dendrite.some_async_method() + + Note: + This automatically closes the session by calling :func:`__aexit__` after the context closes. + """ + await self.aclose_session() + + def __del__(self): + """ + 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. + """ + self.close_session() + + +# For back-compatibility with torch +BaseModel: Union["torch.nn.Module", object] = torch.nn.Module if use_torch() else object + + +class Dendrite(DendriteMixin, BaseModel): # type: ignore + def __init__(self, wallet: Optional[Union["Wallet", "Keypair"]] = None): + if use_torch(): + torch.nn.Module.__init__(self) + DendriteMixin.__init__(self, wallet) + + +if not use_torch(): + + async def call(self, *args, **kwargs): + return await self.forward(*args, **kwargs) + + Dendrite.__call__ = call diff --git a/bittensor/core/errors.py b/bittensor/core/errors.py new file mode 100644 index 0000000000..6fd9729e8b --- /dev/null +++ b/bittensor/core/errors.py @@ -0,0 +1,129 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from __future__ import annotations + +from bittensor.core.synapse import Synapse + + +class ChainError(BaseException): + """Base error for any chain related errors.""" + + +class ChainConnectionError(ChainError): + """Error for any chain connection related errors.""" + + +class ChainTransactionError(ChainError): + """Error for any chain transaction related errors.""" + + +class ChainQueryError(ChainError): + """Error for any chain query related errors.""" + + +class StakeError(ChainTransactionError): + """Error raised when a stake transaction fails.""" + + +class UnstakeError(ChainTransactionError): + """Error raised when an unstake transaction fails.""" + + +class IdentityError(ChainTransactionError): + """Error raised when an identity transaction fails.""" + + +class NominationError(ChainTransactionError): + """Error raised when a nomination transaction fails.""" + + +class TakeError(ChainTransactionError): + """Error raised when an increase / decrease take transaction fails.""" + + +class TransferError(ChainTransactionError): + """Error raised when a transfer transaction fails.""" + + +class RegistrationError(ChainTransactionError): + """Error raised when a neuron registration transaction fails.""" + + +class NotRegisteredError(ChainTransactionError): + """Error raised when a neuron is not registered, and the transaction requires it to be.""" + + +class NotDelegateError(StakeError): + """Error raised when a hotkey you are trying to stake to is not a delegate.""" + + +class MetadataError(ChainTransactionError): + """Error raised when metadata commitment transaction fails.""" + + +class InvalidRequestNameError(Exception): + """This exception is raised when the request name is invalid. Usually indicates a broken URL.""" + + +class SynapseException(Exception): + def __init__(self, message="Synapse Exception", synapse: "Synapse" | None = None): + self.message = message + self.synapse = synapse + super().__init__(self.message) + + +class UnknownSynapseError(SynapseException): + """This exception is raised when the request name is not found in the Axon's forward_fns dictionary.""" + + +class SynapseParsingError(Exception): + """This exception is raised when the request headers are unable to be parsed into the synapse type.""" + + +class NotVerifiedException(SynapseException): + """This exception is raised when the request is not verified.""" + + +class BlacklistedException(SynapseException): + """This exception is raised when the request is blacklisted.""" + + +class PriorityException(SynapseException): + """This exception is raised when the request priority is not met.""" + + +class PostProcessException(SynapseException): + """This exception is raised when the response headers cannot be updated.""" + + +class RunException(SynapseException): + """This exception is raised when the requested function cannot be executed. Indicates a server error.""" + + +class InternalServerError(SynapseException): + """This exception is raised when the requested function fails on the server. Indicates a server error.""" + + +class SynapseDendriteNoneException(SynapseException): + def __init__( + self, + message="Synapse Dendrite is None", + synapse: "Synapse" | None = None, + ): + self.message = message + super().__init__(self.message, synapse) diff --git a/bittensor/core/extrinsics/__init__.py b/bittensor/core/extrinsics/__init__.py new file mode 100644 index 0000000000..640a132503 --- /dev/null +++ b/bittensor/core/extrinsics/__init__.py @@ -0,0 +1,16 @@ +# The MIT License (MIT) +# Copyright © 2024 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. diff --git a/bittensor/core/extrinsics/commit_weights.py b/bittensor/core/extrinsics/commit_weights.py new file mode 100644 index 0000000000..5e9f2e9e19 --- /dev/null +++ b/bittensor/core/extrinsics/commit_weights.py @@ -0,0 +1,274 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +"""Module commit weights and reveal weights extrinsic.""" + +from typing import Optional, TYPE_CHECKING + +from retry import retry +from rich.prompt import Confirm + +from bittensor.core.extrinsics.utils import submit_extrinsic +from bittensor.utils import format_error_message +from bittensor.utils.btlogging import logging +from bittensor.utils.networking import ensure_connected + +# For annotation purposes +if TYPE_CHECKING: + from bittensor_wallet import Wallet + from bittensor.core.subtensor import Subtensor + + +# # Chain call for `commit_weights_extrinsic` +@ensure_connected +def do_commit_weights( + self: "Subtensor", + wallet: "Wallet", + netuid: int, + commit_hash: str, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, +) -> tuple[bool, Optional[dict]]: + """ + Internal method to send a transaction to the Bittensor blockchain, committing the hash of a neuron's weights. + This method constructs and submits the transaction, handling retries and blockchain communication. + + Args: + self (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction. + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the weights. + netuid (int): The unique identifier of the subnet. + commit_hash (str): The hash of the neuron's weights to be committed. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + + Returns: + tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message. + + This method ensures that the weight commitment is securely recorded on the Bittensor blockchain, providing a verifiable record of the neuron's weight distribution at a specific point in time. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.substrate.compose_call( + call_module="SubtensorModule", + call_function="commit_weights", + call_params={ + "netuid": netuid, + "commit_hash": commit_hash, + }, + ) + extrinsic = self.substrate.create_signed_extrinsic( + call=call, + keypair=wallet.hotkey, + ) + response = submit_extrinsic( + substrate=self.substrate, + extrinsic=extrinsic, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + if not wait_for_finalization and not wait_for_inclusion: + return True, None + + response.process_events() + if response.is_success: + return True, None + else: + return False, response.error_message + + return make_substrate_call_with_retry() + + +def commit_weights_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + netuid: int, + commit_hash: str, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, + prompt: bool = False, +) -> tuple[bool, str]: + """ + Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet. + This function is a wrapper around the `do_commit_weights` method, handling user prompts and error messages. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction. + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the weights. + netuid (int): The unique identifier of the subnet. + commit_hash (str): The hash of the neuron's weights to be committed. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. + + Returns: + tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string + value describing the success or potential error. + + This function provides a user-friendly interface for committing weights to the Bittensor blockchain, ensuring proper error handling and user interaction when required. + """ + if prompt and not Confirm.ask(f"Would you like to commit weights?"): + return False, "User cancelled the operation." + + success, error_message = do_commit_weights( + self=subtensor, + wallet=wallet, + netuid=netuid, + commit_hash=commit_hash, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + if success: + success_message = "Successfully committed weights." + logging.info(success_message) + return True, success_message + else: + error_message = format_error_message(error_message) + logging.error(f"Failed to commit weights: {error_message}") + return False, error_message + + +# Chain call for `reveal_weights_extrinsic` +@ensure_connected +def do_reveal_weights( + self: "Subtensor", + wallet: "Wallet", + netuid: int, + uids: list[int], + values: list[int], + salt: list[int], + version_key: int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, +) -> tuple[bool, Optional[dict]]: + """ + Internal method to send a transaction to the Bittensor blockchain, revealing the weights for a specific subnet. + This method constructs and submits the transaction, handling retries and blockchain communication. + + Args: + self (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction. + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron revealing the weights. + netuid (int): The unique identifier of the subnet. + uids (list[int]): List of neuron UIDs for which weights are being revealed. + values (list[int]): List of weight values corresponding to each UID. + salt (list[int]): List of salt values corresponding to the hash function. + version_key (int): Version key for compatibility with the network. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + + Returns: + tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message. + + This method ensures that the weight revelation is securely recorded on the Bittensor blockchain, providing transparency and accountability for the neuron's weight distribution. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.substrate.compose_call( + call_module="SubtensorModule", + call_function="reveal_weights", + call_params={ + "netuid": netuid, + "uids": uids, + "values": values, + "salt": salt, + "version_key": version_key, + }, + ) + extrinsic = self.substrate.create_signed_extrinsic( + call=call, + keypair=wallet.hotkey, + ) + response = submit_extrinsic( + substrate=self.substrate, + extrinsic=extrinsic, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + if not wait_for_finalization and not wait_for_inclusion: + return True, None + + response.process_events() + if response.is_success: + return True, None + else: + return False, response.error_message + + return make_substrate_call_with_retry() + + +def reveal_weights_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + netuid: int, + uids: list[int], + weights: list[int], + salt: list[int], + version_key: int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, + prompt: bool = False, +) -> tuple[bool, str]: + """ + Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. + This function is a wrapper around the `_do_reveal_weights` method, handling user prompts and error messages. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction. + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron revealing the weights. + netuid (int): The unique identifier of the subnet. + uids (list[int]): List of neuron UIDs for which weights are being revealed. + weights (list[int]): List of weight values corresponding to each UID. + salt (list[int]): List of salt values corresponding to the hash function. + version_key (int): Version key for compatibility with the network. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. + + Returns: + tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string + value describing the success or potential error. + + This function provides a user-friendly interface for revealing weights on the Bittensor blockchain, ensuring proper error handling and user interaction when required. + """ + + if prompt and not Confirm.ask(f"Would you like to reveal weights?"): + return False, "User cancelled the operation." + + success, error_message = do_reveal_weights( + self=subtensor, + wallet=wallet, + netuid=netuid, + uids=uids, + values=weights, + salt=salt, + version_key=version_key, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + if success: + success_message = "Successfully revealed weights." + logging.info(success_message) + return True, success_message + else: + error_message = format_error_message(error_message) + logging.error(f"Failed to reveal weights: {error_message}") + return False, error_message diff --git a/bittensor/core/extrinsics/prometheus.py b/bittensor/core/extrinsics/prometheus.py new file mode 100644 index 0000000000..a6ab1cfb16 --- /dev/null +++ b/bittensor/core/extrinsics/prometheus.py @@ -0,0 +1,187 @@ +# The MIT License (MIT) +# Copyright © 2024 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 json +from typing import Optional, TYPE_CHECKING + +from retry import retry + +from bittensor.core.extrinsics.utils import submit_extrinsic +from bittensor.core.settings import version_as_int, bt_console +from bittensor.utils import networking as net, format_error_message +from bittensor.utils.btlogging import logging +from bittensor.utils.networking import ensure_connected + +# For annotation purposes +if TYPE_CHECKING: + from bittensor_wallet import Wallet + from bittensor.core.subtensor import Subtensor + from bittensor.core.types import PrometheusServeCallParams + + +# Chain call for `prometheus_extrinsic` +@ensure_connected +def do_serve_prometheus( + self: "Subtensor", + wallet: "Wallet", + call_params: "PrometheusServeCallParams", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, +) -> tuple[bool, Optional[dict]]: + """ + Sends a serve prometheus extrinsic to the chain. + + Args: + self (bittensor.core.subtensor.Subtensor): Bittensor subtensor object + wallet (bittensor_wallet.Wallet): Wallet object. + call_params (bittensor.core.types.PrometheusServeCallParams): Prometheus serve call parameters. + wait_for_inclusion (bool): If ``true``, waits for inclusion. + wait_for_finalization (bool): If ``true``, waits for finalization. + + Returns: + success (bool): ``True`` if serve prometheus was successful. + error (Optional[str]): Error message if serve prometheus failed, ``None`` otherwise. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.substrate.compose_call( + call_module="SubtensorModule", + call_function="serve_prometheus", + call_params=call_params, + ) + extrinsic = self.substrate.create_signed_extrinsic( + call=call, keypair=wallet.hotkey + ) + response = submit_extrinsic( + substrate=self.substrate, + extrinsic=extrinsic, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + if wait_for_inclusion or wait_for_finalization: + response.process_events() + if response.is_success: + return True, None + else: + return False, response.error_message + else: + return True, None + + return make_substrate_call_with_retry() + + +def prometheus_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + port: int, + netuid: int, + ip: int = None, + wait_for_inclusion: bool = False, + wait_for_finalization=True, +) -> bool: + """Subscribes a Bittensor endpoint to the Subtensor chain. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): Bittensor subtensor object. + wallet (bittensor_wallet.Wallet): Bittensor wallet object. + ip (str): Endpoint host port i.e., ``192.122.31.4``. + port (int): Endpoint port number i.e., `9221`. + netuid (int): Network `uid` to serve on. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + + Returns: + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. + """ + + # Get external ip + if ip is None: + try: + external_ip = net.get_external_ip() + bt_console.print( + f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]" + ) + logging.success(prefix="External IP", suffix="{external_ip}") + except Exception as e: + raise RuntimeError( + f"Unable to attain your external ip. Check your internet connection. error: {e}" + ) from e + else: + external_ip = ip + + call_params: "PrometheusServeCallParams" = { + "version": version_as_int, + "ip": net.ip_to_int(external_ip), + "port": port, + "ip_type": net.ip_version(external_ip), + } + + with bt_console.status(":satellite: Checking Prometheus..."): + neuron = subtensor.get_neuron_for_pubkey_and_subnet( + wallet.hotkey.ss58_address, netuid=netuid + ) + neuron_up_to_date = not neuron.is_null and call_params == { + "version": neuron.prometheus_info.version, + "ip": net.ip_to_int(neuron.prometheus_info.ip), + "port": neuron.prometheus_info.port, + "ip_type": neuron.prometheus_info.ip_type, + } + + if neuron_up_to_date: + bt_console.print( + f":white_heavy_check_mark: [green]Prometheus already Served[/green]\n" + f"[green not bold]- Status: [/green not bold] |" + f"[green not bold] ip: [/green not bold][white not bold]{neuron.prometheus_info.ip}[/white not bold] |" + f"[green not bold] ip_type: [/green not bold][white not bold]{neuron.prometheus_info.ip_type}[/white not bold] |" + f"[green not bold] port: [/green not bold][white not bold]{neuron.prometheus_info.port}[/white not bold] | " + f"[green not bold] version: [/green not bold][white not bold]{neuron.prometheus_info.version}[/white not bold] |" + ) + + bt_console.print( + f":white_heavy_check_mark: [white]Prometheus already served.[/white]" + ) + return True + + # Add netuid, not in prometheus_info + call_params["netuid"] = netuid + + with bt_console.status( + f":satellite: Serving prometheus on: [white]{subtensor.network}:{netuid}[/white] ..." + ): + success, error_message = do_serve_prometheus( + self=subtensor, + wallet=wallet, + call_params=call_params, + wait_for_finalization=wait_for_finalization, + wait_for_inclusion=wait_for_inclusion, + ) + + if wait_for_inclusion or wait_for_finalization: + if success is True: + json_ = json.dumps(call_params, indent=4, sort_keys=True) + bt_console.print( + f":white_heavy_check_mark: [green]Served prometheus[/green]\n [bold white]{json_}[/bold white]" + ) + return True + else: + bt_console.print( + f":cross_mark: [red]Failed[/red]: {format_error_message(error_message)}" + ) + return False + else: + return True diff --git a/bittensor/core/extrinsics/serving.py b/bittensor/core/extrinsics/serving.py new file mode 100644 index 0000000000..490f9c268e --- /dev/null +++ b/bittensor/core/extrinsics/serving.py @@ -0,0 +1,319 @@ +# The MIT License (MIT) +# Copyright © 2024 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 json +from typing import Optional, TYPE_CHECKING + +from retry import retry +from rich.prompt import Confirm + +from bittensor.core.errors import MetadataError +from bittensor.core.extrinsics.utils import submit_extrinsic +from bittensor.core.settings import version_as_int, bt_console +from bittensor.utils import format_error_message, networking as net +from bittensor.utils.btlogging import logging +from bittensor.utils.networking import ensure_connected + +# For annotation purposes +if TYPE_CHECKING: + from bittensor.core.axon import Axon + from bittensor.core.subtensor import Subtensor + from bittensor.core.types import AxonServeCallParams + from bittensor_wallet import Wallet + + +# Chain call for `serve_extrinsic` and `serve_axon_extrinsic` +@ensure_connected +def do_serve_axon( + self: "Subtensor", + wallet: "Wallet", + call_params: "AxonServeCallParams", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, +) -> tuple[bool, Optional[dict]]: + """ + 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. + + Args: + self (bittensor.core.subtensor.Subtensor): Subtensor instance object. + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron. + call_params (bittensor.core.types.AxonServeCallParams): Parameters required for the serve axon call. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + + Returns: + tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message. + + This function is crucial for initializing and announcing a neuron's ``Axon`` service on the network, enhancing the decentralized computation capabilities of Bittensor. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.substrate.compose_call( + call_module="SubtensorModule", + call_function="serve_axon", + call_params=call_params, + ) + extrinsic = self.substrate.create_signed_extrinsic( + call=call, keypair=wallet.hotkey + ) + response = submit_extrinsic( + substrate=self.substrate, + extrinsic=extrinsic, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + if wait_for_inclusion or wait_for_finalization: + response.process_events() + if response.is_success: + return True, None + else: + return False, response.error_message + else: + return True, None + + return make_substrate_call_with_retry() + + +def serve_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + ip: str, + port: int, + protocol: int, + netuid: int, + placeholder1: int = 0, + placeholder2: int = 0, + wait_for_inclusion: bool = False, + wait_for_finalization=True, + prompt: bool = False, +) -> bool: + """Subscribes a Bittensor endpoint to the subtensor chain. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): Subtensor instance object. + wallet (bittensor_wallet.Wallet): Bittensor wallet object. + ip (str): Endpoint host port i.e., ``192.122.31.4``. + port (int): Endpoint port number i.e., ``9221``. + protocol (int): An ``int`` representation of the protocol. + netuid (int): The network uid to serve on. + placeholder1 (int): A placeholder for future use. + placeholder2 (int): A placeholder for future use. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding. + + Returns: + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. + """ + # Decrypt hotkey + wallet.unlock_hotkey() + params: "AxonServeCallParams" = { + "version": version_as_int, + "ip": net.ip_to_int(ip), + "port": port, + "ip_type": net.ip_version(ip), + "netuid": netuid, + "hotkey": wallet.hotkey.ss58_address, + "coldkey": wallet.coldkeypub.ss58_address, + "protocol": protocol, + "placeholder1": placeholder1, + "placeholder2": placeholder2, + } + logging.debug("Checking axon ...") + neuron = subtensor.get_neuron_for_pubkey_and_subnet( + wallet.hotkey.ss58_address, netuid=netuid + ) + neuron_up_to_date = not neuron.is_null and params == { + "version": neuron.axon_info.version, + "ip": net.ip_to_int(neuron.axon_info.ip), + "port": neuron.axon_info.port, + "ip_type": neuron.axon_info.ip_type, + "netuid": neuron.netuid, + "hotkey": neuron.hotkey, + "coldkey": neuron.coldkey, + "protocol": neuron.axon_info.protocol, + "placeholder1": neuron.axon_info.placeholder1, + "placeholder2": neuron.axon_info.placeholder2, + } + output = params.copy() + output["coldkey"] = wallet.coldkeypub.ss58_address + output["hotkey"] = wallet.hotkey.ss58_address + if neuron_up_to_date: + logging.debug( + f"Axon already served on: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) " + ) + return True + + if prompt: + output = params.copy() + output["coldkey"] = wallet.coldkeypub.ss58_address + output["hotkey"] = wallet.hotkey.ss58_address + if not Confirm.ask( + f"Do you want to serve axon:\n [bold white]{json.dumps(output, indent=4, sort_keys=True)}[/bold white]" + ): + return False + + logging.debug( + f"Serving axon with: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) -> {subtensor.network}:{netuid}" + ) + success, error_message = do_serve_axon( + self=subtensor, + wallet=wallet, + call_params=params, + wait_for_finalization=wait_for_finalization, + wait_for_inclusion=wait_for_inclusion, + ) + + if wait_for_inclusion or wait_for_finalization: + if success is True: + logging.debug( + f"Axon served with: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) on {subtensor.network}:{netuid} " + ) + return True + else: + logging.error(f"Failed: {format_error_message(error_message)}") + return False + else: + return True + + +def serve_axon_extrinsic( + subtensor: "Subtensor", + netuid: int, + axon: "Axon", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, +) -> bool: + """Serves the axon to the network. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): Subtensor instance object. + netuid (int): The ``netuid`` being served on. + axon (bittensor.core.axon.Axon): Axon to serve. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + + Returns: + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. + """ + axon.wallet.unlock_hotkey() + axon.wallet.unlock_coldkeypub() + external_port = axon.external_port + + # ---- Get external ip ---- + if axon.external_ip is None: + try: + external_ip = net.get_external_ip() + bt_console.print( + f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]" + ) + logging.success(prefix="External IP", suffix=f"{external_ip}") + except Exception as e: + raise RuntimeError( + f"Unable to attain your external ip. Check your internet connection. error: {e}" + ) from e + else: + external_ip = axon.external_ip + + # ---- Subscribe to chain ---- + serve_success = serve_extrinsic( + subtensor=subtensor, + wallet=axon.wallet, + ip=external_ip, + port=external_port, + netuid=netuid, + protocol=4, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + return serve_success + + +# Community uses this extrinsic directly and via `subtensor.commit` +@net.ensure_connected +def publish_metadata( + self: "Subtensor", + wallet: "Wallet", + netuid: int, + data_type: str, + data: bytes, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, +) -> bool: + """ + Publishes metadata on the Bittensor network using the specified wallet and network identifier. + + Args: + self (bittensor.core.subtensor.Subtensor): The subtensor instance representing the Bittensor blockchain connection. + wallet (bittensor_wallet.Wallet): The wallet object used for authentication in the transaction. + netuid (int): Network UID on which the metadata is to be published. + data_type (str): The data type of the information being submitted. It should be one of the following: ``'Sha256'``, ``'Blake256'``, ``'Keccak256'``, or ``'Raw0-128'``. This specifies the format or hashing algorithm used for the data. + data (str): The actual metadata content to be published. This should be formatted or hashed according to the ``type`` specified. (Note: max ``str`` length is 128 bytes) + wait_for_inclusion (bool): If ``True``, the function will wait for the extrinsic to be included in a block before returning. Defaults to ``False``. + wait_for_finalization (bool): If ``True``, the function will wait for the extrinsic to be finalized on the chain before returning. Defaults to ``True``. + + Returns: + bool: ``True`` if the metadata was successfully published (and finalized if specified). ``False`` otherwise. + + Raises: + MetadataError: If there is an error in submitting the extrinsic or if the response from the blockchain indicates failure. + """ + + wallet.unlock_hotkey() + + with self.substrate as substrate: + call = substrate.compose_call( + call_module="Commitments", + call_function="set_commitment", + call_params={ + "netuid": netuid, + "info": {"fields": [[{f"{data_type}": data}]]}, + }, + ) + + 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 + response.process_events() + if response.is_success: + return True + else: + raise MetadataError(format_error_message(response.error_message)) + + +# Community uses this function directly +@net.ensure_connected +def get_metadata(self, netuid: int, hotkey: str, block: Optional[int] = None) -> str: + @retry(delay=2, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + with self.substrate as substrate: + return substrate.query( + module="Commitments", + storage_function="CommitmentOf", + params=[netuid, hotkey], + block_hash=None if block is None else substrate.get_block_hash(block), + ) + + commit_data = make_substrate_call_with_retry() + return commit_data.value diff --git a/bittensor/core/extrinsics/set_weights.py b/bittensor/core/extrinsics/set_weights.py new file mode 100644 index 0000000000..7680061c5b --- /dev/null +++ b/bittensor/core/extrinsics/set_weights.py @@ -0,0 +1,194 @@ +# The MIT License (MIT) +# Copyright © 2024 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 logging +from typing import Union, Optional, TYPE_CHECKING + +import numpy as np +from numpy.typing import NDArray +from retry import retry +from rich.prompt import Confirm + +from bittensor.core.extrinsics.utils import submit_extrinsic +from bittensor.core.settings import bt_console, version_as_int +from bittensor.utils import format_error_message, weight_utils +from bittensor.utils.btlogging import logging +from bittensor.utils.networking import ensure_connected +from bittensor.utils.registration import torch, use_torch + +# For annotation purposes +if TYPE_CHECKING: + from bittensor.core.subtensor import Subtensor + from bittensor_wallet import Wallet + + +# Chain call for `do_set_weights` +@ensure_connected +def do_set_weights( + self: "Subtensor", + wallet: "Wallet", + uids: list[int], + vals: list[int], + netuid: int, + version_key: int = version_as_int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, +) -> tuple[bool, Optional[dict]]: # (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: + self (bittensor.core.subtensor.Subtensor): Subtensor interface + wallet (bittensor_wallet.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): Version key for compatibility with the network. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + + Returns: + tuple[bool, Optional[str]]: A tuple containing a success flag and an optional response 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=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.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 = self.substrate.create_signed_extrinsic( + call=call, + keypair=wallet.hotkey, + era={"period": 5}, + ) + response = submit_extrinsic( + substrate=self.substrate, + 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 finalization 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() + + +# Community uses this extrinsic directly and via `subtensor.set_weights` +def set_weights_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + netuid: int, + uids: Union[NDArray[np.int64], "torch.LongTensor", list], + weights: Union[NDArray[np.float32], "torch.FloatTensor", list], + version_key: int = 0, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, + prompt: bool = False, +) -> tuple[bool, str]: + """Sets the given weights and values on chain for wallet hotkey account. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): Subtensor endpoint to use. + wallet (bittensor_wallet.Wallet): Bittensor wallet object. + netuid (int): The ``netuid`` of the subnet to set weights for. + uids (Union[NDArray[np.int64], torch.LongTensor, list]): The ``uint64`` uids of destination neurons. + weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The weights to set. These must be ``float`` s and correspond to the passed ``uid`` s. + version_key (int): The version key of the validator. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding. + + Returns: + tuple[bool, str]: A tuple containing a success flag and an optional response message. + """ + # First convert types. + if use_torch(): + if isinstance(uids, list): + uids = torch.tensor(uids, dtype=torch.int64) + if isinstance(weights, list): + weights = torch.tensor(weights, dtype=torch.float32) + else: + if isinstance(uids, list): + uids = np.array(uids, dtype=np.int64) + if isinstance(weights, list): + weights = np.array(weights, dtype=np.float32) + + # Reformat and normalize. + weight_uids, weight_vals = weight_utils.convert_weights_and_uids_for_emit( + uids, weights + ) + + # Ask before moving on. + if prompt: + if not Confirm.ask( + f"Do you want to set weights:\n[bold white] weights: {[float(v / 65535) for v in weight_vals]}\n" + f"uids: {weight_uids}[/bold white ]?" + ): + return False, "Prompt refused." + + with bt_console.status( + f":satellite: Setting weights on [white]{subtensor.network}[/white] ..." + ): + try: + success, error_message = do_set_weights( + self=subtensor, + wallet=wallet, + netuid=netuid, + uids=weight_uids, + vals=weight_vals, + version_key=version_key, + wait_for_finalization=wait_for_finalization, + wait_for_inclusion=wait_for_inclusion, + ) + + if not wait_for_finalization and not wait_for_inclusion: + return True, "Not waiting for finalization or inclusion." + + if success is True: + bt_console.print(":white_heavy_check_mark: [green]Finalized[/green]") + logging.success( + msg=str(success), + prefix="Set weights", + suffix="Finalized: ", + ) + return True, "Successfully set weights and Finalized." + else: + error_message = format_error_message(error_message) + logging.error(error_message) + return False, error_message + + except Exception as e: + bt_console.print(f":cross_mark: [red]Failed[/red]: error:{e}") + logging.debug(str(e)) + return False, str(e) diff --git a/bittensor/core/extrinsics/transfer.py b/bittensor/core/extrinsics/transfer.py new file mode 100644 index 0000000000..896fecbf96 --- /dev/null +++ b/bittensor/core/extrinsics/transfer.py @@ -0,0 +1,215 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from typing import Optional, Union, TYPE_CHECKING + +from retry import retry +from rich.prompt import Confirm + +from bittensor.core.extrinsics.utils import submit_extrinsic +from bittensor.core.settings import bt_console, NETWORK_EXPLORER_MAP +from bittensor.utils import ( + get_explorer_url_for_network, + format_error_message, + is_valid_bittensor_address_or_public_key, +) +from bittensor.utils.balance import Balance +from bittensor.utils.networking import ensure_connected + +# For annotation purposes +if TYPE_CHECKING: + from bittensor.core.subtensor import Subtensor + from bittensor_wallet import Wallet + + +# Chain call for `transfer_extrinsic` +@ensure_connected +def do_transfer( + self: "Subtensor", + wallet: "Wallet", + dest: str, + transfer_balance: "Balance", + wait_for_inclusion: bool = True, + wait_for_finalization: bool = False, +) -> tuple[bool, Optional[str], Optional[dict]]: + """Sends a transfer extrinsic to the chain. + + Args: + self (subtensor.core.subtensor.Subtensor): The Subtensor instance object. + wallet (bittensor_wallet.Wallet): Wallet object. + dest (str): Destination public key address. + transfer_balance (bittensor.utils.balance.Balance): Amount to transfer. + wait_for_inclusion (bool): If ``true``, waits for inclusion. + wait_for_finalization (bool): If ``true``, waits for finalization. + + Returns: + success (bool): ``True`` if transfer was successful. + block_hash (str): Block hash of the transfer. On success and if wait_for_ finalization/inclusion is ``True``. + error (dict): Error message from subtensor if transfer failed. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4) + def make_substrate_call_with_retry(): + call = self.substrate.compose_call( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": dest, "value": transfer_balance.rao}, + ) + extrinsic = self.substrate.create_signed_extrinsic( + call=call, keypair=wallet.coldkey + ) + response = submit_extrinsic( + substrate=self.substrate, + 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, None + + # Otherwise continue with finalization. + response.process_events() + if response.is_success: + block_hash = response.block_hash + return True, block_hash, None + else: + return False, None, response.error_message + + return make_substrate_call_with_retry() + + +# Community uses this extrinsic directly and via `subtensor.transfer` +def transfer_extrinsic( + subtensor: "Subtensor", + wallet: "Wallet", + dest: str, + amount: Union["Balance", float], + wait_for_inclusion: bool = True, + wait_for_finalization: bool = False, + keep_alive: bool = True, + prompt: bool = False, +) -> bool: + """Transfers funds from this wallet to the destination public key address. + + Args: + subtensor (subtensor.core.subtensor.Subtensor): The Subtensor instance object. + wallet (bittensor_wallet.Wallet): Bittensor wallet object to make transfer from. + dest (str, ss58_address or ed25519): Destination public key address of receiver. + amount (Union[Balance, int]): Amount to stake as Bittensor balance, or ``float`` interpreted as Tao. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + keep_alive (bool): If set, keeps the account alive by keeping the balance above the existential deposit. + prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding. + + Returns: + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. + """ + # Validate destination address. + if not is_valid_bittensor_address_or_public_key(dest): + bt_console.print( + f":cross_mark: [red]Invalid destination address[/red]:[bold white]\n {dest}[/bold white]" + ) + return False + + if isinstance(dest, bytes): + # Convert bytes to hex string. + dest = "0x" + dest.hex() + + # Unlock wallet coldkey. + wallet.unlock_coldkey() + + # Convert to bittensor.Balance + if not isinstance(amount, Balance): + transfer_balance = Balance.from_tao(amount) + else: + transfer_balance = amount + + # Check balance. + with bt_console.status(":satellite: Checking Balance..."): + account_balance = subtensor.get_balance(wallet.coldkey.ss58_address) + # check existential deposit. + existential_deposit = subtensor.get_existential_deposit() + + with bt_console.status(":satellite: Transferring..."): + fee = subtensor.get_transfer_fee( + wallet=wallet, dest=dest, value=transfer_balance.rao + ) + + if not keep_alive: + # Check if the transfer should keep_alive the account + existential_deposit = Balance(0) + + # Check if we have enough balance. + if account_balance < (transfer_balance + fee + existential_deposit): + bt_console.print( + ":cross_mark: [red]Not enough balance[/red]:[bold white]\n" + f" balance: {account_balance}\n" + f" amount: {transfer_balance}\n" + f" for fee: {fee}[/bold white]" + ) + return False + + # Ask before moving on. + if prompt: + if not Confirm.ask( + "Do you want to transfer:[bold white]\n" + f" amount: {transfer_balance}\n" + f" from: {wallet.name}:{wallet.coldkey.ss58_address}\n" + f" to: {dest}\n" + f" for fee: {fee}[/bold white]" + ): + return False + + with bt_console.status(":satellite: Transferring..."): + success, block_hash, error_message = do_transfer( + self=subtensor, + wallet=wallet, + dest=dest, + transfer_balance=transfer_balance, + wait_for_finalization=wait_for_finalization, + wait_for_inclusion=wait_for_inclusion, + ) + + if success: + bt_console.print(":white_heavy_check_mark: [green]Finalized[/green]") + bt_console.print(f"[green]Block Hash: {block_hash}[/green]") + + explorer_urls = get_explorer_url_for_network( + subtensor.network, block_hash, NETWORK_EXPLORER_MAP + ) + if explorer_urls != {} and explorer_urls: + bt_console.print( + f"[green]Opentensor Explorer Link: {explorer_urls.get('opentensor')}[/green]" + ) + bt_console.print( + f"[green]Taostats Explorer Link: {explorer_urls.get('taostats')}[/green]" + ) + else: + bt_console.print( + f":cross_mark: [red]Failed[/red]: {format_error_message(error_message)}" + ) + + if success: + with bt_console.status(":satellite: Checking Balance..."): + new_balance = subtensor.get_balance(wallet.coldkey.ss58_address) + bt_console.print( + f"Balance:\n [blue]{account_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" + ) + return True + + return False diff --git a/bittensor/core/extrinsics/utils.py b/bittensor/core/extrinsics/utils.py new file mode 100644 index 0000000000..6c896372b6 --- /dev/null +++ b/bittensor/core/extrinsics/utils.py @@ -0,0 +1,49 @@ +"""Module with helper functions for extrinsics.""" + +from typing import TYPE_CHECKING +from substrateinterface.exceptions import SubstrateRequestException +from bittensor.utils.btlogging import logging +from bittensor.utils import format_error_message + +if TYPE_CHECKING: + from substrateinterface import SubstrateInterface + from scalecodec.types import GenericExtrinsic + + +def submit_extrinsic( + substrate: "SubstrateInterface", + extrinsic: "GenericExtrinsic", + wait_for_inclusion: bool, + wait_for_finalization: bool, +): + """ + Submits an extrinsic to the substrate blockchain and handles potential exceptions. + + This function attempts to submit an extrinsic to the substrate blockchain with specified options + for waiting for inclusion in a block and/or finalization. If an exception occurs during submission, + it logs the error and re-raises the exception. + + Args: + substrate (substrateinterface.SubstrateInterface): The substrate interface instance used to interact with the blockchain. + extrinsic (scalecodec.types.GenericExtrinsic): The extrinsic to be submitted to the blockchain. + wait_for_inclusion (bool): Whether to wait for the extrinsic to be included in a block. + wait_for_finalization (bool): Whether to wait for the extrinsic to be finalized on the blockchain. + + Returns: + response: The response from the substrate after submitting the extrinsic. + + Raises: + SubstrateRequestException: If the submission of the extrinsic fails, the error is logged and re-raised. + """ + try: + response = substrate.submit_extrinsic( + extrinsic, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + except SubstrateRequestException as e: + logging.error(format_error_message(e.args[0], substrate=substrate)) + # Re-rise the exception for retrying of the extrinsic call. If we remove the retry logic, the raise will need + # to be removed. + raise + return response diff --git a/bittensor/core/metagraph.py b/bittensor/core/metagraph.py new file mode 100644 index 0000000000..208eaa6b9f --- /dev/null +++ b/bittensor/core/metagraph.py @@ -0,0 +1,1299 @@ +# The MIT License (MIT) +# Copyright © 2024 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 pickle +import typing +from abc import ABC, abstractmethod +from os import listdir +from os.path import join +from typing import Optional, Union + +import numpy as np +from numpy.typing import NDArray + +from bittensor.utils.btlogging import logging +from bittensor.utils.registration import torch, use_torch +from bittensor.utils.weight_utils import ( + convert_weight_uids_and_vals_to_tensor, + convert_bond_uids_and_vals_to_tensor, + convert_root_weight_uids_and_vals_to_tensor, +) +from . import settings +from .chain_data import AxonInfo + +# For annotation purposes +if typing.TYPE_CHECKING: + from bittensor.core.subtensor import Subtensor + + +METAGRAPH_STATE_DICT_NDARRAY_KEYS = [ + "version", + "n", + "block", + "stake", + "total_stake", + "ranks", + "trust", + "consensus", + "validator_trust", + "incentive", + "emission", + "dividends", + "active", + "last_update", + "validator_permit", + "uids", +] +"""List of keys for the metagraph state dictionary used in NDArray serialization. + +This list defines the set of keys expected in the metagraph's state dictionary when serializing and deserializing NumPy ndarray objects. Each key corresponds to a specific attribute or metric associated with the nodes in the metagraph. + +- **version** (`str`): The version identifier of the metagraph state. +- **n** (`int`): The total number of nodes in the metagraph. +- **block** (`int`): The current block number in the blockchain or ledger. +- **stake** (`ndarray`): An array representing the stake of each node. +- **total_stake** (`float`): The sum of all individual stakes in the metagraph. +- **ranks** (`ndarray`): An array of rank scores assigned to each node. +- **trust** (`ndarray`): An array of trust scores for the nodes. +- **consensus** (`ndarray`): An array indicating consensus levels among nodes. +- **validator_trust** (`ndarray`): Trust scores specific to validator nodes. +- **incentive** (`ndarray`): Incentive values allocated to nodes. +- **emission** (`float`): The rate of emission for new tokens or units. +- **dividends** (`ndarray`): Dividend amounts distributed to nodes. +- **active** (`ndarray`): Boolean array indicating active (`True`) or inactive (`False`) nodes. +- **last_update** (`int`): Timestamp of the last state update. +- **validator_permit** (`ndarray`): Boolean array indicating nodes permitted to validate. +- **uids** (`ndarray`): Unique identifiers for each node in the metagraph. +""" + + +def get_save_dir(network: str, netuid: int) -> str: + """ + Returns a directory path given ``network`` and ``netuid`` inputs. + + Args: + network (str): Network name. + netuid (int): Network UID. + + Returns: + str: Directory path. + """ + return os.path.expanduser( + os.path.join( + "~", + ".bittensor", + "metagraphs", + f"network-{str(network)}", + f"netuid-{str(netuid)}", + ) + ) + + +def latest_block_path(dir_path: str) -> str: + """ + Get the latest block path from the provided directory path. + + Args: + dir_path (str): Directory path. + + Returns: + str: Latest block path. + """ + latest_block = -1 + latest_file_full_path = None + for filename in listdir(dir_path): + full_path_filename = os.path.expanduser(join(dir_path, filename)) + try: + block_number = int(filename.split("-")[1].split(".")[0]) + if block_number > latest_block: + latest_block = block_number + latest_file_full_path = full_path_filename + except Exception: + pass + if not latest_file_full_path: + raise ValueError(f"Metagraph not found at: {dir_path}") + else: + return latest_file_full_path + + +class MetagraphMixin(ABC): + """ + 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. + + Args: + 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 (NDArray): The version number of the network, integral for tracking network updates. + n (NDArray): The total number of neurons in the network, reflecting its size and complexity. + block (NDArray): 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. + + 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: + Initializing the metagraph to represent the current state of the Bittensor network:: + + from bittensor.core.metagraph import Metagraph + metagraph = 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 + axons = metagraph.axons + neurons = metagraph.neurons + + Maintaining a local copy of hotkeys for querying and interacting with network entities:: + + hotkeys = deepcopy(metagraph.hotkeys) + """ + + netuid: int + network: str + version: Union["torch.nn.Parameter", tuple[NDArray]] + n: Union["torch.nn.Parameter", NDArray] + block: Union["torch.nn.Parameter", NDArray] + stake: Union["torch.nn.Parameter", NDArray] + total_stake: Union["torch.nn.Parameter", NDArray] + ranks: Union["torch.nn.Parameter", NDArray] + trust: Union["torch.nn.Parameter", NDArray] + consensus: Union["torch.nn.Parameter", NDArray] + validator_trust: Union["torch.nn.Parameter", NDArray] + incentive: Union["torch.nn.Parameter", NDArray] + emission: Union["torch.nn.Parameter", NDArray] + dividends: Union["torch.nn.Parameter", NDArray] + active: Union["torch.nn.Parameter", NDArray] + last_update: Union["torch.nn.Parameter", NDArray] + validator_permit: Union["torch.nn.Parameter", NDArray] + weights: Union["torch.nn.Parameter", NDArray] + bonds: Union["torch.nn.Parameter", NDArray] + uids: Union["torch.nn.Parameter", NDArray] + axons: list[AxonInfo] + + @property + def S(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor representing the stake of each neuron in the network. Higher values signify a greater stake held by the respective neuron. + """ + return self.total_stake + + @property + def R(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor where each element represents the rank of a neuron. Higher values indicate higher ranks within the network. + """ + return self.ranks + + @property + def I(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor of incentive values, indicating the rewards or benefits accrued by each neuron based on their contributions and network consensus. + """ + return self.incentive + + @property + def E(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor where each element represents the emission value for a neuron, indicating the amount of reward distributed to that neuron. + """ + return self.emission + + @property + def C(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor of consensus values, where each element reflects the level of trust and agreement a neuron has achieved within the network. + + """ + return self.consensus + + @property + def T(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: 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 self.trust + + @property + def Tv(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor of validator trust values, specifically applicable to neurons serving as validators, where higher values denote greater trustworthiness in their validation roles. + """ + return self.validator_trust + + @property + def D(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor of dividend values, where each element indicates the dividends received by a neuron, reflecting their share of network rewards. + """ + return self.dividends + + @property + def B(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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: + NDArray: A tensor representing the bonds held by each neuron, where each value signifies the proportion of bonds owned by one neuron in another. + """ + return self.bonds + + @property + def W(self) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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 :math:`W = [w_{ij}]` is a key component of the network's architecture, where the :math:`i^{th}` row is set by + neuron :math:`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: + NDArray: A tensor of inter-peer weights, where each element :math:`w_{ij}` represents the weight assigned by neuron :math:`i` to neuron :math:`j`. This matrix is fundamental to the network's functioning, influencing the distribution of incentives and the inter-neuronal dynamics. + """ + return self.weights + + @property + def hotkeys(self) -> 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: + List[str]: 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. + + 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. + """ + return [axon.hotkey for axon in self.axons] + + @property + def coldkeys(self) -> 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: + List[str]: 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. + + 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. + """ + return [axon.coldkey for axon in self.axons] + + @property + def addresses(self) -> 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: + List[str]: 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. + + 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. + """ + return [axon.ip_str() for axon in self.axons] + + @abstractmethod + def __init__( + self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True + ): + """ + Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments. + This method is the entry point for creating a metagraph object, + which is a central component in representing the state of the Bittensor network. + + Args: + netuid (int): The unique identifier for the network, distinguishing this instance of the metagraph within potentially multiple network configurations. + network (str): The name of the network, which can indicate specific configurations or versions of the Bittensor network. + lite (bool): A flag indicating whether to use a lite version of the metagraph. The lite version may contain less detailed information but can be quicker to initialize and sync. + sync (bool): A flag indicating whether to synchronize the metagraph with the network upon initialization. Synchronization involves updating the metagraph's parameters to reflect the current state of the network. + + Example: + Initializing a metagraph object for the Bittensor network with a specific network UID:: + + metagraph = metagraph(netuid=123, network="finney", lite=True, sync=True) + + """ + + def __str__(self) -> 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: + str: 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. + + 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)" + """ + return f"metagraph(netuid:{self.netuid}, n:{self.n.item()}, block:{self.block.item()}, network:{self.network})" + + def __repr__(self) -> str: + """ + Provides a detailed string representation of the metagraph object, intended for unambiguous understanding and debugging purposes. This method simply calls the :func:`__str__` method, ensuring + consistency between the informal and formal string representations of the metagraph. + + Returns: + str: The same string representation as provided by the :func:`__str__` method, detailing the metagraph's key attributes including network UID, number of neurons, block number, and network name. + + Example: + The :func:`__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__ + """ + return self.__str__() + + def metadata(self) -> dict: + """ + 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: + dict: 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. + + Note: + This metadata is crucial for understanding the current state and configuration of the network, as well as for tracking its evolution over time. + """ + return { + "netuid": self.netuid, + "n": self.n.item(), + "block": self.block.item(), + "network": self.network, + "version": settings.__version__, + } + + def state_dict(self): + return { + "netuid": self.netuid, + "network": self.network, + "version": self.version, + "n": self.n, + "block": self.block, + "stake": self.stake, + "total_stake": self.total_stake, + "ranks": self.ranks, + "trust": self.trust, + "consensus": self.consensus, + "validator_trust": self.validator_trust, + "incentive": self.incentive, + "emission": self.emission, + "dividends": self.dividends, + "active": self.active, + "last_update": self.last_update, + "validator_permit": self.validator_permit, + "weights": self.weights, + "bonds": self.bonds, + "uids": self.uids, + "axons": self.axons, + "neurons": self.neurons, + } + + def sync( + self, + block: Optional[int] = None, + lite: bool = True, + subtensor: Optional["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. + + Args: + 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.core.subtensor.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. + + Example: + Sync the metagraph with the latest block from the subtensor, using the lite version for efficiency:: + + from bittensor.core.subtensor import Subtensor + + subtensor = Subtensor() + metagraph.sync(subtensor=subtensor) + + Sync with a specific block number for detailed analysis:: + + from bittensor.core.subtensor import Subtensor + + subtensor = Subtensor() + 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:: + + from bittensor.core.subtensor import Subtensor + + subtensor = Subtensor(network='archive') + current_block = subtensor.get_current_block() + history_block = current_block - 1200 + + metagraph.sync(block=history_block, lite=False, subtensor=subtensor) + """ + + # Initialize subtensor + subtensor = self._initialize_subtensor(subtensor) + + if ( + subtensor.chain_endpoint != settings.ARCHIVE_ENTRYPOINT + or subtensor.network != settings.NETWORKS[3] + ): + cur_block = subtensor.get_current_block() + if block and block < (cur_block - 300): + logging.warning( + "Attempting to sync longer than 300 blocks ago on a non-archive node. Please use the 'archive' " + "network for subtensor and retry." + ) + + # Assign neurons based on 'lite' flag + self._assign_neurons(block, lite, subtensor) + + # Set attributes for metagraph + self._set_metagraph_attributes(block, subtensor) + + # If not a 'lite' version, compute and set weights and bonds for each neuron + if not lite: + self._set_weights_and_bonds(subtensor=subtensor) + + def _initialize_subtensor(self, 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. + + Args: + subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance provided for initialization. If ``None``, a new subtensor instance is created using the current network configuration. + + Returns: + subtensor (bittensor.core.subtensor.Subtensor): The initialized subtensor instance, ready to be used for syncing the metagraph. + + Internal Usage: + Used internally during the sync process to ensure a valid subtensor instance is available:: + + subtensor = self._initialize_subtensor(subtensor) + """ + if not subtensor: + # TODO: Check and test the initialization of the new subtensor + # Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor) + from bittensor.core.subtensor import Subtensor + + subtensor = Subtensor(network=self.network) + return subtensor + + def _assign_neurons(self, block: int, lite: bool, subtensor: "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. + + Args: + block (int): The block number for which the neuron data needs to be fetched. If ``None``, the latest block data is used. + lite (bool): 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 (bittensor.core.subtensor.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:: + + from bittensor.core.subtensor import Subtensor + + block = 12345 + lite = False + subtensor = Subtensor() + self._assign_neurons(block, lite, subtensor) + """ + if lite: + self.neurons = subtensor.neurons_lite(block=block, netuid=self.netuid) + else: + self.neurons = subtensor.neurons(block=block, netuid=self.netuid) + self.lite = lite + + @staticmethod + def _create_tensor(data, dtype) -> Union[NDArray, "torch.nn.Parameter"]: + """ + Creates a numpy array with the given data and data type. This method is a utility function used internally to encapsulate data into a np.array, making it compatible with the metagraph's numpy model structure. + + Args: + 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 numpy data type like ``np.float32`` or ``np.int64``. + + Returns: + A tensor parameter encapsulating the provided data. + + Internal Usage: + Used internally to create tensor parameters for various metagraph attributes:: + + self.stake = self._create_tensor(neuron_stakes, dtype=np.float32) + """ + # TODO: Check and test the creation of tensor + return ( + torch.nn.Parameter(torch.tensor(data, dtype=dtype), requires_grad=False) + if use_torch() + else np.array(data, dtype=dtype) + ) + + def _set_weights_and_bonds(self, subtensor: "Optional[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. + + Args: + 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) + """ + # TODO: Check and test the computation of weights and bonds + if self.netuid == 0: + self.weights = self._process_root_weights( + [neuron.weights for neuron in self.neurons], + "weights", + subtensor, + ) + else: + self.weights = self._process_weights_or_bonds( + [neuron.weights for neuron in self.neurons], "weights" + ) + self.bonds = self._process_weights_or_bonds( + [neuron.bonds for neuron in self.neurons], "bonds" + ) + + def _process_weights_or_bonds( + self, data, attribute: str + ) -> Union[NDArray, "torch.nn.Parameter"]: + """ + 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`` or ``bonds``) from a list or other unstructured format into a tensor that can be utilized within the metagraph model. + + Args: + data: The raw weights or bonds data to be processed. This data typically comes from the subtensor. + attribute: A string indicating whether the data is ``weights`` or ``bonds``, which determines the specific processing steps to be applied. + + Returns: + A tensor parameter encapsulating the processed weights or bonds data. + + 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") + """ + data_array = [] + for item in data: + if len(item) == 0: + if use_torch(): + data_array.append(torch.zeros(len(self.neurons))) + else: + data_array.append(np.zeros(len(self.neurons), dtype=np.float32)) + else: + uids, values = zip(*item) + # TODO: Validate and test the conversion of uids and values to tensor + if attribute == "weights": + data_array.append( + convert_weight_uids_and_vals_to_tensor( + len(self.neurons), + list(uids), + list(values), + ) + ) + else: + data_array.append( + convert_bond_uids_and_vals_to_tensor( + len(self.neurons), list(uids), list(values) + ).astype(np.float32) + ) + tensor_param: Union["torch.nn.Parameter", NDArray] = ( + ( + torch.nn.Parameter(torch.stack(data_array), requires_grad=False) + if len(data_array) + else torch.nn.Parameter() + ) + if use_torch() + else ( + np.stack(data_array) + if len(data_array) + else np.array([], dtype=np.float32) + ) + ) + if len(data_array) == 0: + logging.warning( + f"Empty {attribute}_array on metagraph.sync(). The '{attribute}' tensor is empty." + ) + return tensor_param + + @abstractmethod + def _set_metagraph_attributes(self, block, subtensor): + pass + + def _process_root_weights( + self, data: list, attribute: str, subtensor: "Subtensor" + ) -> Union[NDArray, "torch.nn.Parameter"]: + """ + Specifically processes the root weights data for the metagraph. This method is similar to :func:`_process_weights_or_bonds` but is tailored for processing root weights, which have a different structure and significance in the network. + + Args: + data (list): The raw root weights data to be processed. + attribute (str): A string indicating the attribute type, here it's typically ``weights``. + subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for additional data and context needed in processing. + + Returns: + A tensor parameter encapsulating the processed root weights data. + + 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) + """ + data_array = [] + n_subnets = subtensor.get_total_subnets() or 0 + subnets = subtensor.get_subnets() + for item in data: + if len(item) == 0: + if use_torch(): + data_array.append(torch.zeros(n_subnets)) + else: + data_array.append(np.zeros(n_subnets, dtype=np.float32)) + else: + uids, values = zip(*item) + # TODO: Validate and test the conversion of uids and values to tensor + data_array.append( + convert_root_weight_uids_and_vals_to_tensor( + n_subnets, list(uids), list(values), subnets + ) + ) + + tensor_param: Union[NDArray, "torch.nn.Parameter"] = ( + ( + torch.nn.Parameter(torch.stack(data_array), requires_grad=False) + if len(data_array) + else torch.nn.Parameter() + ) + if use_torch() + else ( + np.stack(data_array) + if len(data_array) + else np.array([], dtype=np.float32) + ) + ) + if len(data_array) == 0: + logging.warning( + f"Empty {attribute}_array on metagraph.sync(). The '{attribute}' tensor is empty." + ) + return tensor_param + + def save(self) -> "Metagraph": + """ + 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: + metagraph (bittensor.core.metagraph.Metagraph): The metagraph instance after saving its state. + + 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) + """ + save_directory = get_save_dir(self.network, self.netuid) + os.makedirs(save_directory, exist_ok=True) + if use_torch(): + graph_filename = f"{save_directory}/block-{self.block.item()}.pt" + state_dict = self.state_dict() + state_dict["axons"] = self.axons + state_dict["neurons"] = self.neurons + torch.save(state_dict, graph_filename) + torch.load(graph_filename) # verifies that the file can be loaded correctly + else: + graph_filename = f"{save_directory}/block-{self.block.item()}.pt" + state_dict = self.state_dict() + with open(graph_filename, "wb") as graph_file: + pickle.dump(state_dict, graph_file) + return self + + def load(self): + """ + 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`` and ``netuid`` 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 current ``network`` and ``netuid`` properties. This abstraction simplifies the process of loading the metagraph's state for the user, requiring no direct path specifications. + + Returns: + metagraph (bittensor.core.metagraph.Metagraph): The metagraph instance after loading its state from the default directory. + + 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`` and ``netuid`` 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. + """ + self.load_from_path(get_save_dir(self.network, self.netuid)) + + @abstractmethod + def load_from_path(self, dir_path: str) -> "Metagraph": + """ + 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. + + Args: + 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: + metagraph (bittensor.core.metagraph.Metagraph): The metagraph instance after loading its state from the specified directory path. + + 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. + """ + + +BaseClass: Union["torch.nn.Module", object] = torch.nn.Module if use_torch() else object +""" +Base class that extends :class:`torch.nn.Module` if PyTorch is used; otherwise, it defaults to object. +""" + + +class TorchMetaGraph(MetagraphMixin, BaseClass): + def __init__( + self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True + ): + """ + Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments. + This class requires Torch to be installed. + This method is the entry point for creating a metagraph object, which is a central component in representing the state of the Bittensor network. + + Args: + netuid (int): The unique identifier for the network, distinguishing this instance of the metagraph within potentially multiple network configurations. + network (str): The name of the network, which can indicate specific configurations or versions of the Bittensor network. + lite (bool): A flag indicating whether to use a lite version of the metagraph. The lite version may contain less detailed information but can be quicker to initialize and sync. + sync (bool): A flag indicating whether to synchronize the metagraph with the network upon initialization. Synchronization involves updating the metagraph's parameters to reflect the current state of the network. + + Example: + Initializing a metagraph object for the Bittensor network with a specific network UID:: + + from bittensor.core.metagraph import Metagraph + + metagraph = Metagraph(netuid=123, network="finney", lite=True, sync=True) + """ + torch.nn.Module.__init__(self) + MetagraphMixin.__init__(self, netuid, network, lite, sync) + self.netuid = netuid + self.network = network + self.version = torch.nn.Parameter( + torch.tensor([settings.version_as_int], dtype=torch.int64), + requires_grad=False, + ) + self.n: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([0], dtype=torch.int64), requires_grad=False + ) + self.block: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([0], dtype=torch.int64), requires_grad=False + ) + self.stake = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.total_stake: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.ranks: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.trust: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.consensus: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.validator_trust: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.incentive: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.emission: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.dividends: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.active = torch.nn.Parameter( + torch.tensor([], dtype=torch.int64), requires_grad=False + ) + self.last_update = torch.nn.Parameter( + torch.tensor([], dtype=torch.int64), requires_grad=False + ) + self.validator_permit = torch.nn.Parameter( + torch.tensor([], dtype=torch.bool), requires_grad=False + ) + self.weights: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.float32), requires_grad=False + ) + self.bonds: torch.nn.Parameter = torch.nn.Parameter( + torch.tensor([], dtype=torch.int64), requires_grad=False + ) + self.uids = torch.nn.Parameter( + torch.tensor([], dtype=torch.int64), requires_grad=False + ) + self.axons: list[AxonInfo] = [] + if sync: + self.sync(block=None, lite=lite) + + def _set_metagraph_attributes(self, block: int, subtensor: "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. + + Args: + block (int): The block number for which the metagraph attributes need to be set. If ``None``, the latest block data is used. + subtensor (bittensor.core.subtensor.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:: + + from bittensor.core.subtensor import Subtensor + + subtensor = Subtensor() + block = subtensor.get_current_block() + + self._set_metagraph_attributes(block, subtensor) + """ + self.n = self._create_tensor(len(self.neurons), dtype=torch.int64) + self.version = self._create_tensor([settings.version_as_int], dtype=torch.int64) + self.block = self._create_tensor( + block if block else subtensor.block, dtype=torch.int64 + ) + self.uids = self._create_tensor( + [neuron.uid for neuron in self.neurons], dtype=torch.int64 + ) + self.trust = self._create_tensor( + [neuron.trust for neuron in self.neurons], dtype=torch.float32 + ) + self.consensus = self._create_tensor( + [neuron.consensus for neuron in self.neurons], dtype=torch.float32 + ) + self.incentive = self._create_tensor( + [neuron.incentive for neuron in self.neurons], dtype=torch.float32 + ) + self.dividends = self._create_tensor( + [neuron.dividends for neuron in self.neurons], dtype=torch.float32 + ) + self.ranks = self._create_tensor( + [neuron.rank for neuron in self.neurons], dtype=torch.float32 + ) + self.emission = self._create_tensor( + [neuron.emission for neuron in self.neurons], dtype=torch.float32 + ) + self.active = self._create_tensor( + [neuron.active for neuron in self.neurons], dtype=torch.int64 + ) + self.last_update = self._create_tensor( + [neuron.last_update for neuron in self.neurons], dtype=torch.int64 + ) + self.validator_permit = self._create_tensor( + [neuron.validator_permit for neuron in self.neurons], dtype=torch.bool + ) + self.validator_trust = self._create_tensor( + [neuron.validator_trust for neuron in self.neurons], dtype=torch.float32 + ) + self.total_stake = self._create_tensor( + [neuron.total_stake.tao for neuron in self.neurons], dtype=torch.float32 + ) + self.stake = self._create_tensor( + [neuron.stake for neuron in self.neurons], dtype=torch.float32 + ) + self.axons = [n.axon_info for n in self.neurons] + + def load_from_path(self, dir_path: str) -> "Metagraph": + """ + Loads the metagraph state from a specified directory path. + + Args: + dir_path (str): The directory path where the state file is located. + + Returns: + metagraph (bittensor.core.metagraph.Metagraph): The current metagraph instance with the loaded state. + + Example:: + + from bittensor.core.metagraph import Metagraph + + netuid = 1 + metagraph = Metagraph(netuid=netuid) + + metagraph.load_from_path("/path/to/dir") + + """ + + graph_file = latest_block_path(dir_path) + state_dict = torch.load(graph_file) + self.n = torch.nn.Parameter(state_dict["n"], requires_grad=False) + self.block = torch.nn.Parameter(state_dict["block"], requires_grad=False) + self.uids = torch.nn.Parameter(state_dict["uids"], requires_grad=False) + self.stake = torch.nn.Parameter(state_dict["stake"], requires_grad=False) + self.total_stake = torch.nn.Parameter( + state_dict["total_stake"], requires_grad=False + ) + self.ranks = torch.nn.Parameter(state_dict["ranks"], requires_grad=False) + self.trust = torch.nn.Parameter(state_dict["trust"], requires_grad=False) + self.consensus = torch.nn.Parameter( + state_dict["consensus"], requires_grad=False + ) + self.validator_trust = torch.nn.Parameter( + state_dict["validator_trust"], requires_grad=False + ) + self.incentive = torch.nn.Parameter( + state_dict["incentive"], requires_grad=False + ) + self.emission = torch.nn.Parameter(state_dict["emission"], requires_grad=False) + self.dividends = torch.nn.Parameter( + state_dict["dividends"], requires_grad=False + ) + self.active = torch.nn.Parameter(state_dict["active"], requires_grad=False) + self.last_update = torch.nn.Parameter( + state_dict["last_update"], requires_grad=False + ) + self.validator_permit = torch.nn.Parameter( + state_dict["validator_permit"], requires_grad=False + ) + self.uids = torch.nn.Parameter(state_dict["uids"], requires_grad=False) + self.axons = state_dict["axons"] + self.neurons = state_dict["neurons"] + if "weights" in state_dict: + self.weights = torch.nn.Parameter( + state_dict["weights"], requires_grad=False + ) + if "bonds" in state_dict: + self.bonds = torch.nn.Parameter(state_dict["bonds"], requires_grad=False) + return self + + +class NonTorchMetagraph(MetagraphMixin): + def __init__( + self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True + ): + """ + Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments. + This class doesn't require installed Torch. + This method is the entry point for creating a metagraph object, which is a central component in representing the state of the Bittensor network. + + Args: + netuid (int): The unique identifier for the network, distinguishing this instance of the metagraph within potentially multiple network configurations. + network (str): The name of the network, which can indicate specific configurations or versions of the Bittensor network. + lite (bool): A flag indicating whether to use a lite version of the metagraph. The lite version may contain less detailed information but can be quicker to initialize and sync. + sync (bool): A flag indicating whether to synchronize the metagraph with the network upon initialization. Synchronization involves updating the metagraph's parameters to reflect the current state of the network. + + Example: + Initializing a metagraph object for the Bittensor network with a specific network UID:: + + from bittensor.core.metagraph import Metagraph + + metagraph = Metagraph(netuid=123, network="finney", lite=True, sync=True) + """ + # super(metagraph, self).__init__() + MetagraphMixin.__init__(self, netuid, network, lite, sync) + + self.netuid = netuid + self.network = network + self.version = (np.array([settings.version_as_int], dtype=np.int64),) + self.n = np.array([0], dtype=np.int64) + self.block = np.array([0], dtype=np.int64) + self.stake = np.array([], dtype=np.float32) + self.total_stake = np.array([], dtype=np.float32) + self.ranks = np.array([], dtype=np.float32) + self.trust = np.array([], dtype=np.float32) + self.consensus = np.array([], dtype=np.float32) + self.validator_trust = np.array([], dtype=np.float32) + self.incentive = np.array([], dtype=np.float32) + self.emission = np.array([], dtype=np.float32) + self.dividends = np.array([], dtype=np.float32) + self.active = np.array([], dtype=np.int64) + self.last_update = np.array([], dtype=np.int64) + self.validator_permit = np.array([], dtype=bool) + self.weights = np.array([], dtype=np.float32) + self.bonds = np.array([], dtype=np.int64) + self.uids = np.array([], dtype=np.int64) + self.axons: list[AxonInfo] = [] + if sync: + self.sync(block=None, lite=lite) + + def _set_metagraph_attributes(self, block: int, subtensor: "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. + + Args: + block (int): The block number for which the metagraph attributes need to be set. If ``None``, the latest block data is used. + subtensor (bittensor.core.subtensor.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) + """ + # TODO: Check and test the setting of each attribute + self.n = self._create_tensor(len(self.neurons), dtype=np.int64) + self.version = self._create_tensor([settings.version_as_int], dtype=np.int64) + self.block = self._create_tensor( + block if block else subtensor.block, dtype=np.int64 + ) + self.uids = self._create_tensor( + [neuron.uid for neuron in self.neurons], dtype=np.int64 + ) + self.trust = self._create_tensor( + [neuron.trust for neuron in self.neurons], dtype=np.float32 + ) + self.consensus = self._create_tensor( + [neuron.consensus for neuron in self.neurons], dtype=np.float32 + ) + self.incentive = self._create_tensor( + [neuron.incentive for neuron in self.neurons], dtype=np.float32 + ) + self.dividends = self._create_tensor( + [neuron.dividends for neuron in self.neurons], dtype=np.float32 + ) + self.ranks = self._create_tensor( + [neuron.rank for neuron in self.neurons], dtype=np.float32 + ) + self.emission = self._create_tensor( + [neuron.emission for neuron in self.neurons], dtype=np.float32 + ) + self.active = self._create_tensor( + [neuron.active for neuron in self.neurons], dtype=np.int64 + ) + self.last_update = self._create_tensor( + [neuron.last_update for neuron in self.neurons], dtype=np.int64 + ) + self.validator_permit = self._create_tensor( + [neuron.validator_permit for neuron in self.neurons], dtype=bool + ) + self.validator_trust = self._create_tensor( + [neuron.validator_trust for neuron in self.neurons], dtype=np.float32 + ) + self.total_stake = self._create_tensor( + [neuron.total_stake.tao for neuron in self.neurons], dtype=np.float32 + ) + self.stake = self._create_tensor( + [neuron.stake for neuron in self.neurons], dtype=np.float32 + ) + self.axons = [n.axon_info for n in self.neurons] + + def load_from_path(self, dir_path: str) -> "Metagraph": + """ + Loads the state of the Metagraph from a specified directory path. + + Args: + dir_path (str): The directory path where the metagraph's state file is located. + + Returns: + metagraph (:func:`bittensor.core.metagraph.Metagraph`): An instance of the Metagraph with the state loaded from the file. + + Raises: + pickle.UnpicklingError: If there is an error unpickling the state file. + RuntimeError: If there is an error loading the state file using PyTorch. + ImportError: If there is an error importing PyTorch. + """ + graph_filename = latest_block_path(dir_path) + try: + with open(graph_filename, "rb") as graph_file: + state_dict = pickle.load(graph_file) + except pickle.UnpicklingError: + settings.bt_console.print( + "Unable to load file. Attempting to restore metagraph using torch." + ) + settings.bt_console.print( + ":warning:[yellow]Warning:[/yellow] This functionality exists to load " + "metagraph state from legacy saves, but will not be supported in the future." + ) + try: + import torch as real_torch + + state_dict = real_torch.load(graph_filename) + for key in METAGRAPH_STATE_DICT_NDARRAY_KEYS: + state_dict[key] = state_dict[key].detach().numpy() + del real_torch + except (RuntimeError, ImportError): + settings.bt_console.print("Unable to load file. It may be corrupted.") + raise + + self.n = state_dict["n"] + self.block = state_dict["block"] + self.uids = state_dict["uids"] + self.stake = state_dict["stake"] + self.total_stake = state_dict["total_stake"] + self.ranks = state_dict["ranks"] + self.trust = state_dict["trust"] + self.consensus = state_dict["consensus"] + self.validator_trust = state_dict["validator_trust"] + self.incentive = state_dict["incentive"] + self.emission = state_dict["emission"] + self.dividends = state_dict["dividends"] + self.active = state_dict["active"] + self.last_update = state_dict["last_update"] + self.validator_permit = state_dict["validator_permit"] + self.axons = state_dict["axons"] + self.neurons = state_dict["neurons"] + if "weights" in state_dict: + self.weights = state_dict["weights"] + if "bonds" in state_dict: + self.bonds = state_dict["bonds"] + return self + + +Metagraph = TorchMetaGraph if use_torch() else NonTorchMetagraph +"""Metagraph class that uses :class:`TorchMetaGraph` if PyTorch is available; otherwise, it falls back to :class:`NonTorchMetagraph`. + +- **With PyTorch**: When `use_torch()` returns `True`, `Metagraph` is set to :class:`TorchMetaGraph`, which utilizes PyTorch functionalities. +- **Without PyTorch**: When `use_torch()` returns `False`, `Metagraph` is set to :class:`NonTorchMetagraph`, which does not rely on PyTorch. +""" diff --git a/bittensor/core/settings.py b/bittensor/core/settings.py new file mode 100644 index 0000000000..cfccf362be --- /dev/null +++ b/bittensor/core/settings.py @@ -0,0 +1,241 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +__version__ = "8.0.0" + +import os +import re +import warnings +from pathlib import Path + +from munch import munchify +from rich.console import Console +from rich.traceback import install + +# Rich console. +__console__ = Console() +__use_console__ = True + +# Remove overdue locals in debug training. +install(show_locals=False) + + +def turn_console_off(): + global __use_console__ + global __console__ + from io import StringIO + + __use_console__ = False + __console__ = Console(file=StringIO(), stderr=False) + + +def turn_console_on(): + global __use_console__ + global __console__ + __use_console__ = True + __console__ = Console() + + +turn_console_off() + +bt_console = __console__ + + +HOME_DIR = Path.home() +USER_BITTENSOR_DIR = HOME_DIR / ".bittensor" +WALLETS_DIR = USER_BITTENSOR_DIR / "wallets" +MINERS_DIR = USER_BITTENSOR_DIR / "miners" + +# Bittensor networks name +NETWORKS = ["local", "finney", "test", "archive"] + +DEFAULT_ENDPOINT = "wss://entrypoint-finney.opentensor.ai:443" +DEFAULT_NETWORK = NETWORKS[1] + +# Create dirs if they don't exist +WALLETS_DIR.mkdir(parents=True, exist_ok=True) +MINERS_DIR.mkdir(parents=True, exist_ok=True) + + +# Bittensor endpoints (Needs to use wss://) +FINNEY_ENTRYPOINT = "wss://entrypoint-finney.opentensor.ai:443" +FINNEY_TEST_ENTRYPOINT = "wss://test.finney.opentensor.ai:443/" +ARCHIVE_ENTRYPOINT = "wss://archive.chain.opentensor.ai:443/" +LOCAL_ENTRYPOINT = os.getenv("BT_SUBTENSOR_CHAIN_ENDPOINT") or "ws://127.0.0.1:9946" + +# Currency Symbols Bittensor +TAO_SYMBOL: str = chr(0x03C4) +RAO_SYMBOL: str = chr(0x03C1) + +# Pip address for versioning +PIPADDRESS = "https://pypi.org/pypi/bittensor/json" + +# Substrate chain block time (seconds). +BLOCKTIME = 12 + +# Substrate ss58_format +SS58_FORMAT = 42 + +# Wallet ss58 address length +SS58_ADDRESS_LENGTH = 48 + +# Raw GitHub url for delegates registry file +DELEGATES_DETAILS_URL = "https://raw.githubusercontent.com/opentensor/bittensor-delegates/main/public/delegates.json" + +# Block Explorers map network to explorer url +# Must all be polkadotjs explorer urls +NETWORK_EXPLORER_MAP = { + "opentensor": { + "local": "https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fentrypoint-finney.opentensor.ai%3A443#/explorer", + "endpoint": "https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fentrypoint-finney.opentensor.ai%3A443#/explorer", + "finney": "https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fentrypoint-finney.opentensor.ai%3A443#/explorer", + }, + "taostats": { + "local": "https://x.taostats.io", + "endpoint": "https://x.taostats.io", + "finney": "https://x.taostats.io", + }, +} + +# --- Type Registry --- +TYPE_REGISTRY: dict = { + "types": { + "Balance": "u64", # Need to override default u128 + }, + "runtime_api": { + "NeuronInfoRuntimeApi": { + "methods": { + "get_neuron_lite": { + "params": [ + { + "name": "netuid", + "type": "u16", + }, + { + "name": "uid", + "type": "u16", + }, + ], + "type": "Vec", + }, + "get_neurons_lite": { + "params": [ + { + "name": "netuid", + "type": "u16", + }, + ], + "type": "Vec", + }, + } + }, + "SubnetInfoRuntimeApi": { + "methods": { + "get_subnet_hyperparams": { + "params": [ + { + "name": "netuid", + "type": "u16", + }, + ], + "type": "Vec", + } + } + }, + "SubnetRegistrationRuntimeApi": { + "methods": {"get_network_registration_cost": {"params": [], "type": "u64"}} + }, + }, +} + + +_BT_AXON_PORT = os.getenv("BT_AXON_PORT") +_BT_AXON_MAX_WORKERS = os.getenv("BT_AXON_MAX_WORKERS") +_BT_PRIORITY_MAX_WORKERS = os.getenv("BT_PRIORITY_MAX_WORKERS") +_BT_PRIORITY_MAXSIZE = os.getenv("BT_PRIORITY_MAXSIZE") + +DEFAULTS = munchify( + { + "axon": { + "port": int(_BT_AXON_PORT) if _BT_AXON_PORT else 8091, + "ip": os.getenv("BT_AXON_IP") or "[::]", + "external_port": os.getenv("BT_AXON_EXTERNAL_PORT") or None, + "external_ip": os.getenv("BT_AXON_EXTERNAL_IP") or None, + "max_workers": int(_BT_AXON_MAX_WORKERS) if _BT_AXON_MAX_WORKERS else 10, + }, + "logging": { + "debug": os.getenv("BT_LOGGING_DEBUG") or False, + "trace": os.getenv("BT_LOGGING_TRACE") or False, + "record_log": os.getenv("BT_LOGGING_RECORD_LOG") or False, + "logging_dir": os.getenv("BT_LOGGING_LOGGING_DIR") or str(MINERS_DIR), + }, + "priority": { + "max_workers": int(_BT_PRIORITY_MAX_WORKERS) + if _BT_PRIORITY_MAX_WORKERS + else 5, + "maxsize": int(_BT_PRIORITY_MAXSIZE) if _BT_PRIORITY_MAXSIZE else 10, + }, + "subtensor": { + "chain_endpoint": DEFAULT_ENDPOINT, + "network": DEFAULT_NETWORK, + "_mock": False, + }, + "wallet": { + "name": "default", + "hotkey": "default", + "path": str(WALLETS_DIR), + }, + } +) + + +# Parsing version without any literals. +__version__ = re.match(r"^\d+\.\d+\.\d+", __version__).group(0) + +version_split = __version__.split(".") +_version_info = tuple(int(part) for part in version_split) +_version_int_base = 1000 +assert max(_version_info) < _version_int_base + +version_as_int: int = sum( + e * (_version_int_base**i) for i, e in enumerate(reversed(_version_info)) +) +assert version_as_int < 2**31 # fits in int32 + + +def __apply_nest_asyncio(): + """ + Apply nest_asyncio if the environment variable NEST_ASYNCIO is set to "1" or not set. + If not set, warn the user that the default will change in the future. + """ + nest_asyncio_env = os.getenv("NEST_ASYNCIO") + if nest_asyncio_env == "1" or nest_asyncio_env is None: + if nest_asyncio_env is None: + warnings.warn( + """NEST_ASYNCIO implicitly set to '1'. In the future, the default value will be '0'. + If you use `nest_asyncio`, make sure to add it explicitly to your project dependencies, + as it will be removed from `bittensor` package dependencies in the future. + To silence this warning, explicitly set the environment variable, e.g. `export NEST_ASYNCIO=0`.""", + DeprecationWarning, + ) + # Install and apply nest asyncio to allow the async functions to run in a .ipynb + import nest_asyncio + + nest_asyncio.apply() + + +__apply_nest_asyncio() diff --git a/bittensor/core/stream.py b/bittensor/core/stream.py new file mode 100644 index 0000000000..9e880ffa87 --- /dev/null +++ b/bittensor/core/stream.py @@ -0,0 +1,158 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from abc import ABC, abstractmethod +from typing import Callable, Awaitable, Optional + +from aiohttp import ClientResponse +from pydantic import ConfigDict, BaseModel +from starlette.responses import StreamingResponse as _StreamingResponse +from starlette.types import Send, Receive, Scope + +from .synapse import Synapse + + +class BTStreamingResponseModel(BaseModel): + """ + :func:`BTStreamingResponseModel` is a Pydantic model that encapsulates the token streamer callable for Pydantic validation. + It is used within the :func:`StreamingSynapse` class to create a :func:`BTStreamingResponse` 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. + + Attributes: + 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. + """ + + token_streamer: Callable[[Send], Awaitable[None]] + + +class StreamingSynapse(Synapse, ABC): + """ + The :func:`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. + """ + + model_config = ConfigDict(validate_assignment=True) + + class BTStreamingResponse(_StreamingResponse): + """ + :func:`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 :func:`create_streaming_response` method to create a response object based on the token streamer + provided by the subclass. + """ + + def __init__( + self, + model: "BTStreamingResponseModel", + *, + synapse: "Optional[StreamingSynapse]" = None, + **kwargs, + ): + """ + Initializes the BTStreamingResponse with the given token streamer model. + + Args: + model (bittensor.core.stream.BTStreamingResponseModel): A BTStreamingResponseModel instance containing the token streamer callable, which is responsible for generating the content of the response. + synapse (bittensor.core.stream.StreamingSynapse): The response Synapse to be used to update the response headers etc. + **kwargs: Additional keyword arguments passed to the parent StreamingResponse class. + """ + super().__init__(content=iter(()), **kwargs) + self.token_streamer = model.token_streamer + self.synapse = synapse + + async def stream_response(self, send: "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. + + Args: + send (starlette.types.Send): A callable to send the response, provided by the ASGI server. + """ + headers = [(b"content-type", b"text/event-stream")] + self.raw_headers + + await send( + {"type": "http.response.start", "status": 200, "headers": headers} + ) + + await self.token_streamer(send) + + await send({"type": "http.response.body", "body": b"", "more_body": False}) + + async def __call__(self, scope: "Scope", receive: "Receive", send: "Send"): + """ + Asynchronously calls the :func:`stream_response method`, allowing the :func:`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 :func:`stream_response` method to perform the actual streaming process. + + Args: + 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. + """ + await self.stream_response(send) + + @abstractmethod + async def process_streaming_response(self, response: "ClientResponse"): + """ + Abstract method that must be implemented by the subclass. + This method should provide logic to handle the streaming response, such as parsing and accumulating data. + It is called as the response is being streamed from the network, and should be implemented to handle the specific streaming data format and requirements of the subclass. + + Args: + response (aiohttp.ClientResponse): The response object to be processed, typically containing chunks of data. + """ + ... + + @abstractmethod + def extract_response_json(self, response: "ClientResponse") -> dict: + """ + 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. + + Args: + response (aiohttp.ClientResponse): The response object from which to extract JSON data. + """ + + def create_streaming_response( + self, token_streamer: Callable[[Send], Awaitable[None]] + ) -> "BTStreamingResponse": + """ + 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. + + Args: + 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: + BTStreamingResponse (bittensor.core.stream.StreamingSynapse.BTStreamingResponse): The streaming response object, ready to be sent to the client. + """ + model_instance = BTStreamingResponseModel(token_streamer=token_streamer) + + return self.BTStreamingResponse(model_instance, synapse=self) diff --git a/bittensor/core/subtensor.py b/bittensor/core/subtensor.py new file mode 100644 index 0000000000..5339645952 --- /dev/null +++ b/bittensor/core/subtensor.py @@ -0,0 +1,1733 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +The ``bittensor.core.subtensor`` module 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. +""" + +import argparse +import copy +import socket +from typing import Union, Optional, TypedDict, Any + +import numpy as np +import scalecodec +from bittensor_wallet import Wallet +from numpy.typing import NDArray +from retry import retry +from scalecodec.base import RuntimeConfiguration +from scalecodec.exceptions import RemainingScaleBytesNotEmptyException +from scalecodec.type_registry import load_type_registry_preset +from scalecodec.types import ScaleType +from substrateinterface.base import QueryMapResult, SubstrateInterface + +from bittensor.core import settings +from bittensor.core.axon import Axon +from bittensor.core.chain_data import ( + NeuronInfo, + PrometheusInfo, + SubnetHyperparameters, + NeuronInfoLite, + custom_rpc_type_registry, +) +from bittensor.core.config import Config +from bittensor.core.extrinsics.commit_weights import ( + commit_weights_extrinsic, + reveal_weights_extrinsic, +) +from bittensor.core.extrinsics.prometheus import ( + do_serve_prometheus, + prometheus_extrinsic, +) +from bittensor.core.extrinsics.serving import ( + do_serve_axon, + serve_axon_extrinsic, + publish_metadata, + get_metadata, +) +from bittensor.core.extrinsics.set_weights import set_weights_extrinsic +from bittensor.core.extrinsics.transfer import ( + transfer_extrinsic, +) +from bittensor.core.metagraph import Metagraph +from bittensor.utils import torch +from bittensor.utils import u16_normalized_float, networking +from bittensor.utils.balance import Balance +from bittensor.utils.btlogging import logging +from bittensor.utils.weight_utils import generate_weight_hash + +KEY_NONCE: dict[str, int] = {} + + +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. + + Example Usage:: + + from bittensor.core.subtensor import Subtensor + + # Connect to the main Bittensor network (Finney). + finney_subtensor = Subtensor(network='finney') + + # Close websocket connection with the Bittensor network. + finney_subtensor.close() + + # Register a new neuron on the network. + wallet = bittensor_wallet.Wallet(...) # Assuming a wallet instance is created. + netuid = 1 + success = finney_subtensor.register(wallet=wallet, netuid=netuid) + + # Set inter-neuronal weights for collaborative learning. + success = finney_subtensor.set_weights(wallet=wallet, netuid=netuid, uids=[...], weights=[...]) + + # Get the metagraph for a specific subnet using given subtensor connection + metagraph = finney_subtensor.metagraph(netuid=netuid) + + By facilitating these operations, the Subtensor class is instrumental in maintaining the decentralized + intelligence and dynamic learning environment of the Bittensor network, as envisioned in its foundational + principles and mechanisms described in the `NeurIPS paper + `_. paper. + """ + + def __init__( + self, + network: Optional[str] = None, + config: Optional["Config"] = None, + _mock: bool = False, + log_verbose: bool = True, + connection_timeout: int = 600, + ) -> 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 (Optional[str]): The network name to connect to (e.g., ``finney``, ``local``). This can also be the chain endpoint (e.g., ``wss://entrypoint-finney.opentensor.ai:443``) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network. + config (Optional[bittensor.core.config.Config]): Configuration object for the subtensor. If not provided, a default configuration is used. + _mock (bool): If set to ``True``, uses a mocked connection for testing purposes. Default is ``False``. + log_verbose (bool): Whether to enable verbose logging. If set to ``True``, detailed log information about the connection and network operations will be provided. Default is ``True``. + connection_timeout (int): The maximum time in seconds to keep the connection alive. Default is ``600``. + + This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights. + """ + # 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 + + if config is None: + config = Subtensor.config() + self._config = copy.deepcopy(config) + + # Setup config.subtensor.network and config.subtensor.chain_endpoint + self.chain_endpoint, self.network = Subtensor.setup_config( + network, self._config + ) + + if ( + self.network == "finney" + or self.chain_endpoint == settings.FINNEY_ENTRYPOINT + ) and log_verbose: + logging.info( + f"You are connecting to {self.network} network with endpoint {self.chain_endpoint}." + ) + logging.warning( + "We strongly encourage running a local subtensor node whenever possible. " + "This increases decentralization and resilience of the network." + ) + 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." + ) + + self.log_verbose = log_verbose + self._connection_timeout = connection_timeout + self._get_substrate() + + def __str__(self) -> str: + if self.network == self.chain_endpoint: + # Connecting to chain endpoint without network known. + return f"subtensor({self.chain_endpoint})" + else: + # Connecting to network with endpoint known. + return f"subtensor({self.network}, {self.chain_endpoint})" + + def __repr__(self) -> str: + return self.__str__() + + def close(self): + """Cleans up resources for this subtensor instance like active websocket connection and active extensions.""" + self.substrate.close() + + def _get_substrate(self): + """Establishes a connection to the Substrate node using configured parameters.""" + try: + # Set up params. + self.substrate = SubstrateInterface( + ss58_format=settings.SS58_FORMAT, + use_remote_preset=True, + url=self.chain_endpoint, + type_registry=settings.TYPE_REGISTRY, + ) + if self.log_verbose: + logging.info( + f"Connected to {self.network} network and {self.chain_endpoint}." + ) + + try: + self.substrate.websocket.settimeout(self._connection_timeout) + except (AttributeError, TypeError, socket.error, OSError) as e: + logging.warning(f"Error setting timeout: {e}") + + except ConnectionRefusedError: + logging.error( + f"Could not connect to {self.network} network with {self.chain_endpoint} chain endpoint.", + ) + logging.info( + "You can check if you have connectivity by running this command: nc -vz localhost " + f"{self.chain_endpoint.split(':')[2]}" + ) + + @staticmethod + def config() -> "Config": + """ + Creates and returns a Bittensor configuration object. + + Returns: + config (bittensor.core.config.Config): A Bittensor configuration object configured with arguments added by the `subtensor.add_args` method. + """ + parser = argparse.ArgumentParser() + Subtensor.add_args(parser) + return Config(parser, args=[]) + + @staticmethod + def setup_config(network: Optional[str], config: "Config"): + """ + Sets up and returns the configuration for the Subtensor network and endpoint. + + This method determines the appropriate network and chain endpoint based on the provided network string or + configuration object. It evaluates the network and endpoint in the following order of precedence: + 1. Provided network string. + 2. Configured chain endpoint in the `config` object. + 3. Configured network in the `config` object. + 4. Default chain endpoint. + 5. Default network. + + Args: + network (Optional[str]): The name of the Subtensor network. If None, the network and endpoint will be determined from the `config` object. + config (bittensor.core.config.Config): The configuration object containing the network and chain endpoint settings. + + Returns: + tuple: A tuple containing the formatted WebSocket endpoint URL and the evaluated network name. + """ + if network is not None: + ( + evaluated_network, + evaluated_endpoint, + ) = Subtensor.determine_chain_endpoint_and_network(network) + else: + if config.is_set("subtensor.chain_endpoint"): + ( + evaluated_network, + evaluated_endpoint, + ) = Subtensor.determine_chain_endpoint_and_network( + config.subtensor.chain_endpoint + ) + + elif config.is_set("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( + settings.DEFAULTS.subtensor.network + ) + + return ( + networking.get_formatted_ws_endpoint_url(evaluated_endpoint), + evaluated_network, + ) + + @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): + """ + Adds command-line arguments to the provided ArgumentParser for configuring the Subtensor settings. + + Args: + parser (argparse.ArgumentParser): The ArgumentParser object to which the Subtensor arguments will be added. + prefix (Optional[str]): An optional prefix for the argument names. If provided, the prefix is prepended to each argument name. + + Arguments added: + --subtensor.network: The Subtensor network flag. Possible values are 'finney', 'test', 'archive', and 'local'. Overrides the chain endpoint if set. + --subtensor.chain_endpoint: The Subtensor chain endpoint flag. If set, it overrides the network flag. + --subtensor._mock: If true, uses a mocked connection to the chain. + + Example: + parser = argparse.ArgumentParser() + Subtensor.add_args(parser) + """ + prefix_str = "" if prefix is None else f"{prefix}." + try: + default_network = settings.DEFAULT_NETWORK + default_chain_endpoint = settings.FINNEY_ENTRYPOINT + + parser.add_argument( + f"--{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( + f"--{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( + f"--{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 + + # Inner private functions + @networking.ensure_connected + def _encode_params( + self, + call_definition: list["ParamWithTypes"], + params: Union[list[Any], dict[str, Any]], + ) -> str: + """Returns a hex encoded string of the params using their types.""" + param_data = scalecodec.ScaleBytes(b"") + + for i, param in enumerate(call_definition["params"]): # type: ignore + scale_obj = self.substrate.create_scale_object(param["type"]) + if type(params) is list: + param_data += scale_obj.encode(params[i]) + else: + if param["name"] not in params: + raise ValueError(f"Missing param {param['name']} in params dict.") + + param_data += scale_obj.encode(params[param["name"]]) + + return param_data.to_hex() + + def _get_hyperparameter( + self, param_name: str, netuid: int, block: Optional[int] = None + ) -> Optional[Any]: + """ + Retrieves a specified hyperparameter for a specific subnet. + + Args: + param_name (str): The name of the hyperparameter to retrieve. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + Optional[Union[int, float]]: The value of the specified hyperparameter if the subnet exists, ``None`` otherwise. + """ + if not self.subnet_exists(netuid, block): + return None + + result = self.query_subtensor(param_name, block, [netuid]) + if result is None or not hasattr(result, "value"): + return None + + return result.value + + # Calls methods + @networking.ensure_connected + def query_subtensor( + self, name: str, block: Optional[int] = None, params: Optional[list] = None + ) -> "ScaleType": + """ + 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. + + Args: + name (str): The name of the storage function to query. + block (Optional[int]): The blockchain block number at which to perform the query. + params (Optional[list[object]]): A list of parameters to pass to the query function. + + Returns: + query_response (scalecodec.ScaleType): An object containing the requested data. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry() -> "ScaleType": + return self.substrate.query( + module="SubtensorModule", + storage_function=name, + params=params, + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + return make_substrate_call_with_retry() + + @networking.ensure_connected + def query_map_subtensor( + self, name: str, block: Optional[int] = None, params: Optional[list] = None + ) -> "QueryMapResult": + """ + 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. + + Args: + name (str): The name of the map storage function to query. + block (Optional[int]): The blockchain block number at which to perform the query. + params (Optional[list[object]]): A list of parameters to pass to the query function. + + Returns: + QueryMapResult (substrateinterface.base.QueryMapResult): An object containing the map-like data structure, or ``None`` if not found. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry(): + return self.substrate.query_map( + module="SubtensorModule", + storage_function=name, + params=params, + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + return make_substrate_call_with_retry() + + def query_runtime_api( + self, + runtime_api: str, + method: str, + params: Optional[Union[list[int], dict[str, int]]], + block: Optional[int] = None, + ) -> Optional[str]: + """ + 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. + + Args: + runtime_api (str): The name of the runtime API to query. + method (str): The specific method within the runtime API to call. + params (Optional[list[ParamWithTypes]]): The parameters to pass to the method call. + block (Optional[int]): The blockchain block number at which to perform the query. + + Returns: + Optional[str]: The Scale Bytes encoded result from the runtime API call, or ``None`` if the call fails. + + This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network's runtime environment. + """ + call_definition = settings.TYPE_REGISTRY["runtime_api"][runtime_api]["methods"][ + method + ] + + json_result = self.state_call( + method=f"{runtime_api}_{method}", + data=( + "0x" + if params is None + else self._encode_params(call_definition=call_definition, params=params) + ), + block=block, + ) + + if json_result is None: + return None + + return_type = call_definition["type"] + + as_scale_bytes = scalecodec.ScaleBytes(json_result["result"]) + + rpc_runtime_config = RuntimeConfiguration() + rpc_runtime_config.update_type_registry(load_type_registry_preset("legacy")) + rpc_runtime_config.update_type_registry(custom_rpc_type_registry) + + obj = rpc_runtime_config.create_scale_object(return_type, as_scale_bytes) + if obj.data.to_hex() == "0x0400": # RPC returned None result + return None + + return obj.decode() + + @networking.ensure_connected + def state_call( + self, method: str, data: str, block: Optional[int] = None + ) -> dict[Any, Any]: + """ + 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. + + Args: + method (str): The method name for the state call. + data (str): The data to be passed to the method. + block (Optional[int]): The blockchain block number at which to perform the state call. + + Returns: + result (dict[Any, Any]): The result of the rpc call. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry() -> dict[Any, Any]: + block_hash = None if block is None else self.substrate.get_block_hash(block) + return self.substrate.rpc_request( + method="state_call", + params=[method, data, block_hash] if block_hash else [method, data], + ) + + return make_substrate_call_with_retry() + + @networking.ensure_connected + def query_map( + self, + module: str, + name: str, + block: Optional[int] = None, + params: Optional[list] = None, + ) -> "QueryMapResult": + """ + 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. + + Args: + module (str): The name of the module from which to query the map storage. + name (str): The specific storage function within the module to query. + block (Optional[int]): The blockchain block number at which to perform the query. + params (Optional[list[object]]): Parameters to be passed to the query. + + Returns: + result (substrateinterface.base.QueryMapResult): A data structure representing the map storage if found, ``None`` otherwise. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry() -> "QueryMapResult": + return self.substrate.query_map( + module=module, + storage_function=name, + params=params, + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + return make_substrate_call_with_retry() + + @networking.ensure_connected + def query_constant( + self, module_name: str, constant_name: str, block: Optional[int] = None + ) -> Optional["ScaleType"]: + """ + 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. + + Args: + module_name (str): The name of the module containing the constant. + constant_name (str): The name of the constant to retrieve. + block (Optional[int]): The blockchain block number at which to query the constant. + + Returns: + Optional[scalecodec.ScaleType]: The value of the constant if found, ``None`` otherwise. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry(): + return self.substrate.get_constant( + module_name=module_name, + constant_name=constant_name, + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + return make_substrate_call_with_retry() + + @networking.ensure_connected + def query_module( + self, + module: str, + name: str, + block: Optional[int] = None, + params: Optional[list] = None, + ) -> "ScaleType": + """ + 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. + + Args: + 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]): The blockchain block number at which to perform the query. + params (Optional[list[object]]): A list of parameters to pass to the query function. + + Returns: + Optional[scalecodec.ScaleType]: An object containing the requested data if found, ``None`` otherwise. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry() -> "ScaleType": + return self.substrate.query( + module=module, + storage_function=name, + params=params, + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + return make_substrate_call_with_retry() + + # Common subtensor methods + def metagraph( + self, netuid: int, lite: bool = True, block: Optional[int] = None + ) -> "Metagraph": # type: ignore + """ + Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the network's structure, including neuron connections and interactions. + + Args: + netuid (int): The network UID of the subnet to query. + lite (bool): If true, returns a metagraph using a lightweight sync (no weights, no bonds). Default is ``True``. + block (Optional[int]): Block number for synchronization, or ``None`` for the latest block. + + Returns: + bittensor.core.metagraph.Metagraph: The metagraph representing the subnet's structure and neuron relationships. + + 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. + """ + metagraph = Metagraph( + network=self.network, netuid=netuid, lite=lite, sync=False + ) + metagraph.sync(block=block, lite=lite, subtensor=self) + + return metagraph + + @staticmethod + def determine_chain_endpoint_and_network( + network: str, + ) -> tuple[Optional[str], Optional[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). + + Returns: + tuple[Optional[str], Optional[str]]: The network and chain endpoint flag. If passed, overrides the ``network`` argument. + """ + + if network is None: + return None, None + if network in ["finney", "local", "test", "archive"]: + if network == "finney": + # Kiru Finney staging network. + return network, settings.FINNEY_ENTRYPOINT + elif network == "local": + return network, settings.LOCAL_ENTRYPOINT + elif network == "test": + return network, settings.FINNEY_TEST_ENTRYPOINT + elif network == "archive": + return network, settings.ARCHIVE_ENTRYPOINT + else: + if ( + network == settings.FINNEY_ENTRYPOINT + or "entrypoint-finney.opentensor.ai" in network + ): + return "finney", settings.FINNEY_ENTRYPOINT + elif ( + network == settings.FINNEY_TEST_ENTRYPOINT + or "test.finney.opentensor.ai" in network + ): + return "test", settings.FINNEY_TEST_ENTRYPOINT + elif ( + network == settings.ARCHIVE_ENTRYPOINT + or "archive.chain.opentensor.ai" in network + ): + return "archive", settings.ARCHIVE_ENTRYPOINT + elif "127.0.0.1" in network or "localhost" in network: + return "local", network + else: + return "unknown", network + return None, None + + def get_netuids_for_hotkey( + self, hotkey_ss58: str, block: Optional[int] = None + ) -> list[int]: + """ + 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. + + Args: + hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + block (Optional[int]): The blockchain block number at which to perform the query. + + Returns: + list[int]: A list of netuids where the neuron is a member. + """ + result = self.query_map_subtensor("IsNetworkMember", block, [hotkey_ss58]) + return ( + [record[0].value for record in result if record[1]] + if result and hasattr(result, "records") + else [] + ) + + @networking.ensure_connected + def get_current_block(self) -> int: + """ + 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: + int: The current chain block number. + + 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. + """ + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry(): + return self.substrate.get_block_number(None) # type: ignore + + return make_substrate_call_with_retry() + + def is_hotkey_registered_any( + self, hotkey_ss58: str, block: Optional[int] = None + ) -> bool: + """ + Checks if a neuron's hotkey is registered on any subnet within the Bittensor network. + + Args: + hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + block (Optional[int]): The blockchain block number at which to perform the check. + + Returns: + bool: ``True`` if the hotkey is registered on any subnet, False otherwise. + + This function is essential for determining the network-wide presence and participation of a neuron. + """ + return len(self.get_netuids_for_hotkey(hotkey_ss58, block)) > 0 + + def is_hotkey_registered_on_subnet( + self, hotkey_ss58: str, netuid: int, block: Optional[int] = None + ) -> bool: + """ + Checks if a neuron's hotkey is registered on a specific subnet within the Bittensor network. + + Args: + hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number at which to perform the check. + + Returns: + bool: ``True`` if the hotkey is registered on the specified subnet, False otherwise. + + 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. + """ + return self.get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block) is not None + + def is_hotkey_registered( + self, + hotkey_ss58: str, + netuid: Optional[int] = None, + block: Optional[int] = None, + ) -> bool: + """ + 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. + + Args: + hotkey_ss58 (str): The SS58 address of the neuron's hotkey. + netuid (Optional[int]): The unique identifier of the subnet to check the registration. If ``None``, the registration is checked across all subnets. + block (Optional[int]): The blockchain block number at which to perform the query. + + Returns: + bool: ``True`` if the hotkey is registered in the specified context (either any subnet or a specific subnet), ``False`` otherwise. + + 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. + """ + if netuid is None: + return self.is_hotkey_registered_any(hotkey_ss58, block) + else: + return self.is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block) + + # Not used in Bittensor, but is actively used by the community in almost all subnets + def set_weights( + self, + wallet: "Wallet", + netuid: int, + uids: Union[NDArray[np.int64], "torch.LongTensor", list], + weights: Union[NDArray[np.float32], "torch.FloatTensor", list], + version_key: int = settings.version_as_int, + 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.Wallet): The wallet associated with the neuron setting the weights. + netuid (int): The unique identifier of the subnet. + uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of neuron UIDs that the weights are being set for. + weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The corresponding weights to be set for each UID. + version_key (int): Version key for compatibility with the network. Default is ``int representation of Bittensor version.``. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``False``. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. Default is ``False``. + max_retries (int): The number of maximum attempts to set weights. Default is ``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: + logging.info( + f"Setting weights for subnet #{netuid}. Attempt {retries + 1} of {max_retries}." + ) + 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: + logging.error(f"Error setting weights: {e}") + finally: + retries += 1 + + return success, message + + def serve_axon( + self, + netuid: int, + axon: "Axon", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, + ) -> bool: + """ + 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. + + Args: + netuid (int): The unique identifier of the subnetwork. + axon (bittensor.core.axon.Axon): The Axon instance to be registered for serving. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``True``. + + Returns: + bool: ``True`` if the Axon serve registration is successful, False otherwise. + + By registering an Axon, the neuron becomes an active part of the network's distributed computing infrastructure, contributing to the collective intelligence of Bittensor. + """ + return serve_axon_extrinsic( + self, netuid, axon, wait_for_inclusion, wait_for_finalization + ) + + # metagraph + @property + def block(self) -> int: + """Returns current chain block. + + Returns: + block (int): Current chain block. + """ + return self.get_current_block() + + def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]: + """ + Returns the number of blocks since the last update for a specific UID in the subnetwork. + + Args: + netuid (int): The unique identifier of the subnetwork. + uid (int): The unique identifier of the neuron. + + Returns: + Optional[int]: The number of blocks since the last update, or ``None`` if the subnetwork or UID does not exist. + """ + call = self._get_hyperparameter(param_name="LastUpdate", netuid=netuid) + return None if call is None else self.get_current_block() - int(call[uid]) + + @networking.ensure_connected + def get_block_hash(self, block_id: int) -> str: + """ + 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. + + Args: + block_id (int): The block number for which the hash is to be retrieved. + + Returns: + str: The cryptographic hash of the specified block. + + 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. + """ + return self.substrate.get_block_hash(block_id=block_id) + + def weights_rate_limit(self, netuid: int) -> Optional[int]: + """ + Returns network WeightsSetRateLimit hyperparameter. + + Args: + netuid (int): The unique identifier of the subnetwork. + + Returns: + Optional[int]: The value of the WeightsSetRateLimit hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. + """ + call = self._get_hyperparameter(param_name="WeightsSetRateLimit", netuid=netuid) + return None if call is None else int(call) + + # Keep backwards compatibility for community usage. + # Make some commitment on-chain about arbitrary data. + def commit(self, wallet, netuid: int, data: str): + """ + Commits arbitrary data to the Bittensor network by publishing metadata. + + Args: + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the data. + netuid (int): The unique identifier of the subnetwork. + data (str): The data to be committed to the network. + """ + publish_metadata(self, wallet, netuid, f"Raw{len(data)}", data.encode()) + + # Keep backwards compatibility for community usage. + def subnetwork_n(self, netuid: int, block: Optional[int] = None) -> Optional[int]: + """ + Returns network SubnetworkN hyperparameter. + + Args: + netuid (int): The unique identifier of the subnetwork. + block (Optional[int]): The block number to retrieve the parameter from. If ``None``, the latest block is used. Default is ``None``. + + Returns: + Optional[int]: The value of the SubnetworkN hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. + """ + call = self._get_hyperparameter( + param_name="SubnetworkN", netuid=netuid, block=block + ) + return None if call is None else int(call) + + # Community uses this method + def transfer( + self, + wallet: "Wallet", + dest: str, + amount: Union["Balance", float], + wait_for_inclusion: bool = True, + wait_for_finalization: bool = False, + prompt: bool = False, + ) -> bool: + """ + 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. + + Args: + wallet (bittensor_wallet.Wallet): The wallet from which funds are being transferred. + dest (str): The destination public key address. + amount (Union[bittensor.utils.balance.Balance, float]): The amount of TAO to be transferred. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``True``. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``False``. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. Default is ``False``. + + Returns: + transfer_extrinsic (bool): ``True`` if the transfer is successful, False otherwise. + + This function is essential for the fluid movement of tokens in the network, supporting various economic activities such as staking, delegation, and reward distribution. + """ + return transfer_extrinsic( + subtensor=self, + wallet=wallet, + dest=dest, + amount=amount, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + ) + + # Community uses this method via `bittensor.api.extrinsics.prometheus.prometheus_extrinsic` + def get_neuron_for_pubkey_and_subnet( + self, hotkey_ss58: str, netuid: int, block: Optional[int] = None + ) -> Optional["NeuronInfo"]: + """ + 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. + + Args: + hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number at which to perform the query. + + Returns: + Optional[bittensor.core.chain_data.neuron_info.NeuronInfo]: Detailed information about the neuron if found, ``None`` otherwise. + + 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. + """ + return self.neuron_for_uid( + self.get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=block), + netuid, + block=block, + ) + + @networking.ensure_connected + def neuron_for_uid( + self, uid: Optional[int], netuid: int, block: Optional[int] = None + ) -> "NeuronInfo": + """ + 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. + + Args: + uid (Optional[int]): The unique identifier of the neuron. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + bittensor.core.chain_data.neuron_info.NeuronInfo: Detailed information about the neuron if found, ``None`` otherwise. + + 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. + """ + if uid is None: + return NeuronInfo.get_null_neuron() + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry(): + block_hash = None if block is None else self.substrate.get_block_hash(block) + params = [netuid, uid] + if block_hash: + params = params + [block_hash] + return self.substrate.rpc_request( + method="neuronInfo_getNeuron", + params=params, # custom rpc method + ) + + json_body = make_substrate_call_with_retry() + + if not (result := json_body.get("result", None)): + return NeuronInfo.get_null_neuron() + + return NeuronInfo.from_vec_u8(result) + + # Community uses this method + def serve_prometheus( + self, + wallet: "Wallet", + port: int, + netuid: int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, + ) -> bool: + """ + Serves Prometheus metrics by submitting an extrinsic to a blockchain network via the specified wallet. The function allows configuring whether to wait for the transaction's inclusion in a block and its finalization. + + Args: + wallet (bittensor_wallet.Wallet): Bittensor wallet instance used for submitting the extrinsic. + port (int): The port number on which Prometheus metrics are served. + netuid (int): The unique identifier of the subnetwork. + wait_for_inclusion (bool): If True, waits for the transaction to be included in a block. Defaults to ``False``. + wait_for_finalization (bool): If True, waits for the transaction to be finalized. Defaults to ``True``. + + Returns: + bool: Returns True if the Prometheus extrinsic is successfully processed, otherwise False. + """ + return prometheus_extrinsic( + self, + wallet=wallet, + port=port, + netuid=netuid, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Community uses this method + def get_subnet_hyperparameters( + self, netuid: int, block: Optional[int] = None + ) -> Optional[Union[list, "SubnetHyperparameters"]]: + """ + Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet's behavior. + + Args: + netuid (int): The network UID of the subnet to query. + block (Optional[int]): The blockchain block number for the query. + + Returns: + Optional[bittensor.core.chain_data.subnet_hyperparameters.SubnetHyperparameters]: The subnet's hyperparameters, or ``None`` if not available. + + 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. + """ + hex_bytes_result = self.query_runtime_api( + runtime_api="SubnetInfoRuntimeApi", + method="get_subnet_hyperparams", + params=[netuid], + block=block, + ) + + if hex_bytes_result is None: + return [] + + if hex_bytes_result.startswith("0x"): + bytes_result = bytes.fromhex(hex_bytes_result[2:]) + else: + bytes_result = bytes.fromhex(hex_bytes_result) + + return SubnetHyperparameters.from_vec_u8(bytes_result) # type: ignore + + # Community uses this method + # Returns network ImmunityPeriod hyper parameter. + def immunity_period( + self, netuid: int, block: Optional[int] = None + ) -> Optional[int]: + """ + 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. + + Args: + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, ``None`` otherwise. + + 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. + """ + call = self._get_hyperparameter( + param_name="ImmunityPeriod", netuid=netuid, block=block + ) + return None if call is None else int(call) + + # Community uses this method + def get_uid_for_hotkey_on_subnet( + self, hotkey_ss58: str, netuid: int, block: Optional[int] = None + ) -> Optional[int]: + """ + Retrieves the unique identifier (UID) for a neuron's hotkey on a specific subnet. + + Args: + hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + Optional[int]: The UID of the neuron if it is registered on the subnet, ``None`` otherwise. + + The UID is a critical identifier within the network, linking the neuron's hotkey to its operational and governance activities on a particular subnet. + """ + _result = self.query_subtensor("Uids", block, [netuid, hotkey_ss58]) + return getattr(_result, "value", None) + + # Community uses this method + def tempo(self, netuid: int, block: Optional[int] = None) -> Optional[int]: + """ + Returns network Tempo hyperparameter. + + Args: + netuid (int): The unique identifier of the subnetwork. + block (Optional[int]): The block number to retrieve the parameter from. If ``None``, the latest block is used. Default is ``None``. + + Returns: + Optional[int]: The value of the Tempo hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. + """ + call = self._get_hyperparameter(param_name="Tempo", netuid=netuid, block=block) + return None if call is None else int(call) + + # Community uses this method + def get_commitment(self, netuid: int, uid: int, block: Optional[int] = None) -> str: + """ + Retrieves the on-chain commitment for a specific neuron in the Bittensor network. + + Args: + netuid (int): The unique identifier of the subnetwork. + uid (int): The unique identifier of the neuron. + block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. Default is ``None``. + + Returns: + str: The commitment data as a string. + """ + metagraph = self.metagraph(netuid) + hotkey = metagraph.hotkeys[uid] # type: ignore + + metadata = get_metadata(self, netuid, hotkey, block) + commitment = metadata["info"]["fields"][0] # type: ignore + hex_data = commitment[list(commitment.keys())[0]][2:] # type: ignore + + return bytes.fromhex(hex_data).decode() + + # Community uses this via `bittensor.utils.weight_utils.process_weights_for_netuid` function. + def min_allowed_weights( + self, netuid: int, block: Optional[int] = None + ) -> Optional[int]: + """ + Returns network MinAllowedWeights hyperparameter. + + Args: + netuid (int): The unique identifier of the subnetwork. + block (Optional[int]): The block number to retrieve the parameter from. If ``None``, the latest block is used. Default is ``None``. + + Returns: + Optional[int]: The value of the MinAllowedWeights hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. + """ + call = self._get_hyperparameter( + param_name="MinAllowedWeights", block=block, netuid=netuid + ) + return None if call is None else int(call) + + # Community uses this via `bittensor.utils.weight_utils.process_weights_for_netuid` function. + def max_weight_limit( + self, netuid: int, block: Optional[int] = None + ) -> Optional[float]: + """ + Returns network MaxWeightsLimit hyperparameter. + + Args: + netuid (int): The unique identifier of the subnetwork. + block (Optional[int]): The block number to retrieve the parameter from. If ``None``, the latest block is used. Default is ``None``. + + Returns: + Optional[float]: The value of the MaxWeightsLimit hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. + """ + call = self._get_hyperparameter( + param_name="MaxWeightsLimit", block=block, netuid=netuid + ) + return None if call is None else u16_normalized_float(int(call)) + + # # Community uses this method. It is used in subtensor in neuron_info, and serving. + def get_prometheus_info( + self, netuid: int, hotkey_ss58: str, block: Optional[int] = None + ) -> Optional["PrometheusInfo"]: + """ + Returns the prometheus information for this hotkey account. + + Args: + netuid (int): The unique identifier of the subnetwork. + hotkey_ss58 (str): The SS58 address of the hotkey. + block (Optional[int]): The block number to retrieve the prometheus information from. If ``None``, the latest block is used. Default is ``None``. + + Returns: + Optional[bittensor.core.chain_data.prometheus_info.PrometheusInfo]: A PrometheusInfo object containing the prometheus information, or ``None`` if the prometheus information is not found. + """ + result = self.query_subtensor("Prometheus", block, [netuid, hotkey_ss58]) + if result is not None and hasattr(result, "value"): + return PrometheusInfo( + ip=networking.int_to_ip(result.value["ip"]), + ip_type=result.value["ip_type"], + port=result.value["port"], + version=result.value["version"], + block=result.value["block"], + ) + return None + + # Community uses this method + def subnet_exists(self, netuid: int, block: Optional[int] = None) -> bool: + """ + Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network. + + Args: + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number at which to check the subnet's existence. + + Returns: + bool: ``True`` if the subnet exists, False otherwise. + + 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. + """ + _result = self.query_subtensor("NetworksAdded", block, [netuid]) + return getattr(_result, "value", False) + + # Metagraph uses this method + def bonds( + self, netuid: int, block: Optional[int] = None + ) -> list[tuple[int, list[tuple[int, int]]]]: + """ + 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. + + Args: + netuid (int): The network UID of the subnet to query. + block (Optional[int]): The blockchain block number for the query. + + Returns: + list[tuple[int, list[tuple[int, int]]]]: A list of tuples mapping each neuron's UID to its bonds with other neurons. + + 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. + """ + b_map = [] + b_map_encoded = self.query_map_subtensor( + name="Bonds", block=block, params=[netuid] + ) + if b_map_encoded.records: + for uid, b in b_map_encoded: + b_map.append((uid.serialize(), b.serialize())) + + return b_map + + # Metagraph uses this method + def neurons(self, netuid: int, block: Optional[int] = None) -> list["NeuronInfo"]: + """ + 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. + + Args: + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + list[bittensor.core.chain_data.neuron_info.NeuronInfo]: A list of NeuronInfo objects detailing each neuron's characteristics in the subnet. + + 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 = self.neurons_lite(netuid=netuid, block=block) + weights = self.weights(block=block, netuid=netuid) + bonds = self.bonds(block=block, netuid=netuid) + + weights_as_dict = {uid: w for uid, w in weights} + bonds_as_dict = {uid: b for uid, b in bonds} + + neurons = [ + NeuronInfo.from_weights_bonds_and_neuron_lite( + neuron_lite, weights_as_dict, bonds_as_dict + ) + for neuron_lite in neurons_lite + ] + + return neurons + + # Metagraph uses this method + def get_total_subnets(self, block: Optional[int] = None) -> Optional[int]: + """ + Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block. + + Args: + block (Optional[int]): The blockchain block number for the query. + + Returns: + Optional[int]: The total number of subnets in the network. + + Understanding the total number of subnets is essential for assessing the network's growth and the extent of its decentralized infrastructure. + """ + _result = self.query_subtensor("TotalNetworks", block) + return getattr(_result, "value", None) + + # Metagraph uses this method + def get_subnets(self, block: Optional[int] = None) -> list[int]: + """ + Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers. + + Args: + block (Optional[int]): The blockchain block number for the query. + + Returns: + list[int]: A list of network UIDs representing each active subnet. + + This function is valuable for understanding the network's structure and the diversity of subnets available for neuron participation and collaboration. + """ + result = self.query_map_subtensor("NetworksAdded", block) + return ( + [network[0].value for network in result.records if network[1]] + if result and hasattr(result, "records") + else [] + ) + + # Metagraph uses this method + def neurons_lite( + self, netuid: int, block: Optional[int] = None + ) -> list["NeuronInfoLite"]: + """ + 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. + + Args: + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The blockchain block number for the query. + + Returns: + list[bittensor.core.chain_data.neuron_info_lite.NeuronInfoLite]: A list of simplified neuron information for the subnet. + + 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. + """ + hex_bytes_result = self.query_runtime_api( + runtime_api="NeuronInfoRuntimeApi", + method="get_neurons_lite", + params=[netuid], + block=block, + ) + + if hex_bytes_result is None: + return [] + + if hex_bytes_result.startswith("0x"): + bytes_result = bytes.fromhex(hex_bytes_result[2:]) + else: + bytes_result = bytes.fromhex(hex_bytes_result) + + return NeuronInfoLite.list_from_vec_u8(bytes_result) # type: ignore + + # Used in the `neurons` method which is used in metagraph.py + def weights( + self, netuid: int, block: Optional[int] = None + ) -> list[tuple[int, list[tuple[int, int]]]]: + """ + 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. + + Args: + netuid (int): The network UID of the subnet to query. + block (Optional[int]): The blockchain block number for the query. + + Returns: + list[tuple[int, list[tuple[int, int]]]]: A list of tuples mapping each neuron's UID to its assigned weights. + + 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. + """ + w_map = [] + w_map_encoded = self.query_map_subtensor( + name="Weights", block=block, params=[netuid] + ) + if w_map_encoded.records: + for uid, w in w_map_encoded: + w_map.append((uid.serialize(), w.serialize())) + + return w_map + + # Used by community via `transfer_extrinsic` + @networking.ensure_connected + def get_balance(self, address: str, block: Optional[int] = None) -> "Balance": + """ + 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. + + Args: + address (str): The Substrate address in ``ss58`` format. + block (Optional[int]): The blockchain block number at which to perform the query. + + Returns: + bittensor.utils.balance.Balance: The account balance at the specified block, represented as a Balance object. + + 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. + """ + try: + + @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=logging) + def make_substrate_call_with_retry(): + return self.substrate.query( + module="System", + storage_function="Account", + params=[address], + block_hash=( + None if block is None else self.substrate.get_block_hash(block) + ), + ) + + result = make_substrate_call_with_retry() + + except RemainingScaleBytesNotEmptyException: + logging.error( + "Received a corrupted message. This likely points to an error with the network or subnet." + ) + return Balance(1000) + return Balance(result.value["data"]["free"]) + + # Used in community via `bittensor.core.subtensor.Subtensor.transfer` + @networking.ensure_connected + def get_transfer_fee( + self, wallet: "Wallet", dest: str, value: Union["Balance", float, int] + ) -> "Balance": + """ + 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. + + Args: + wallet (bittensor_wallet.Wallet): The wallet from which the transfer is initiated. + dest (str): The ``SS58`` address of the destination account. + value (Union[bittensor.utils.balance.Balance, float, int]): The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units. + + Returns: + bittensor.utils.balance.Balance: The estimated transaction fee for the transfer, represented as a Balance object. + + 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. + """ + if isinstance(value, float): + value = Balance.from_tao(value) + elif isinstance(value, int): + value = Balance.from_rao(value) + + if isinstance(value, Balance): + call = self.substrate.compose_call( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": dest, "value": value.rao}, + ) + + try: + payment_info = self.substrate.get_payment_info( + call=call, keypair=wallet.coldkeypub + ) + except Exception as e: + settings.bt_console.print( + f":cross_mark: [red]Failed to get payment info[/red]:[bold white]\n {e}[/bold white]" + ) + payment_info = {"partialFee": int(2e7)} # assume 0.02 Tao + + fee = Balance.from_rao(payment_info["partialFee"]) + return fee + else: + fee = Balance.from_rao(int(2e7)) + logging.error( + "To calculate the transaction fee, the value must be Balance, float, or int. Received type: %s. Fee " + "is %s", + type(value), + 2e7, + ) + return fee + + # Used in community via `bittensor.core.subtensor.Subtensor.transfer` + def get_existential_deposit( + self, block: Optional[int] = None + ) -> Optional["Balance"]: + """ + 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. + + Args: + block (Optional[int]): Block number at which to query the deposit amount. If ``None``, the current block is used. + + Returns: + Optional[bittensor.utils.balance.Balance]: The existential deposit amount, or ``None`` if the query fails. + + The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts. + """ + result = self.query_constant( + module_name="Balances", constant_name="ExistentialDeposit", block=block + ) + if result is None or not hasattr(result, "value"): + return None + return Balance.from_rao(result.value) + + # Community uses this method + def commit_weights( + self, + wallet: "Wallet", + netuid: int, + salt: list[int], + uids: Union[NDArray[np.int64], list], + weights: Union[NDArray[np.int64], list], + version_key: int = settings.version_as_int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, + prompt: bool = False, + max_retries: int = 5, + ) -> tuple[bool, str]: + """ + Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet. + This action serves as a commitment or snapshot of the neuron's current weight distribution. + + Args: + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the weights. + netuid (int): The unique identifier of the subnet. + salt (list[int]): list of randomly generated integers as salt to generated weighted hash. + uids (np.ndarray): NumPy array of neuron UIDs for which weights are being committed. + weights (np.ndarray): NumPy array of weight values corresponding to each UID. + version_key (int): Version key for compatibility with the network. Default is ``int representation of Bittensor version.``. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``False``. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. Default is ``False``. + max_retries (int): The number of maximum attempts to commit weights. Default is ``5``. + + Returns: + tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string + value describing the success or potential error. + + This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, + enhancing transparency and accountability within the Bittensor network. + """ + retries = 0 + success = False + message = "No attempt made. Perhaps it is too soon to commit weights!" + + logging.info( + f"Committing weights with params: netuid={netuid}, uids={uids}, weights={weights}, version_key={version_key}" + ) + + # Generate the hash of the weights + commit_hash = generate_weight_hash( + address=wallet.hotkey.ss58_address, + netuid=netuid, + uids=list(uids), + values=list(weights), + salt=salt, + version_key=version_key, + ) + + logging.info(f"Commit Hash: {commit_hash}") + + while retries < max_retries: + try: + success, message = commit_weights_extrinsic( + subtensor=self, + wallet=wallet, + netuid=netuid, + commit_hash=commit_hash, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + ) + if success: + break + except Exception as e: + logging.error(f"Error committing weights: {e}") + finally: + retries += 1 + + return success, message + + # Community uses this method + def reveal_weights( + self, + wallet: "Wallet", + netuid: int, + uids: Union[NDArray[np.int64], list], + weights: Union[NDArray[np.int64], list], + salt: Union[NDArray[np.int64], list], + version_key: int = settings.version_as_int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = False, + prompt: bool = False, + max_retries: int = 5, + ) -> tuple[bool, str]: + """ + Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. + This action serves as a revelation of the neuron's previously committed weight distribution. + + Args: + wallet (bittensor_wallet.Wallet): The wallet associated with the neuron revealing the weights. + netuid (int): The unique identifier of the subnet. + uids (np.ndarray): NumPy array of neuron UIDs for which weights are being revealed. + weights (np.ndarray): NumPy array of weight values corresponding to each UID. + salt (np.ndarray): NumPy array of salt values corresponding to the hash function. + version_key (int): Version key for compatibility with the network. Default is ``int representation of Bittensor version``. + wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. + wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``False``. + prompt (bool): If ``True``, prompts for user confirmation before proceeding. Default is ``False``. + max_retries (int): The number of maximum attempts to reveal weights. Default is ``5``. + + Returns: + tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string + value describing the success or potential error. + + This function allows neurons to reveal their previously committed weight distribution, ensuring transparency + and accountability within the Bittensor network. + """ + + retries = 0 + success = False + message = "No attempt made. Perhaps it is too soon to reveal weights!" + + while retries < max_retries: + try: + success, message = reveal_weights_extrinsic( + subtensor=self, + wallet=wallet, + netuid=netuid, + uids=list(uids), + weights=list(weights), + salt=list(salt), + version_key=version_key, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + ) + if success: + break + except Exception as e: + logging.error(f"Error revealing weights: {e}") + finally: + retries += 1 + + return success, message + + # Subnet 27 uses this method + _do_serve_prometheus = do_serve_prometheus + # Subnet 27 uses this method name + _do_serve_axon = do_serve_axon diff --git a/bittensor/core/synapse.py b/bittensor/core/synapse.py new file mode 100644 index 0000000000..a96a92e1a1 --- /dev/null +++ b/bittensor/core/synapse.py @@ -0,0 +1,852 @@ +# The MIT License (MIT) +# Copyright © 2024 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 base64 +import json +import sys +import warnings +from typing import cast, Any, ClassVar, Optional, Union + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) + +from bittensor.utils import get_hash +from bittensor.utils.btlogging import logging + + +def get_size(obj: Any, seen: Optional[set] = None) -> int: + """ + Recursively finds size of objects. + + This function traverses every item of a given object and sums their sizes to compute the total size. + + Args: + obj (Any): The object to get the size of. + seen (Optional[set]): Set of object ids that have been calculated. + + Returns: + int: The total size of the object. + + """ + size = sys.getsizeof(obj) + if seen is None: + seen = set() + obj_id = id(obj) + if obj_id in seen: + return 0 + # Important mark as seen *before* entering recursion to gracefully handle + # self-referential objects + seen.add(obj_id) + if isinstance(obj, dict): + size += sum([get_size(v, seen) for v in obj.values()]) + size += sum([get_size(k, seen) for k in obj.keys()]) + elif hasattr(obj, "__dict__"): + size += get_size(obj.__dict__, seen) + elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes, bytearray)): + size += sum([get_size(i, seen) for i in obj]) + return size + + +def cast_int(raw: str) -> int: + """ + 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 returns ``None``. + + Args: + raw (str): The string to convert. + + Returns: + int or None: The converted integer, or ``None`` if the input was ``None``. + + """ + return int(raw) if raw is not None else raw + + +def cast_float(raw: str) -> Optional[float]: + """ + 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 returns ``None``. + + Args: + raw (str): The string to convert. + + Returns: + float or None: The converted float, or ``None`` if the input was ``None``. + + """ + return float(raw) if raw is not None else raw + + +class TerminalInfo(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. + + Args: + 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. + + Usage:: + + # Creating a TerminalInfo instance + from bittensor.core.synapse import TerminalInfo + + terminal_info = TerminalInfo( + status_code=200, + status_message="Success", + process_time=0.1, + ip="198.123.23.1", + port=9282, + version=111, + nonce=111111, + uuid="5ecbd69c-1cec-11ee-b0dc-e29ce36fec1a", + hotkey="5EnjDGNqqWnuL2HCAdxeEtN2oqtXZw6BMBe936Kfy2PFz1J1", + signature="0x0813029319030129u4120u10841824y0182u091u230912u" + ) + + # Accessing TerminalInfo attributes + ip_address = terminal_info.ip + processing_duration = terminal_info.process_time + + # TerminalInfo can be used to monitor and verify network interactions, ensuring proper communication and security within the Bittensor network. + + TerminalInfo plays a pivotal role in providing transparency and control over network operations, making it an indispensable tool for developers and users interacting with the Bittensor ecosystem. + """ + + model_config = ConfigDict(validate_assignment=True) + + # The HTTP status code from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + status_code: Optional[int] = Field( + title="status_code", + description="The HTTP status code from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status", + examples=[200], + default=None, + frozen=False, + ) + + # The HTTP status code from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + status_message: Optional[str] = Field( + title="status_message", + description="The status_message associated with the status_code", + examples=["Success"], + default=None, + frozen=False, + ) + + # Process time on this terminal side of call + process_time: Optional[float] = Field( + title="process_time", + description="Process time on this terminal side of call", + examples=[0.1], + default=None, + frozen=False, + ) + + # The terminal ip. + ip: Optional[str] = Field( + title="ip", + description="The ip of the axon receiving the request.", + examples=["198.123.23.1"], + default=None, + frozen=False, + ) + + # The host port of the terminal. + port: Optional[int] = Field( + title="port", + description="The port of the terminal.", + examples=["9282"], + default=None, + frozen=False, + ) + + # The bittensor version on the terminal as an int. + version: Optional[int] = Field( + title="version", + description="The bittensor version on the axon as str(int)", + examples=[111], + default=None, + frozen=False, + ) + + # A Unix timestamp to associate with the terminal + nonce: Optional[int] = Field( + title="nonce", + description="A Unix timestamp that prevents replay attacks", + examples=[111111], + default=None, + frozen=False, + ) + + # A unique identifier associated with the terminal, set on the axon side. + uuid: Optional[str] = Field( + title="uuid", + description="A unique identifier associated with the terminal", + examples=["5ecbd69c-1cec-11ee-b0dc-e29ce36fec1a"], + default=None, + frozen=False, + ) + + # The bittensor version on the terminal as an int. + hotkey: Optional[str] = Field( + title="hotkey", + description="The ss58 encoded hotkey string of the terminal wallet.", + examples=["5EnjDGNqqWnuL2HCAdxeEtN2oqtXZw6BMBe936Kfy2PFz1J1"], + default=None, + frozen=False, + ) + + # A signature verifying the tuple (axon_nonce, axon_hotkey, dendrite_hotkey, axon_uuid) + signature: Optional[str] = Field( + title="signature", + description="A signature verifying the tuple (nonce, axon_hotkey, dendrite_hotkey, uuid)", + examples=["0x0813029319030129u4120u10841824y0182u091u230912u"], + default=None, + frozen=False, + ) + + # Extract the process time on this terminal side of call as a float + _extract_process_time = field_validator("process_time", mode="before")(cast_float) + + # Extract the host port of the terminal as an int + _extract_port = field_validator("port", mode="before")(cast_int) + + # Extract the bittensor version on the terminal as an int. + _extract_version = field_validator("version", mode="before")(cast_int) + + # Extract the Unix timestamp associated with the terminal as an int + _extract_nonce = field_validator("nonce", mode="before")(cast_int) + + # Extract the HTTP status code as an int + _extract_status_code = field_validator("status_code", mode="before")(cast_int) + + +class Synapse(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: + + 1. 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. + + 2. 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. + + 3. 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. + + 4. 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. + + 5. Body Hash Computation (``computed_body_hash``, ``required_hash_fields``): + Ensures data integrity and security by computing hashes of transmitted data. Provides users with a + mechanism to verify data integrity and detect any tampering during transmission. + It is recommended that names of fields in `required_hash_fields` are listed in the order they are + defined in the class. + + 6. 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. + + 7. 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. + + Example usage:: + + # Creating a Synapse instance with default values + from bittensor.core.synapse import Synapse + + synapse = Synapse() + + # Setting properties and input + synapse.timeout = 15.0 + synapse.name = "MySynapse" + + # Not setting fields that are not defined in your synapse class will result in an error, e.g.: + synapse.dummy_input = 1 # This will raise an error because dummy_input is not defined in the Synapse class + + # Get a dictionary of headers and body from the synapse instance + synapse_dict = synapse.model_dump_json() + + # Get a dictionary of headers from the synapse instance + headers = synapse.to_headers() + + # Reconstruct the synapse from headers using the classmethod 'from_headers' + synapse = Synapse.from_headers(headers) + + # Deserialize synapse after receiving it over the network, controlled by `deserialize` method + deserialized_synapse = synapse.deserialize() + + # Checking the status of the request + if synapse.is_success: + print("Request succeeded") + + # Checking and setting the status of the request + print(synapse.axon.status_code) + synapse.axon.status_code = 408 # Timeout + + Args: + name (str): HTTP route name, set on :func:`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 (:func:`TerminalInfo`): Information about the dendrite terminal. + axon (:func:`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. + + Methods: + deserialize: Custom deserialization logic for subclasses. + __setattr__: Override method to make ``required_hash_fields`` read-only. + get_total_size: Calculates and returns the total size of the object. + to_headers: Constructs a dictionary of headers from instance properties. + body_hash: Computes a SHA3-256 hash of the serialized body. + 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. + """ + + model_config = ConfigDict(validate_assignment=True) + + def deserialize(self) -> "Synapse": + """ + Deserializes the Synapse object. + + This method is intended to be overridden by subclasses for custom deserialization logic. + In the context of the Synapse superclass, this method simply returns the instance itself. + When inheriting from this class, subclasses should provide their own implementation for + deserialization if specific deserialization behavior is desired. + + By default, if a subclass does not provide its own implementation of this method, the + Synapse's deserialize method will be used, returning the object instance as-is. + + In its default form, this method simply returns the instance of the Synapse itself without any modifications. Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting serialized data back into complex object types or performing additional data integrity checks. + + Example:: + + class CustomSynapse(Synapse): + additional_data: str + + def deserialize(self) -> "CustomSynapse": + # Custom deserialization logic + # For example, decoding a base64 encoded string in 'additional_data' + if self.additional_data: + self.additional_data = base64.b64decode(self.additional_data).decode('utf-8') + return self + + serialized_data = '{"additional_data": "SGVsbG8gV29ybGQ="}' # Base64 for 'Hello World' + custom_synapse = CustomSynapse.model_validate_json(serialized_data) + deserialized_synapse = custom_synapse.deserialize() + + # deserialized_synapse.additional_data would now be 'Hello World' + + Returns: + Synapse: The deserialized Synapse object. In this default implementation, it returns the object itself. + """ + return self + + @model_validator(mode="before") + def set_name_type(cls, values: dict) -> dict: + values["name"] = cls.__name__ # type: ignore + return values + + # Defines the http route name which is set on axon.attach( callable( request: RequestName )) + name: Optional[str] = Field( + title="name", + description="Defines the http route name which is set on axon.attach( callable( request: RequestName ))", + examples=["Forward"], + frozen=False, + default=None, + repr=False, + ) + + # The call timeout, set by the dendrite terminal. + timeout: Optional[float] = Field( + title="timeout", + description="Defines the total query length.", + examples=[12.0], + default=12.0, + frozen=False, + repr=False, + ) + + # The call timeout, set by the dendrite terminal. + total_size: Optional[int] = Field( + title="total_size", + description="Total size of request body in bytes.", + examples=[1000], + default=0, + frozen=False, + repr=False, + ) + + # The call timeout, set by the dendrite terminal. + header_size: Optional[int] = Field( + title="header_size", + description="Size of request header in bytes.", + examples=[1000], + default=0, + frozen=False, + repr=False, + ) + + # The dendrite Terminal Information. + dendrite: Optional[TerminalInfo] = Field( + title="dendrite", + description="Dendrite Terminal Information", + examples=["TerminalInfo"], + default=TerminalInfo(), + frozen=False, + repr=False, + ) + + # A axon terminal information + axon: Optional[TerminalInfo] = Field( + title="axon", + description="Axon Terminal Information", + examples=["TerminalInfo"], + default=TerminalInfo(), + frozen=False, + repr=False, + ) + + computed_body_hash: Optional[str] = Field( + title="computed_body_hash", + description="The computed body hash of the request.", + examples=["0x0813029319030129u4120u10841824y0182u091u230912u"], + default="", + frozen=True, + repr=False, + ) + + required_hash_fields: ClassVar[tuple[str, ...]] = () + + _extract_total_size = field_validator("total_size", mode="before")(cast_int) + + _extract_header_size = field_validator("header_size", mode="before")(cast_int) + + _extract_timeout = field_validator("timeout", mode="before")(cast_float) + + def __setattr__(self, name: str, value: Any): + """ + Override the :func:`__setattr__` method to make the ``required_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. + """ + if name == "body_hash": + raise AttributeError( + "body_hash property is read-only and cannot be overridden." + ) + super().__setattr__(name, value) + + def get_total_size(self) -> int: + """ + 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 :func:`self.total_size` and finally returns this value. + + Returns: + int: The total size of the current object. + """ + self.total_size = get_size(self) + return self.total_size + + @property + def is_success(self) -> bool: + """ + Checks if the dendrite's status code indicates success. + + This method returns ``True`` if the status code of the dendrite is ``200``, + which typically represents a successful HTTP request. + + Returns: + bool: ``True`` if dendrite's status code is ``200``, ``False`` otherwise. + """ + return self.dendrite is not None and self.dendrite.status_code == 200 + + @property + def is_failure(self) -> bool: + """ + Checks if the dendrite's status code indicates failure. + + This method returns ``True`` if the status code of the dendrite is not ``200``, + which would mean the HTTP request was not successful. + + Returns: + bool: ``True`` if dendrite's status code is not ``200``, ``False`` otherwise. + """ + return self.dendrite is not None and self.dendrite.status_code != 200 + + @property + def is_timeout(self) -> bool: + """ + Checks if the dendrite's status code indicates a timeout. + + This method returns ``True`` if the status code of the dendrite is ``408``, + which is the HTTP status code for a request timeout. + + Returns: + bool: ``True`` if dendrite's status code is ``408``, ``False`` otherwise. + """ + return self.dendrite is not None and self.dendrite.status_code == 408 + + @property + def is_blacklist(self) -> bool: + """ + Checks if the dendrite's status code indicates a blacklisted request. + + This method returns ``True`` if the status code of the dendrite is ``403``, + which is the HTTP status code for a forbidden request. + + Returns: + bool: ``True`` if dendrite's status code is ``403``, ``False`` otherwise. + """ + return self.dendrite is not None and self.dendrite.status_code == 403 + + @property + def failed_verification(self) -> bool: + """ + Checks if the dendrite's status code indicates failed verification. + + This method returns ``True`` if the status code of the dendrite is ``401``, + which is the HTTP status code for unauthorized access. + + Returns: + bool: ``True`` if dendrite's status code is ``401``, ``False`` otherwise. + """ + return self.dendrite is not None and self.dendrite.status_code == 401 + + def get_required_fields(self): + """ + Get the required fields from the model's JSON schema. + """ + schema = self.__class__.model_json_schema() + return schema.get("required", []) + + def to_headers(self) -> dict: + """ + 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: + + 1. Basic Information: It starts by including the ``name`` and ``timeout`` of the Synapse, which are fundamental for identifying the query and managing its lifespan on the network. + 2. Complex Objects: The method serializes the ``axon`` and ``dendrite`` objects, if present, into strings. This serialization is crucial for preserving the state and structure of these objects over the network. + 3. Encoding: Non-optional complex objects are serialized and encoded in base64, making them safe for HTTP transport. + 4. 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: + dict: A dictionary containing key-value pairs representing the Synapse's properties, suitable for HTTP communication. + """ + # Initializing headers with 'name' and 'timeout' + headers = {"name": self.name, "timeout": str(self.timeout)} + + # Adding headers for 'axon' and 'dendrite' if they are not None + if self.axon: + headers.update( + { + f"bt_header_axon_{k}": str(v) + for k, v in self.axon.model_dump().items() + if v is not None + } + ) + if self.dendrite: + headers.update( + { + f"bt_header_dendrite_{k}": str(v) + for k, v in self.dendrite.model_dump().items() + if v is not None + } + ) + + # Getting the fields of the instance + instance_fields = self.model_dump() + + # Iterating over the fields of the instance + for field, value in instance_fields.items(): + # If the object is not optional, serializing it, encoding it, and adding it to the headers + required = self.get_required_fields() + + # Skipping the field if it's already in the headers or its value is None + if field in headers or value is None: + continue + + elif required and field in required: + try: + # create an empty (dummy) instance of type(value) to pass pydantic validation on the axon side + serialized_value = json.dumps(value.__class__.__call__()) + encoded_value = base64.b64encode(serialized_value.encode()).decode( + "utf-8" + ) + headers[f"bt_header_input_obj_{field}"] = encoded_value + except TypeError as e: + raise ValueError( + f"Error serializing {field} with value {value}. Objects must be json serializable." + ) from e + + # Adding the size of the headers and the total size to the headers + headers["header_size"] = str(sys.getsizeof(headers)) + headers["total_size"] = str(self.get_total_size()) + headers["computed_body_hash"] = self.body_hash + + return headers + + @property + def body_hash(self) -> 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: + + 1. Iterates over each required field as specified in ``required_hash_fields``. + 2. Concatenates the string representation of these fields. + 3. 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: + str: The SHA3-256 hash as a hexadecimal string, providing a fingerprint of the Synapse instance's data for integrity checks. + """ + hashes = [] + + hash_fields_field = self.model_fields.get("required_hash_fields") + instance_fields = None + if hash_fields_field: + warnings.warn( + "The 'required_hash_fields' field handling deprecated and will be removed. " + "Please update Synapse class definition to use 'required_hash_fields' class variable instead.", + DeprecationWarning, + ) + required_hash_fields = hash_fields_field.default + + if required_hash_fields: + instance_fields = self.model_dump() + # Preserve backward compatibility in which fields will added in .model_dump() order + # instead of the order one from `self.required_hash_fields` + required_hash_fields = [ + field for field in instance_fields if field in required_hash_fields + ] + + # Hack to cache the required hash fields names + if len(required_hash_fields) == len(required_hash_fields): + self.__class__.required_hash_fields = tuple(required_hash_fields) + else: + required_hash_fields = self.__class__.required_hash_fields + + if required_hash_fields: + instance_fields = instance_fields or self.model_dump() + for field in required_hash_fields: + hashes.append(get_hash(str(instance_fields[field]))) + + return get_hash("".join(hashes)) + + @classmethod + def parse_headers_to_inputs(cls, headers: dict) -> dict: + """ + 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: + + 1. Separates headers into categories based on prefixes (``axon``, ``dendrite``, etc.). + 2. Decodes and deserializes ``input_obj`` headers into their original objects. + 3. 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 :func:`Synapse.from_headers(headers)` and does not need to be called directly. + + Args: + headers (dict): The headers dictionary to parse. + + Returns: + dict: A structured dictionary representing the inputs for constructing a Synapse instance. + """ + + # Initialize the input dictionary with empty sub-dictionaries for 'axon' and 'dendrite' + inputs_dict: dict[str, Union[dict, Optional[str]]] = { + "axon": {}, + "dendrite": {}, + } + + # Iterate over each item in the headers + for key, value in headers.items(): + # Handle 'axon' headers + if "bt_header_axon_" in key: + try: + new_key = key.split("bt_header_axon_")[1] + axon_dict = cast(dict, inputs_dict["axon"]) + axon_dict[new_key] = value + except Exception as e: + logging.error(f"Error while parsing 'axon' header {key}: {str(e)}") + continue + # Handle 'dendrite' headers + elif "bt_header_dendrite_" in key: + try: + new_key = key.split("bt_header_dendrite_")[1] + dendrite_dict = cast(dict, inputs_dict["dendrite"]) + dendrite_dict[new_key] = value + except Exception as e: + logging.error(f"Error while parsing 'dendrite' header {key}: {e}") + continue + # Handle 'input_obj' headers + elif "bt_header_input_obj" in key: + try: + new_key = key.split("bt_header_input_obj_")[1] + # Skip if the key already exists in the dictionary + if new_key in inputs_dict: + continue + # Decode and load the serialized object + inputs_dict[new_key] = json.loads( + base64.b64decode(value.encode()).decode("utf-8") + ) + except json.JSONDecodeError as e: + logging.error( + f"Error while json decoding 'input_obj' header {key}: {e}" + ) + continue + except Exception as e: + logging.error(f"Error while parsing 'input_obj' header {key}: {e}") + continue + else: + pass # TODO: log unexpected keys + + # Assign the remaining known headers directly + inputs_dict["timeout"] = headers.get("timeout", None) + inputs_dict["name"] = headers.get("name", None) + inputs_dict["header_size"] = headers.get("header_size", None) + inputs_dict["total_size"] = headers.get("total_size", None) + inputs_dict["computed_body_hash"] = headers.get("computed_body_hash", None) + + return inputs_dict + + @classmethod + def from_headers(cls, headers: dict) -> "Synapse": + """ + 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 + + Args: + headers (dict): The dictionary of headers containing serialized Synapse information. + + Returns: + bittensor.core.synapse.Synapse: A new instance of Synapse, reconstructed from the parsed header information, replicating the original instance's state. + """ + + # Get the inputs dictionary from the headers + input_dict = cls.parse_headers_to_inputs(headers) + + # Use the dictionary unpacking operator to pass the inputs to the class constructor + synapse = cls(**input_dict) + + return synapse diff --git a/bittensor/core/tensor.py b/bittensor/core/tensor.py new file mode 100644 index 0000000000..4ec71cc44f --- /dev/null +++ b/bittensor/core/tensor.py @@ -0,0 +1,249 @@ +# The MIT License (MIT) +# Copyright © 2024 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 base64 +from typing import Optional, Union + +import msgpack +import msgpack_numpy +import numpy as np +from pydantic import ConfigDict, BaseModel, Field, field_validator + +from bittensor.utils.registration import torch, use_torch + + +class DTypes(dict): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.torch: bool = False + self.update( + { + "float16": np.float16, + "float32": np.float32, + "float64": np.float64, + "uint8": np.uint8, + "int16": np.int16, + "int8": np.int8, + "int32": np.int32, + "int64": np.int64, + "bool": bool, + } + ) + + def __getitem__(self, key): + self._add_torch() + return super().__getitem__(key) + + def __contains__(self, key): + self._add_torch() + return super().__contains__(key) + + def _add_torch(self): + if self.torch is False: + torch_dtypes = { + "torch.float16": torch.float16, + "torch.float32": torch.float32, + "torch.float64": torch.float64, + "torch.uint8": torch.uint8, + "torch.int16": torch.int16, + "torch.int8": torch.int8, + "torch.int32": torch.int32, + "torch.int64": torch.int64, + "torch.bool": torch.bool, + } + self.update(torch_dtypes) + self.torch = True + + +dtypes = DTypes() + + +def cast_dtype(raw: Union[None, np.dtype, "torch.dtype", str]) -> Optional[str]: + """ + Casts the raw value to a string representing the `numpy data type `_, or the `torch data type `_ if using torch. + + Args: + raw (Union[None, numpy.dtype, torch.dtype, str]): The raw value to cast. + + Returns: + str: The string representing the numpy/torch data type. + + Raises: + Exception: If the raw value is of an invalid type. + """ + if not raw: + return None + if use_torch() and isinstance(raw, torch.dtype): + return dtypes[raw] + elif isinstance(raw, np.dtype): + return dtypes[raw] + elif isinstance(raw, str): + if use_torch(): + assert raw in dtypes, f"{raw} not a valid torch type in dict {dtypes}" + return raw + else: + assert raw in dtypes, f"{raw} not a valid numpy type in dict {dtypes}" + return raw + else: + raise Exception( + f"{raw} of type {type(raw)} does not have a valid type in Union[None, numpy.dtype, torch.dtype, str]" + ) + + +def cast_shape(raw: Union[None, list[int], str]) -> Optional[Union[str, list]]: + """ + Casts the raw value to a string representing the tensor shape. + + Args: + raw (Union[None, list[int], str]): The raw value to cast. + + Returns: + str: The string representing the tensor shape. + + Raises: + Exception: If the raw value is of an invalid type or if the list elements are not of type int. + """ + if not raw: + return None + elif isinstance(raw, list): + if len(raw) == 0 or isinstance(raw[0], int): + return raw + else: + raise Exception(f"{raw} list elements are not of type int") + elif isinstance(raw, str): + shape = list(map(int, raw.split("[")[1].split("]")[0].split(","))) + return shape + else: + raise Exception( + f"{raw} of type {type(raw)} does not have a valid type in Union[None, list[int], str]" + ) + + +class tensor: + def __new__(cls, tensor: Union[list, "np.ndarray", "torch.Tensor"]): + if isinstance(tensor, list) or isinstance(tensor, np.ndarray): + tensor = torch.tensor(tensor) if use_torch() else np.array(tensor) + return Tensor.serialize(tensor_=tensor) + + +class Tensor(BaseModel): + """ + Represents a Tensor object. + + Args: + buffer (Optional[str]): Tensor buffer data. + dtype (str): Tensor data type. + shape (list[int]): Tensor shape. + """ + + model_config = ConfigDict(validate_assignment=True) + + def tensor(self) -> Union[np.ndarray, "torch.Tensor"]: + return self.deserialize() + + def tolist(self) -> list[object]: + return self.deserialize().tolist() + + def numpy(self) -> "np.ndarray": + return ( + self.deserialize().detach().numpy() if use_torch() else self.deserialize() + ) + + def deserialize(self) -> Union["np.ndarray", "torch.Tensor"]: + """ + Deserializes the Tensor object. + + Returns: + np.array or torch.Tensor: The deserialized tensor object. + + Raises: + Exception: If the deserialization process encounters an error. + """ + shape = tuple(self.shape) + buffer_bytes = base64.b64decode(self.buffer.encode("utf-8")) + numpy_object = msgpack.unpackb( + buffer_bytes, object_hook=msgpack_numpy.decode + ).copy() + if use_torch(): + torch_object = torch.as_tensor(numpy_object) + # Reshape does not work for (0) or [0] + if not (len(shape) == 1 and shape[0] == 0): + torch_object = torch_object.reshape(shape) + return torch_object.type(dtypes[self.dtype]) + else: + # Reshape does not work for (0) or [0] + if not (len(shape) == 1 and shape[0] == 0): + numpy_object = numpy_object.reshape(shape) + return numpy_object.astype(dtypes[self.dtype]) + + @staticmethod + def serialize(tensor_: Union["np.ndarray", "torch.Tensor"]) -> "Tensor": + """ + Serializes the given tensor. + + Args: + tensor_ (np.array or torch.Tensor): The tensor to serialize. + + Returns: + :func:`Tensor`: The serialized tensor. + + Raises: + Exception: If the serialization process encounters an error. + """ + dtype = str(tensor_.dtype) + shape = list(tensor_.shape) + if len(shape) == 0: + shape = [0] + tensor__ = tensor_.cpu().detach().numpy().copy() if use_torch() else tensor_ + data_buffer = base64.b64encode( + msgpack.packb(tensor__, default=msgpack_numpy.encode) + ).decode("utf-8") + return Tensor(buffer=data_buffer, shape=shape, dtype=dtype) + + # Represents the tensor buffer data. + buffer: Optional[str] = Field( + default=None, + title="buffer", + description="Tensor buffer data. This field stores the serialized representation of the tensor data.", + examples=["0x321e13edqwds231231231232131"], + frozen=True, + repr=False, + ) + + # Represents the data type of the tensor. + dtype: str = Field( + title="dtype", + description="Tensor data type. This field specifies the data type of the tensor, such as numpy.float32 or torch.int64.", + examples=["np.float32"], + frozen=True, + repr=True, + ) + + # Represents the shape of the tensor. + shape: list[int] = Field( + title="shape", + description="Tensor shape. This field defines the dimensions of the tensor as a list of integers, such as [10, 10] for a 2D tensor with shape (10, 10).", + examples=[10, 10], + frozen=True, + repr=True, + ) + + # Extract the represented shape of the tensor. + _extract_shape = field_validator("shape", mode="before")(cast_shape) + + # Extract the represented data type of the tensor. + _extract_dtype = field_validator("dtype", mode="before")(cast_dtype) diff --git a/bittensor/core/threadpool.py b/bittensor/core/threadpool.py new file mode 100644 index 0000000000..17e5535096 --- /dev/null +++ b/bittensor/core/threadpool.py @@ -0,0 +1,295 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Implements `ThreadPoolExecutor `_.""" + +__author__ = "Brian Quinlan (brian@sweetapp.com)" + +import argparse +import itertools +import logging +import os +import queue +import random +import sys +import threading +import time +import weakref +from concurrent.futures import _base +from typing import Callable + +from bittensor.core.config import Config +from bittensor.core.settings import BLOCKTIME +from bittensor.utils.btlogging.defines import BITTENSOR_LOGGER_NAME + +# Workers are created as daemon threads. This is done to allow the interpreter +# to exit when there are still idle threads in a ThreadPoolExecutor's thread +# pool (i.e. shutdown() was not called). However, allowing workers to die with +# the interpreter has two undesirable properties: +# - The workers would still be running during interpreter shutdown, +# meaning that they would fail in unpredictable ways. +# - The workers could be killed while evaluating a work item, which could +# be bad if the callable being evaluated has external side-effects e.g. +# writing to a file. +# +# To work around this problem, an exit handler is installed which tells the +# workers to exit when their work queues are empty and then waits until the +# threads finish. + +logger = logging.getLogger(BITTENSOR_LOGGER_NAME) + +_threads_queues = weakref.WeakKeyDictionary() +_shutdown = False + + +class _WorkItem(object): + def __init__(self, future, fn, start_time, args, kwargs): + self.future = future + self.fn = fn + self.start_time = start_time + self.args = args + self.kwargs = kwargs + + def run(self): + """Run the given work item""" + # Checks if future is canceled or if work item is stale + if (not self.future.set_running_or_notify_cancel()) or ( + time.time() - self.start_time > BLOCKTIME + ): + return + + try: + result = self.fn(*self.args, **self.kwargs) + except BaseException as exc: + self.future.set_exception(exc) + # Break a reference cycle with the exception 'exc' + self = None + else: + self.future.set_result(result) + + +NULL_ENTRY = (sys.maxsize, _WorkItem(None, None, time.time(), (), {})) + + +def _worker(executor_reference, work_queue, initializer, initargs): + if initializer is not None: + try: + initializer(*initargs) + except BaseException: + _base.LOGGER.critical("Exception in initializer:", exc_info=True) + executor = executor_reference() + if executor is not None: + executor._initializer_failed() + return + try: + while True: + work_item = work_queue.get(block=True) + priority = work_item[0] + item = work_item[1] + if priority == sys.maxsize: + del item + elif item is not None: + item.run() + # Delete references to object. See issue16284 + del item + continue + + executor = executor_reference() + # Exit if: + # - The interpreter is shutting down OR + # - The executor that owns the worker has been collected OR + # - The executor that owns the worker has been shutdown. + if _shutdown or executor is None or executor._shutdown: + # Flag the executor as shutting down as early as possible if it + # is not gc-ed yet. + if executor is not None: + executor._shutdown = True + # Notice other workers + work_queue.put(NULL_ENTRY) + return + del executor + except BaseException: + logger.error("work_item", work_item) + _base.LOGGER.critical("Exception in worker", exc_info=True) + + +class BrokenThreadPool(_base.BrokenExecutor): + """ + Raised when a worker thread in a `ThreadPoolExecutor `_ failed initializing. + """ + + +class PriorityThreadPoolExecutor(_base.Executor): + """Base threadpool executor with a priority queue.""" + + # Used to assign unique thread names when thread_name_prefix is not supplied. + _counter = itertools.count().__next__ + + def __init__( + self, + maxsize=-1, + max_workers=None, + thread_name_prefix="", + initializer=None, + initargs=(), + ): + """Initializes a new `ThreadPoolExecutor `_ instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + thread_name_prefix: An optional name prefix to give our threads. + initializer: An callable used to initialize worker threads. + initargs: A tuple of arguments to pass to the initializer. + """ + if max_workers is None: + # Use this number because ThreadPoolExecutor is often + # used to overlap I/O instead of CPU work. + max_workers = (os.cpu_count() or 1) * 5 + if max_workers <= 0: + raise ValueError("max_workers must be greater than 0") + + if initializer is not None and not callable(initializer): + raise TypeError("initializer must be a callable") + + self._max_workers = max_workers + self._work_queue = queue.PriorityQueue(maxsize=maxsize) + self._idle_semaphore = threading.Semaphore(0) + self._threads = set() + self._broken = False + self._shutdown = False + self._shutdown_lock = threading.Lock() + self._thread_name_prefix = thread_name_prefix or ( + "ThreadPoolExecutor-%d" % self._counter() + ) + self._initializer = initializer + self._initargs = initargs + + @classmethod + def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): + """Accept specific arguments from parser""" + prefix_str = "" if prefix is None else prefix + "." + try: + default_max_workers = ( + os.getenv("BT_PRIORITY_MAX_WORKERS") + if os.getenv("BT_PRIORITY_MAX_WORKERS") is not None + else 5 + ) + default_maxsize = ( + os.getenv("BT_PRIORITY_MAXSIZE") + if os.getenv("BT_PRIORITY_MAXSIZE") is not None + else 10 + ) + parser.add_argument( + "--" + prefix_str + "priority.max_workers", + type=int, + help="""maximum number of threads in thread pool""", + default=default_max_workers, + ) + parser.add_argument( + "--" + prefix_str + "priority.maxsize", + type=int, + help="""maximum size of tasks in priority queue""", + default=default_maxsize, + ) + except argparse.ArgumentError: + # re-parsing arguments. + pass + + @classmethod + def config(cls) -> "Config": + """Get config from the argument parser. + + Return: :func:`bittensor.Config` object. + """ + parser = argparse.ArgumentParser() + PriorityThreadPoolExecutor.add_args(parser) + return Config(parser, args=[]) + + @property + def is_empty(self): + return self._work_queue.empty() + + def submit(self, fn: Callable, *args, **kwargs) -> _base.Future: + with self._shutdown_lock: + if self._broken: + raise BrokenThreadPool(self._broken) + + if self._shutdown: + raise RuntimeError("cannot schedule new futures after shutdown") + if _shutdown: + raise RuntimeError( + "cannot schedule new futures after " "interpreter shutdown" + ) + + priority = kwargs.get("priority", random.randint(0, 1000000)) + if priority == 0: + priority = random.randint(1, 100) + epsilon = random.uniform(0, 0.01) * priority + start_time = time.time() + if "priority" in kwargs: + del kwargs["priority"] + + f = _base.Future() + w = _WorkItem(f, fn, start_time, args, kwargs) + self._work_queue.put((-float(priority + epsilon), w), block=False) + self._adjust_thread_count() + return f + + submit.__doc__ = _base.Executor.submit.__doc__ + + def _adjust_thread_count(self): + # if idle threads are available, don't spin new threads + if self._idle_semaphore.acquire(timeout=0): + return + + # When the executor gets lost, the weakref callback will wake up + # the worker threads. + def weakref_cb(_, q=self._work_queue): + q.put(NULL_ENTRY) + + num_threads = len(self._threads) + if num_threads < self._max_workers: + thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads) + t = threading.Thread( + name=thread_name, + target=_worker, + args=( + weakref.ref(self, weakref_cb), + self._work_queue, + self._initializer, + self._initargs, + ), + ) + t.daemon = True + t.start() + self._threads.add(t) + _threads_queues[t] = self._work_queue + + def _initializer_failed(self): + with self._shutdown_lock: + self._broken = ( + "A thread initializer failed, the thread pool " "is not usable anymore" + ) + # Drain work queue and mark pending futures failed + while True: + try: + work_item = self._work_queue.get_nowait() + except queue.Empty: + break + if work_item is not None: + work_item.future.set_exception(BrokenThreadPool(self._broken)) + + def shutdown(self, wait=True): + with self._shutdown_lock: + self._shutdown = True + self._work_queue.put(NULL_ENTRY) + + if wait: + for t in self._threads: + try: + t.join(timeout=2) + except Exception: + pass + + shutdown.__doc__ = _base.Executor.shutdown.__doc__ diff --git a/bittensor/core/types.py b/bittensor/core/types.py new file mode 100644 index 0000000000..9fd2b4d052 --- /dev/null +++ b/bittensor/core/types.py @@ -0,0 +1,38 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from typing import TypedDict + + +class AxonServeCallParams(TypedDict): + """Axon serve chain call parameters.""" + + version: int + ip: int + port: int + ip_type: int + netuid: int + + +class PrometheusServeCallParams(TypedDict): + """Prometheus serve chain call parameters.""" + + version: int + ip: int + port: int + ip_type: int + netuid: int diff --git a/bittensor/utils/__init__.py b/bittensor/utils/__init__.py new file mode 100644 index 0000000000..58a7e0a7c2 --- /dev/null +++ b/bittensor/utils/__init__.py @@ -0,0 +1,279 @@ +# The MIT License (MIT) +# Copyright © 2024 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 hashlib +from typing import List, Dict, Literal, Union, Optional, TYPE_CHECKING + +import scalecodec +from substrateinterface import Keypair +from substrateinterface.utils import ss58 + +from bittensor.core.settings import SS58_FORMAT +from bittensor.utils.btlogging import logging +from .registration import torch, use_torch +from .version import version_checking, check_version, VersionCheckError + +if TYPE_CHECKING: + from substrateinterface import SubstrateInterface + +RAOPERTAO = 1e9 +U16_MAX = 65535 +U64_MAX = 18446744073709551615 + + +def ss58_to_vec_u8(ss58_address: str) -> list[int]: + ss58_bytes: bytes = ss58_address_to_bytes(ss58_address) + encoded_address: list[int] = [int(byte) for byte in ss58_bytes] + return encoded_address + + +def strtobool(val: str) -> Union[bool, Literal["==SUPRESS=="]]: + """ + Converts a string to a boolean value. + + truth-y values are 'y', 'yes', 't', 'true', 'on', and '1'; + false-y values are 'n', 'no', 'f', 'false', 'off', and '0'. + + Raises ValueError if 'val' is anything else. + """ + val = val.lower() + if val in ("y", "yes", "t", "true", "on", "1"): + return True + elif val in ("n", "no", "f", "false", "off", "0"): + return False + else: + raise ValueError("invalid truth value %r" % (val,)) + + +def _get_explorer_root_url_by_network_from_map( + network: str, network_map: dict[str, dict[str, str]] +) -> Optional[dict[str, str]]: + """ + Returns the explorer root url for the given network name from the given network map. + + Args: + network(str): The network to get the explorer url for. + network_map(dict[str, str]): The network map to get the explorer url from. + + Returns: + The explorer url for the given network. + Or None if the network is not in the network map. + """ + explorer_urls: Optional[dict[str, str]] = {} + for entity_nm, entity_network_map in network_map.items(): + if network in entity_network_map: + explorer_urls[entity_nm] = entity_network_map[network] + + return explorer_urls + + +def get_explorer_url_for_network( + network: str, block_hash: str, network_map: dict[str, dict[str, str]] +) -> Optional[dict[str, str]]: + """ + Returns the explorer url for the given block hash and network. + + Args: + network(str): The network to get the explorer url for. + block_hash(str): The block hash to get the explorer url for. + network_map(dict[str, dict[str, str]]): The network maps to get the explorer urls from. + + Returns: + The explorer url for the given block hash and network. + Or None if the network is not known. + """ + + explorer_urls: Optional[dict[str, str]] = {} + # Will be None if the network is not known. i.e. not in network_map + explorer_root_urls: Optional[dict[str, str]] = ( + _get_explorer_root_url_by_network_from_map(network, network_map) + ) + + if explorer_root_urls != {}: + # We are on a known network. + explorer_opentensor_url = ( + f"{explorer_root_urls.get('opentensor')}/query/{block_hash}" + ) + explorer_taostats_url = ( + f"{explorer_root_urls.get('taostats')}/extrinsic/{block_hash}" + ) + explorer_urls["opentensor"] = explorer_opentensor_url + explorer_urls["taostats"] = explorer_taostats_url + + return explorer_urls + + +def ss58_address_to_bytes(ss58_address: str) -> bytes: + """Converts a ss58 address to a bytes object.""" + account_id_hex: str = scalecodec.ss58_decode(ss58_address, SS58_FORMAT) + return bytes.fromhex(account_id_hex) + + +def u16_normalized_float(x: int) -> float: + return float(x) / float(U16_MAX) + + +def u64_normalized_float(x: int) -> float: + return float(x) / float(U64_MAX) + + +def get_hash(content, encoding="utf-8"): + sha3 = hashlib.sha3_256() + + # Update the hash object with the concatenated string + sha3.update(content.encode(encoding)) + + # Produce the hash + return sha3.hexdigest() + + +def format_error_message( + error_message: dict, substrate: "SubstrateInterface" = None +) -> str: + """ + Formats an error message from the Subtensor error information for use in extrinsics. + + Args: + error_message (dict): A dictionary containing the error information from Subtensor. + substrate (SubstrateInterface, optional): The substrate interface to use. + + Returns: + str: A formatted error message string. + """ + err_name = "UnknownError" + err_type = "UnknownType" + err_description = "Unknown Description" + + if isinstance(error_message, dict): + # subtensor error structure + if ( + error_message.get("code") + and error_message.get("message") + and error_message.get("data") + ): + err_name = "SubstrateRequestException" + err_type = error_message.get("message") + err_data = error_message.get("data") + + # subtensor custom error marker + if err_data.startswith("Custom error:") and substrate: + if not substrate.metadata: + substrate.get_metadata() + + if substrate.metadata: + try: + pallet = substrate.metadata.get_metadata_pallet( + "SubtensorModule" + ) + error_index = int(err_data.split("Custom error:")[-1]) + + error_dict = pallet.errors[error_index].value + err_type = error_dict.get("message", err_type) + err_docs = error_dict.get("docs", []) + err_description = err_docs[0] if err_docs else err_description + except Exception: + logging.error("Substrate pallets data unavailable.") + else: + err_description = err_data + + elif ( + error_message.get("type") + and error_message.get("name") + and error_message.get("docs") + ): + err_type = error_message.get("type", err_type) + err_name = error_message.get("name", err_name) + err_docs = error_message.get("docs", [err_description]) + err_description = err_docs[0] if err_docs else err_description + + return f"Subtensor returned `{err_name}({err_type})` error. This means: `{err_description}`." + + +# Subnet 24 uses this function +def is_valid_ss58_address(address: str) -> bool: + """ + Checks if the given address is a valid ss58 address. + + Args: + address(str): The address to check. + + Returns: + True if the address is a valid ss58 address for Bittensor, False otherwise. + """ + try: + return ss58.is_valid_ss58_address( + address, valid_ss58_format=SS58_FORMAT + ) or ss58.is_valid_ss58_address( + address, valid_ss58_format=42 + ) # Default substrate ss58 format (legacy) + except IndexError: + return False + + +def _is_valid_ed25519_pubkey(public_key: Union[str, bytes]) -> bool: + """ + Checks if the given public_key is a valid ed25519 key. + + Args: + public_key(Union[str, bytes]): The public_key to check. + + Returns: + True if the public_key is a valid ed25519 key, False otherwise. + + """ + try: + if isinstance(public_key, str): + if len(public_key) != 64 and len(public_key) != 66: + raise ValueError("a public_key should be 64 or 66 characters") + elif isinstance(public_key, bytes): + if len(public_key) != 32: + raise ValueError("a public_key should be 32 bytes") + else: + raise ValueError("public_key must be a string or bytes") + + keypair = Keypair(public_key=public_key, ss58_format=SS58_FORMAT) + + ss58_addr = keypair.ss58_address + return ss58_addr is not None + + except (ValueError, IndexError): + return False + + +def is_valid_bittensor_address_or_public_key(address: Union[str, bytes]) -> bool: + """ + Checks if the given address is a valid destination address. + + Args: + address(Union[str, bytes]): The address to check. + + Returns: + True if the address is a valid destination address, False otherwise. + """ + if isinstance(address, str): + # Check if ed25519 + if address.startswith("0x"): + return _is_valid_ed25519_pubkey(address) + else: + # Assume ss58 address + return is_valid_ss58_address(address) + elif isinstance(address, bytes): + # Check if ed25519 + return _is_valid_ed25519_pubkey(address) + else: + # Invalid address type + return False diff --git a/bittensor/utils/axon_utils.py b/bittensor/utils/axon_utils.py new file mode 100644 index 0000000000..3c73c8080d --- /dev/null +++ b/bittensor/utils/axon_utils.py @@ -0,0 +1,58 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from typing import Optional + +ALLOWED_DELTA = 4_000_000_000 # Delta of 4 seconds for nonce validation +NANOSECONDS_IN_SECOND = 1_000_000_000 + + +def allowed_nonce_window_ns(current_time_ns: int, synapse_timeout: Optional[float]): + """ + Calculates the allowed window for a nonce in nanoseconds. + + Args: + current_time_ns (int): The current time in nanoseconds. + synapse_timeout (Optional[float]): The optional timeout for the synapse in seconds. If None, it defaults to 0. + + Returns: + int: The allowed nonce window in nanoseconds. + """ + synapse_timeout_ns = (synapse_timeout or 0) * NANOSECONDS_IN_SECOND + allowed_window_ns = current_time_ns - ALLOWED_DELTA - synapse_timeout_ns + return allowed_window_ns + + +def calculate_diff_seconds( + current_time: int, synapse_timeout: Optional[float], synapse_nonce: int +): + """ + Calculates the difference in seconds between the current time and the synapse nonce, + and also returns the allowed delta in seconds. + + Args: + current_time (int): The current time in nanoseconds. + synapse_timeout (Optional[float]): The optional timeout for the synapse in seconds. + synapse_nonce (int): The nonce value for the synapse in nanoseconds. + + Returns: + tuple: A tuple containing the difference in seconds (float) and the allowed delta in seconds (float). + """ + synapse_timeout_ns = (synapse_timeout or 0) * NANOSECONDS_IN_SECOND + diff_seconds = (current_time - synapse_nonce) / NANOSECONDS_IN_SECOND + allowed_delta_seconds = (ALLOWED_DELTA + synapse_timeout_ns) / NANOSECONDS_IN_SECOND + return diff_seconds, allowed_delta_seconds diff --git a/bittensor/utils/balance.py b/bittensor/utils/balance.py new file mode 100644 index 0000000000..016db373a4 --- /dev/null +++ b/bittensor/utils/balance.py @@ -0,0 +1,268 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from typing import Union + +from bittensor.core import settings + + +class Balance: + """ + Represents the bittensor balance of the wallet, stored as rao (int). + This class provides a way to interact with balances in two different units: rao and tao. + It provides methods to convert between these units, as well as to perform arithmetic and comparison operations. + + Attributes: + unit (str): A string representing the symbol for the tao unit. + rao_unit (str): A string representing the symbol for the rao unit. + rao (int): An integer that stores the balance in rao units. + tao (float): A float property that gives the balance in tao units. + """ + + unit: str = settings.TAO_SYMBOL # This is the tao unit + rao_unit: str = settings.RAO_SYMBOL # This is the rao unit + rao: int + tao: float + + def __init__(self, balance: Union[int, float]): + """ + Initialize a Balance object. If balance is an int, it's assumed to be in rao. + If balance is a float, it's assumed to be in tao. + + Args: + balance: The initial balance, in either rao (if an int) or tao (if a float). + """ + if isinstance(balance, int): + self.rao = balance + elif isinstance(balance, float): + # Assume tao value for the float + self.rao = int(balance * pow(10, 9)) + else: + raise TypeError("balance must be an int (rao) or a float (tao)") + + @property + def tao(self): + return self.rao / pow(10, 9) + + def __int__(self): + """Convert the Balance object to an int. The resulting value is in rao.""" + return self.rao + + def __float__(self): + """Convert the Balance object to a float. The resulting value is in tao.""" + return self.tao + + def __str__(self): + """Returns the Balance object as a string in the format "symbolvalue", where the value is in tao.""" + return f"{self.unit}{float(self.tao):,.9f}" + + def __rich__(self): + int_tao, fract_tao = format(float(self.tao), "f").split(".") + return f"[green]{self.unit}[/green][green]{int_tao}[/green][green].[/green][dim green]{fract_tao}[/dim green]" + + def __str_rao__(self): + return f"{self.rao_unit}{int(self.rao)}" + + def __rich_rao__(self): + return f"[green]{self.rao_unit}{int(self.rao)}[/green]" + + def __repr__(self): + return self.__str__() + + def __eq__(self, other: Union[int, float, "Balance"]): + if other is None: + return False + + if hasattr(other, "rao"): + return self.rao == other.rao + else: + try: + # Attempt to cast to int from rao + other_rao = int(other) + return self.rao == other_rao + except (TypeError, ValueError): + raise NotImplementedError("Unsupported type") + + def __ne__(self, other: Union[int, float, "Balance"]): + return not self == other + + def __gt__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return self.rao > other.rao + else: + try: + # Attempt to cast to int from rao + other_rao = int(other) + return self.rao > other_rao + except ValueError: + raise NotImplementedError("Unsupported type") + + def __lt__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return self.rao < other.rao + else: + try: + # Attempt to cast to int from rao + other_rao = int(other) + return self.rao < other_rao + except ValueError: + raise NotImplementedError("Unsupported type") + + def __le__(self, other: Union[int, float, "Balance"]): + try: + return self < other or self == other + except TypeError: + raise NotImplementedError("Unsupported type") + + def __ge__(self, other: Union[int, float, "Balance"]): + try: + return self > other or self == other + except TypeError: + raise NotImplementedError("Unsupported type") + + def __add__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(self.rao + other.rao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(self.rao + other)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __radd__(self, other: Union[int, float, "Balance"]): + try: + return self + other + except TypeError: + raise NotImplementedError("Unsupported type") + + def __sub__(self, other: Union[int, float, "Balance"]): + try: + return self + -other + except TypeError: + raise NotImplementedError("Unsupported type") + + def __rsub__(self, other: Union[int, float, "Balance"]): + try: + return -self + other + except TypeError: + raise NotImplementedError("Unsupported type") + + def __mul__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(self.rao * other.rao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(self.rao * other)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __rmul__(self, other: Union[int, float, "Balance"]): + return self * other + + def __truediv__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(self.rao / other.rao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(self.rao / other)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __rtruediv__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(other.rao / self.rao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(other / self.rao)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __floordiv__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(self.tao // other.tao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(self.rao // other)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __rfloordiv__(self, other: Union[int, float, "Balance"]): + if hasattr(other, "rao"): + return Balance.from_rao(int(other.rao // self.rao)) + else: + try: + # Attempt to cast to int from rao + return Balance.from_rao(int(other // self.rao)) + except (ValueError, TypeError): + raise NotImplementedError("Unsupported type") + + def __nonzero__(self) -> bool: + return bool(self.rao) + + def __neg__(self): + return Balance.from_rao(-self.rao) + + def __pos__(self): + return Balance.from_rao(self.rao) + + def __abs__(self): + return Balance.from_rao(abs(self.rao)) + + @staticmethod + def from_float(amount: float): + """ + Given tao, return :func:`Balance` object with rao(``int``) and tao(``float``), where rao = int(tao*pow(10,9)) + Args: + amount (float): The amount in tao. + + Returns: + A Balance object representing the given amount. + """ + rao = int(amount * pow(10, 9)) + return Balance(rao) + + @staticmethod + def from_tao(amount: float): + """ + Given tao, return Balance object with rao(``int``) and tao(``float``), where rao = int(tao*pow(10,9)) + + Args: + amount (float): The amount in tao. + + Returns: + A Balance object representing the given amount. + """ + rao = int(amount * pow(10, 9)) + return Balance(rao) + + @staticmethod + def from_rao(amount: int): + """ + Given rao, return Balance object with rao(``int``) and tao(``float``), where rao = int(tao*pow(10,9)) + + Args: + amount (int): The amount in rao. + + Returns: + A Balance object representing the given amount. + """ + return Balance(amount) diff --git a/bittensor/utils/btlogging/__init__.py b/bittensor/utils/btlogging/__init__.py new file mode 100644 index 0000000000..a5e6d2518c --- /dev/null +++ b/bittensor/utils/btlogging/__init__.py @@ -0,0 +1,27 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +btlogging sub-package standardized logging for Bittensor. + +This module provides logging functionality for the Bittensor package. It includes custom loggers, handlers, and formatters to ensure consistent logging throughout the project. +""" + +from .loggingmachine import LoggingMachine + + +logging = LoggingMachine(LoggingMachine.config()) diff --git a/bittensor/utils/btlogging/defines.py b/bittensor/utils/btlogging/defines.py new file mode 100644 index 0000000000..9e1dada25b --- /dev/null +++ b/bittensor/utils/btlogging/defines.py @@ -0,0 +1,28 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +"""Btlogging constant definition module.""" + +BASE_LOG_FORMAT = "%(asctime)s | %(levelname)s | %(message)s" +TRACE_LOG_FORMAT = ( + f"%(asctime)s | %(levelname)s | %(name)s:%(filename)s:%(lineno)s | %(message)s" +) +DATE_FORMAT = "%Y-%m-%d %H:%M:%S" +BITTENSOR_LOGGER_NAME = "bittensor" +DEFAULT_LOG_FILE_NAME = "bittensor.log" +DEFAULT_MAX_ROTATING_LOG_FILE_SIZE = 25 * 1024 * 1024 +DEFAULT_LOG_BACKUP_COUNT = 10 diff --git a/bittensor/utils/btlogging/format.py b/bittensor/utils/btlogging/format.py new file mode 100644 index 0000000000..1aa505c82c --- /dev/null +++ b/bittensor/utils/btlogging/format.py @@ -0,0 +1,222 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +btlogging.format module + +This module defines custom logging formatters for the Bittensor project. +""" + +import logging +import time +from typing import Optional +from colorama import init, Fore, Back, Style + +init(autoreset=True) + +TRACE_LEVEL_NUM: int = 5 +SUCCESS_LEVEL_NUM: int = 21 + + +def _trace(self, message: str, *args, **kws): + if self.isEnabledFor(TRACE_LEVEL_NUM): + self._log(TRACE_LEVEL_NUM, message, args, **kws) + + +def _success(self, message: str, *args, **kws): + if self.isEnabledFor(SUCCESS_LEVEL_NUM): + self._log(SUCCESS_LEVEL_NUM, message, args, **kws) + + +logging.SUCCESS = SUCCESS_LEVEL_NUM +logging.addLevelName(SUCCESS_LEVEL_NUM, "SUCCESS") +logging.Logger.success = _success + +logging.TRACE = TRACE_LEVEL_NUM +logging.addLevelName(TRACE_LEVEL_NUM, "TRACE") +logging.Logger.trace = _trace + +emoji_map: dict[str, str] = { + ":white_heavy_check_mark:": "✅", + ":cross_mark:": "❌", + ":satellite:": "🛰️", +} + + +color_map: dict[str, str] = { + "": Fore.RED, + "": Style.RESET_ALL, + "": Fore.BLUE, + "": Style.RESET_ALL, + "": Fore.GREEN, + "": Style.RESET_ALL, +} + + +log_level_color_prefix: dict[int, str] = { + logging.NOTSET: Fore.RESET, + logging.TRACE: Fore.MAGENTA, + logging.DEBUG: Fore.BLUE, + logging.INFO: Fore.WHITE, + logging.SUCCESS: Fore.GREEN, + logging.WARNING: Fore.YELLOW, + logging.ERROR: Fore.RED, + logging.CRITICAL: Back.RED, +} + + +LOG_FORMATS: dict[int, str] = { + level: f"{Fore.BLUE}%(asctime)s{Fore.RESET} | {Style.BRIGHT}{color}%(levelname)s\033[0m | %(message)s" + for level, color in log_level_color_prefix.items() +} + +LOG_TRACE_FORMATS: dict[int, str] = { + level: f"{Fore.BLUE}%(asctime)s{Fore.RESET}" + f" | {Style.BRIGHT}{color}%(levelname)s{Fore.RESET}{Back.RESET}{Style.RESET_ALL}" + f" | %(name)s:%(filename)s:%(lineno)s" + f" | %(message)s" + for level, color in log_level_color_prefix.items() +} + +DEFAULT_LOG_FORMAT: str = ( + f"{Fore.BLUE}%(asctime)s{Fore.RESET} | " + f"{Style.BRIGHT}{Fore.WHITE}%(levelname)s{Style.RESET_ALL} | " + f"%(name)s:%(filename)s:%(lineno)s | %(message)s" +) + +DEFAULT_TRACE_FORMAT: str = ( + f"{Fore.BLUE}%(asctime)s{Fore.RESET} | " + f"{Style.BRIGHT}{Fore.WHITE}%(levelname)s{Style.RESET_ALL} | " + f"%(name)s:%(filename)s:%(lineno)s | %(message)s" +) + + +class BtStreamFormatter(logging.Formatter): + """ + A custom logging formatter for the Bittensor project that overrides the time formatting to include milliseconds, + centers the level name, and applies custom log formats, emojis, and colors. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.trace = False + + def formatTime(self, record, datefmt: Optional[str] = None) -> str: + """ + Override formatTime to add milliseconds. + + Args: + record (logging.LogRecord): The log record. + datefmt (Optional[str]): The date format string. + + Returns: + s (str): The formatted time string with milliseconds. + """ + + created = self.converter(record.created) + if datefmt: + s = time.strftime(datefmt, created) + else: + s = time.strftime("%Y-%m-%d %H:%M:%S", created) + s += f".{int(record.msecs):03d}" + return s + + def format(self, record: "logging.LogRecord") -> str: + """ + Override format to apply custom formatting including emojis and colors. + + This method saves the original format, applies custom formatting based on the log level and trace flag, replaces + text with emojis and colors, and then returns the formatted log record. + + Args: + record (logging.LogRecord): The log record. + + Returns: + result (str): The formatted log record. + """ + + format_orig = self._style._fmt + record.levelname = f"{record.levelname:^16}" + + if record.levelno not in LOG_FORMATS: + self._style._fmt = ( + DEFAULT_TRACE_FORMAT if self.trace else DEFAULT_LOG_FORMAT + ) + else: + if self.trace is True: + self._style._fmt = LOG_TRACE_FORMATS[record.levelno] + else: + self._style._fmt = LOG_FORMATS[record.levelno] + + for text, emoji in emoji_map.items(): + record.msg = record.msg.replace(text, emoji) + # Apply color specifiers + for text, color in color_map.items(): + record.msg = record.msg.replace(text, color) + + result = super().format(record) + self._style._fmt = format_orig + + return result + + def set_trace(self, state: bool = True): + """Change formatter state.""" + self.trace = state + + +class BtFileFormatter(logging.Formatter): + """ + BtFileFormatter + + A custom logging formatter for the Bittensor project that overrides the time formatting to include milliseconds and + centers the level name. + """ + + def formatTime( + self, record: "logging.LogRecord", datefmt: Optional[str] = None + ) -> str: + """ + Override formatTime to add milliseconds. + + Args: + record (logging.LogRecord): The log record. + datefmt (Optional[str]): The date format string. + + Returns: + s (str): The formatted time string with milliseconds. + """ + + created = self.converter(record.created) + if datefmt: + s = time.strftime(datefmt, created) + else: + s = time.strftime("%Y-%m-%d %H:%M:%S", created) + s += f".{int(record.msecs):03d}" + return s + + def format(self, record: "logging.LogRecord") -> str: + """ + Override format to center the level name. + + Args: + record (logging.LogRecord): The log record. + + Returns: + formated record (str): The formatted log record. + """ + record.levelname = f"{record.levelname:^16}" + return super().format(record) diff --git a/bittensor/utils/btlogging/helpers.py b/bittensor/utils/btlogging/helpers.py new file mode 100644 index 0000000000..3fdca4ee04 --- /dev/null +++ b/bittensor/utils/btlogging/helpers.py @@ -0,0 +1,88 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +btlogging.helpers module provides helper functions for the Bittensor logging system. +""" + +import logging +from typing import Generator + + +def all_loggers() -> Generator["logging.Logger", None, None]: + """Generator that yields all logger instances in the application. + + Iterates through the logging root manager's logger dictionary and yields all active `Logger` instances. It skips + placeholders and other types that are not instances of `Logger`. + + Yields: + logger (logging.Logger): An active logger instance. + """ + for logger in logging.root.manager.loggerDict.values(): + if isinstance(logger, logging.PlaceHolder): + continue + # In some versions of Python, the values in loggerDict might be + # LoggerAdapter instances instead of Logger instances. + # We check for Logger instances specifically. + if isinstance(logger, logging.Logger): + yield logger + else: + # If it's not a Logger instance, it could be a LoggerAdapter or + # another form that doesn't directly offer logging methods. + # This branch can be extended to handle such cases as needed. + pass + + +def all_logger_names() -> Generator[str, None, None]: + """ + Generate the names of all active loggers. + + This function iterates through the logging root manager's logger dictionary and yields the names of all active + `Logger` instances. It skips placeholders and other types that are not instances of `Logger`. + + Yields: + name (str): The name of an active logger. + """ + for name, logger in logging.root.manager.loggerDict.items(): + if isinstance(logger, logging.PlaceHolder): + continue + # In some versions of Python, the values in loggerDict might be + # LoggerAdapter instances instead of Logger instances. + # We check for Logger instances specifically. + if isinstance(logger, logging.Logger): + yield name + else: + # If it's not a Logger instance, it could be a LoggerAdapter or + # another form that doesn't directly offer logging methods. + # This branch can be extended to handle such cases as needed. + pass + + +def get_max_logger_name_length() -> int: + """ + Calculate and return the length of the longest logger name. + + This function iterates through all active logger names and determines the length of the longest name. + + Returns: + max_length (int): The length of the longest logger name. + """ + max_length = 0 + for name in all_logger_names(): + if len(name) > max_length: + max_length = len(name) + return max_length diff --git a/bittensor/utils/btlogging/loggingmachine.py b/bittensor/utils/btlogging/loggingmachine.py new file mode 100644 index 0000000000..b2cfb2918e --- /dev/null +++ b/bittensor/utils/btlogging/loggingmachine.py @@ -0,0 +1,534 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +Module provides a logging framework for Bittensor, managing both Bittensor-specific and third-party logging states. +It leverages the StateMachine from the statemachine package to transition between different logging states such as +Default, Debug, Trace, and Disabled. +""" + +import argparse +import atexit +import copy +import logging as stdlogging +import multiprocessing as mp +import os +import sys +from logging import Logger +from logging.handlers import QueueHandler, QueueListener, RotatingFileHandler +from typing import NamedTuple + +from statemachine import State, StateMachine + +from bittensor.core.config import Config +from .defines import ( + BITTENSOR_LOGGER_NAME, + DATE_FORMAT, + DEFAULT_LOG_BACKUP_COUNT, + DEFAULT_LOG_FILE_NAME, + DEFAULT_MAX_ROTATING_LOG_FILE_SIZE, + TRACE_LOG_FORMAT, +) +from .format import BtFileFormatter, BtStreamFormatter +from .helpers import all_loggers + + +def _concat_message(msg="", prefix="", suffix=""): + """Concatenates a message with optional prefix and suffix.""" + msg = f"{f'{prefix} - ' if prefix else ''}{msg}{f' - {suffix}' if suffix else ''}" + return msg + + +class LoggingConfig(NamedTuple): + """Named tuple to hold the logging configuration.""" + + debug: bool + trace: bool + record_log: bool + logging_dir: str + + +class LoggingMachine(StateMachine, Logger): + """Handles logger states for bittensor and 3rd party libraries.""" + + Default = State(initial=True) + Debug = State() + Trace = State() + Disabled = State() + + enable_default = ( + Debug.to(Default) + | Trace.to(Default) + | Disabled.to(Default) + | Default.to(Default) + ) + + enable_trace = ( + Default.to(Trace) | Debug.to(Trace) | Disabled.to(Trace) | Trace.to(Trace) + ) + + enable_debug = ( + Default.to(Debug) | Trace.to(Debug) | Disabled.to(Debug) | Debug.to(Debug) + ) + + disable_trace = Trace.to(Default) + + disable_debug = Debug.to(Default) + + disable_logging = ( + Trace.to(Disabled) + | Debug.to(Disabled) + | Default.to(Disabled) + | Disabled.to(Disabled) + ) + + def __init__(self, config: "Config", name: str = BITTENSOR_LOGGER_NAME): + # basics + super(LoggingMachine, self).__init__() + self._queue = mp.Queue(-1) + self._primary_loggers = {name} + self._config = self._extract_logging_config(config) + + # Formatters + # + # In the future, this may be expanded to a dictionary mapping handler + # types to their respective formatters. + self._stream_formatter = BtStreamFormatter() + self._file_formatter = BtFileFormatter(TRACE_LOG_FORMAT, DATE_FORMAT) + + # start with handlers for the QueueListener. + # + # In the future, we may want to add options to introduce other handlers + # for things like log aggregation by external services. + self._handlers = self._configure_handlers(self._config) + + # configure and start the queue listener + self._listener = self._create_and_start_listener(self._handlers) + + # set up all the loggers + self._logger = self._initialize_bt_logger(name) + self.disable_third_party_loggers() + self._enable_initial_state(self._config) + + def _enable_initial_state(self, config): + """Set correct state action on initializing""" + if config.trace: + self.enable_trace() + elif config.debug: + self.enable_debug() + else: + self.enable_default() + + def _extract_logging_config(self, config: "Config") -> dict: + """Extract btlogging's config from bittensor config + + Args: + config (bittensor.core.config.Config): Bittensor config instance. + + Returns: + (dict): btlogging's config from Bittensor config or Bittensor config. + """ + if hasattr(config, "logging"): + return config.logging + else: + return config + + def _configure_handlers(self, config) -> list[stdlogging.Handler]: + handlers = list() + + # stream handler, a given + stream_handler = stdlogging.StreamHandler(sys.stdout) + stream_handler.setFormatter(self._stream_formatter) + handlers.append(stream_handler) + + # file handler, maybe + if config.record_log and config.logging_dir: + logfile = os.path.abspath( + os.path.join(config.logging_dir, DEFAULT_LOG_FILE_NAME) + ) + file_handler = self._create_file_handler(logfile) + handlers.append(file_handler) + return handlers + + def get_config(self): + return self._config + + def set_config(self, config: "Config"): + """Set config after initialization, if desired. + + Args: + config (bittensor.core.config.Config): Bittensor config instance. + """ + self._config = config + if config.logging_dir and config.record_log: + expanded_dir = os.path.expanduser(config.logging_dir) + logfile = os.path.abspath(os.path.join(expanded_dir, DEFAULT_LOG_FILE_NAME)) + self._enable_file_logging(logfile) + if config.trace: + self.enable_trace() + elif config.debug: + self.enable_debug() + + def _create_and_start_listener(self, handlers): + """ + A listener to receive and publish log records. + + This listener receives records from a queue populated by the main bittensor logger, as well as 3rd party loggers + """ + + listener = QueueListener(self._queue, *handlers, respect_handler_level=True) + listener.start() + atexit.register(listener.stop) + return listener + + def get_queue(self): + """ + Get the queue the QueueListener is publishing from. + + To set up logging in a separate process, a QueueHandler must be added to all the desired loggers. + """ + return self._queue + + def _initialize_bt_logger(self, name: str): + """ + Initialize logging for bittensor. + + Since the initial state is Default, logging level for the module logger is INFO, and all third-party loggers are + silenced. Subsequent state transitions will handle all logger outputs. + """ + logger = stdlogging.getLogger(name) + queue_handler = QueueHandler(self._queue) + logger.addHandler(queue_handler) + return logger + + def _deinitialize_bt_logger(self, name: str): + """Find the logger by name and remove the queue handler associated with it.""" + logger = stdlogging.getLogger(name) + for handler in list(logger.handlers): + if isinstance(handler, QueueHandler): + logger.removeHandler(handler) + return logger + + def _create_file_handler(self, logfile: str): + file_handler = RotatingFileHandler( + logfile, + maxBytes=DEFAULT_MAX_ROTATING_LOG_FILE_SIZE, + backupCount=DEFAULT_LOG_BACKUP_COUNT, + ) + file_handler.setFormatter(self._file_formatter) + file_handler.setLevel(stdlogging.TRACE) + return file_handler + + def register_primary_logger(self, name: str): + """ + Register a logger as primary logger + + This adds a logger to the _primary_loggers set to ensure + it doesn't get disabled when disabling third-party loggers. + A queue handler is also associated with it. + + Args: + name (str): the name for primary logger. + """ + self._primary_loggers.add(name) + self._initialize_bt_logger(name) + + def deregister_primary_logger(self, name: str): + """ + De-registers a primary logger + + This function removes the logger from the _primary_loggers + set and deinitializes its queue handler + + Args: + name (str): the name of primary logger. + """ + self._primary_loggers.remove(name) + self._deinitialize_bt_logger(name) + + def enable_third_party_loggers(self): + """Enables logging for third-party loggers by adding a queue handler to each.""" + for logger in all_loggers(): + if logger.name in self._primary_loggers: + continue + queue_handler = QueueHandler(self._queue) + logger.addHandler(queue_handler) + logger.setLevel(self._logger.level) + + def disable_third_party_loggers(self): + """Disables logging for third-party loggers by removing all their handlers.""" + # remove all handlers + for logger in all_loggers(): + if logger.name in self._primary_loggers: + continue + for handler in logger.handlers: + logger.removeHandler(handler) + + def _enable_file_logging(self, logfile: str): + # preserve idempotency; do not create extra filehandlers + # if one already exists + if any( + [isinstance(handler, RotatingFileHandler) for handler in self._handlers] + ): + return + file_handler = self._create_file_handler(logfile) + self._handlers.append(file_handler) + self._listener.handlers = tuple(self._handlers) + + # state transitions + def before_transition(self, event, state): + """Stops listener after transition.""" + self._listener.stop() + + def after_transition(self, event, state): + """Starts listener after transition.""" + self._listener.start() + + # Default Logging + def before_enable_default(self): + """Logs status before enable Default.""" + self._logger.info(f"Enabling default logging.") + self._logger.setLevel(stdlogging.WARNING) + for logger in all_loggers(): + if logger.name in self._primary_loggers: + continue + logger.setLevel(stdlogging.CRITICAL) + + def after_enable_default(self): + pass + + # Trace + def before_enable_trace(self): + """Logs status before enable Trace.""" + self._logger.info("Enabling trace.") + self._stream_formatter.set_trace(True) + for logger in all_loggers(): + logger.setLevel(stdlogging.TRACE) + + def after_enable_trace(self): + """Logs status after enable Trace.""" + self._logger.info("Trace enabled.") + + def before_disable_trace(self): + """Logs status before disable Trace.""" + self._logger.info(f"Disabling trace.") + self._stream_formatter.set_trace(False) + self.enable_default() + + def after_disable_trace(self): + """Logs status after disable Trace.""" + self._logger.info("Trace disabled.") + + # Debug + def before_enable_debug(self): + """Logs status before enable Debug.""" + self._logger.info("Enabling debug.") + self._stream_formatter.set_trace(True) + for logger in all_loggers(): + logger.setLevel(stdlogging.DEBUG) + + def after_enable_debug(self): + """Logs status after enable Debug.""" + self._logger.info("Debug enabled.") + + def before_disable_debug(self): + """Logs status before disable Debug.""" + self._logger.info("Disabling debug.") + self._stream_formatter.set_trace(False) + self.enable_default() + + def after_disable_debug(self): + """Logs status after disable Debug.""" + self._logger.info("Debug disabled.") + + # Disable Logging + def before_disable_logging(self): + """ + Prepares the logging system for disabling. + + This method performs the following actions: + 1. Logs an informational message indicating that logging is being disabled. + 2. Disables trace mode in the stream formatter. + 3. Sets the logging level to CRITICAL for all loggers. + + This ensures that only critical messages will be logged after this method is called. + """ + self._logger.info("Disabling logging.") + self._stream_formatter.set_trace(False) + + for logger in all_loggers(): + logger.setLevel(stdlogging.CRITICAL) + + # Required API support log commands for API backwards compatibility. + @property + def __trace_on__(self) -> bool: + """ + Checks if the current state is in "Trace" mode. + + Returns: + bool: True if the current state is "Trace", otherwise False. + """ + return self.current_state_value == "Trace" + + def trace(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps trace message with prefix and suffix.""" + msg = _concat_message(msg, prefix, suffix) + self._logger.trace(msg, *args, **kwargs) + + def debug(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps debug message with prefix and suffix.""" + msg = _concat_message(msg, prefix, suffix) + self._logger.debug(msg, *args, **kwargs) + + def info(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps info message with prefix and suffix.""" + msg = _concat_message(msg, prefix, suffix) + self._logger.info(msg, *args, **kwargs) + + def success(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps success message with prefix and suffix.""" + msg = f"{prefix} - {msg} - {suffix}" + self._logger.success(msg, *args, **kwargs) + + def warning(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps warning message with prefix and suffix.""" + msg = f"{prefix} - {msg} - {suffix}" + self._logger.warning(msg, *args, **kwargs) + + def error(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps error message with prefix and suffix.""" + msg = f"{prefix} - {msg} - {suffix}" + self._logger.error(msg, *args, **kwargs) + + def critical(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps critical message with prefix and suffix.""" + msg = f"{prefix} - {msg} - {suffix}" + self._logger.critical(msg, *args, **kwargs) + + def exception(self, msg="", prefix="", suffix="", *args, **kwargs): + """Wraps exception message with prefix and suffix.""" + msg = f"{prefix} - {msg} - {suffix}" + self._logger.exception(msg, *args, **kwargs) + + def on(self): + """Enable default state.""" + self._logger.info("Logging enabled.") + self.enable_default() + + def off(self): + """Disables all states.""" + self.disable_logging() + + def set_debug(self, on: bool = True): + """Sets Debug state.""" + if on and not self.current_state_value == "Debug": + self.enable_debug() + elif not on: + if self.current_state_value == "Debug": + self.disable_debug() + + def set_trace(self, on: bool = True): + """Sets Trace state.""" + if on and not self.current_state_value == "Trace": + self.enable_trace() + elif not on: + if self.current_state_value == "Trace": + self.disable_trace() + + def get_level(self) -> int: + """Returns Logging level.""" + return self._logger.level + + def check_config(self, config: "Config"): + assert config.logging + + def help(self): + pass + + @classmethod + def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): + """Accept specific arguments fro parser""" + prefix_str = "" if prefix is None else prefix + "." + try: + default_logging_debug = os.getenv("BT_LOGGING_DEBUG") or False + default_logging_trace = os.getenv("BT_LOGGING_TRACE") or False + default_logging_record_log = os.getenv("BT_LOGGING_RECORD_LOG") or False + default_logging_logging_dir = os.getenv( + "BT_LOGGING_LOGGING_DIR" + ) or os.path.join("~", ".bittensor", "miners") + parser.add_argument( + "--" + prefix_str + "logging.debug", + action="store_true", + help="""Turn on bittensor debugging information""", + default=default_logging_debug, + ) + parser.add_argument( + "--" + prefix_str + "logging.trace", + action="store_true", + help="""Turn on bittensor trace level information""", + default=default_logging_trace, + ) + parser.add_argument( + "--" + prefix_str + "logging.record_log", + action="store_true", + help="""Turns on logging to file.""", + default=default_logging_record_log, + ) + parser.add_argument( + "--" + prefix_str + "logging.logging_dir", + type=str, + help="Logging default root directory.", + default=default_logging_logging_dir, + ) + except argparse.ArgumentError: + # re-parsing arguments. + pass + + @classmethod + def config(cls) -> "Config": + """Get config from the argument parser. + + Return: + config (bittensor.core.config.Config): config object + """ + parser = argparse.ArgumentParser() + cls.add_args(parser) + return Config(parser, args=[]) + + def __call__( + self, + config: "Config" = None, + debug: bool = None, + trace: bool = None, + record_log: bool = None, + logging_dir: str = None, + ): + if config is not None: + cfg = copy.deepcopy(config) + if debug is not None: + cfg.debug = debug + elif trace is not None: + cfg.trace = trace + if record_log is not None: + cfg.record_log = record_log + if logging_dir is not None: + cfg.logging_dir = logging_dir + else: + cfg = LoggingConfig( + debug=debug, trace=trace, record_log=record_log, logging_dir=logging_dir + ) + self.set_config(cfg) diff --git a/bittensor/utils/deprecated.py b/bittensor/utils/deprecated.py new file mode 100644 index 0000000000..6075a93d8f --- /dev/null +++ b/bittensor/utils/deprecated.py @@ -0,0 +1,150 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +""" +The Bittensor Compatibility Module is designed to ensure seamless integration and functionality with legacy versions of +the Bittensor framework, specifically up to and including version 7.3.0. This module addresses changes and deprecated +features in recent versions, allowing users to maintain compatibility with older systems and projects. +""" + +import importlib +import sys + +from bittensor_wallet.errors import KeyFileError # noqa: F401 +from bittensor_wallet.keyfile import ( # noqa: F401 + serialized_keypair_to_keyfile_data, + deserialize_keypair_from_keyfile_data, + validate_password, + ask_password_to_encrypt, + keyfile_data_is_encrypted_nacl, + keyfile_data_is_encrypted_ansible, + keyfile_data_is_encrypted_legacy, + keyfile_data_is_encrypted, + keyfile_data_encryption_method, + legacy_encrypt_keyfile_data, + encrypt_keyfile_data, + get_coldkey_password_from_environment, + decrypt_keyfile_data, + Keyfile, +) +from bittensor_wallet.wallet import display_mnemonic_msg, Wallet # noqa: F401 +from substrateinterface import Keypair # noqa: F401 + +from bittensor.core import settings +from bittensor.core.axon import Axon +from bittensor.core.chain_data import ( # noqa: F401 + AxonInfo, + NeuronInfo, + NeuronInfoLite, + PrometheusInfo, + DelegateInfo, + StakeInfo, + SubnetInfo, + SubnetHyperparameters, + IPInfo, + ProposalCallData, + ProposalVoteData, +) +from bittensor.core.config import ( # noqa: F401 + InvalidConfigFile, + DefaultConfig, + Config, + T, +) +from bittensor.core.dendrite import Dendrite # noqa: F401 +from bittensor.core.errors import ( # noqa: F401 + BlacklistedException, + ChainConnectionError, + ChainError, + ChainQueryError, + ChainTransactionError, + IdentityError, + InternalServerError, + InvalidRequestNameError, + MetadataError, + NominationError, + NotDelegateError, + NotRegisteredError, + NotVerifiedException, + PostProcessException, + PriorityException, + RegistrationError, + RunException, + StakeError, + SynapseDendriteNoneException, + SynapseParsingError, + TransferError, + UnknownSynapseError, + UnstakeError, +) +from bittensor.core.metagraph import Metagraph +from bittensor.core.settings import BLOCKTIME +from bittensor.core.stream import StreamingSynapse # noqa: F401 +from bittensor.core.subtensor import Subtensor +from bittensor.core.synapse import TerminalInfo, Synapse # noqa: F401 +from bittensor.core.tensor import Tensor # noqa: F401 +from bittensor.core.threadpool import ( # noqa: F401 + PriorityThreadPoolExecutor as PriorityThreadPoolExecutor, +) +from bittensor.utils import ( # noqa: F401 + ss58_to_vec_u8, + version_checking, + strtobool, + get_explorer_url_for_network, + ss58_address_to_bytes, + u16_normalized_float, + u64_normalized_float, + get_hash, +) +from bittensor.utils.balance import Balance as Balance # noqa: F401 +from bittensor.utils.mock.subtensor_mock import MockSubtensor as MockSubtensor # noqa: F401 +from bittensor.utils.subnets import SubnetsAPI # noqa: F401 + +# Backwards compatibility with previous bittensor versions. +axon = Axon +config = Config +dendrite = Dendrite +keyfile = Keyfile +metagraph = Metagraph +wallet = Wallet +subtensor = Subtensor +synapse = Synapse + +__blocktime__ = BLOCKTIME +__network_explorer_map__ = settings.NETWORK_EXPLORER_MAP +__pipaddress__ = settings.PIPADDRESS +__ss58_format__ = settings.SS58_FORMAT +__type_registry__ = settings.TYPE_REGISTRY +__ss58_address_length__ = settings.SS58_ADDRESS_LENGTH + +__networks__ = settings.NETWORKS + +__finney_entrypoint__ = settings.FINNEY_ENTRYPOINT +__finney_test_entrypoint__ = settings.FINNEY_TEST_ENTRYPOINT +__archive_entrypoint__ = settings.ARCHIVE_ENTRYPOINT +__local_entrypoint__ = settings.LOCAL_ENTRYPOINT + +__tao_symbol__ = settings.TAO_SYMBOL +__rao_symbol__ = settings.RAO_SYMBOL + +# Makes the `bittensor.utils.mock` subpackage available as `bittensor.mock` for backwards compatibility. +mock_subpackage = importlib.import_module("bittensor.utils.mock") +sys.modules["bittensor.mock"] = mock_subpackage + +# Makes the `bittensor.core.extrinsics` subpackage available as `bittensor.extrinsics` for backwards compatibility. +extrinsics_subpackage = importlib.import_module("bittensor.core.extrinsics") +sys.modules["bittensor.extrinsics"] = extrinsics_subpackage diff --git a/bittensor/utils/mock/__init__.py b/bittensor/utils/mock/__init__.py new file mode 100644 index 0000000000..218579a153 --- /dev/null +++ b/bittensor/utils/mock/__init__.py @@ -0,0 +1,18 @@ +# The MIT License (MIT) +# Copyright © 2023 Opentensor Technologies Inc + +# 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. + +from .subtensor_mock import MockSubtensor diff --git a/bittensor/utils/mock/subtensor_mock.py b/bittensor/utils/mock/subtensor_mock.py new file mode 100644 index 0000000000..817be08434 --- /dev/null +++ b/bittensor/utils/mock/subtensor_mock.py @@ -0,0 +1,908 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from collections.abc import Mapping +from dataclasses import dataclass +from hashlib import sha256 +from types import SimpleNamespace +from typing import Any, Optional, Union, TypedDict +from unittest.mock import MagicMock + +from bittensor_wallet import Wallet + +from bittensor.core.chain_data import ( + NeuronInfo, + NeuronInfoLite, + PrometheusInfo, + AxonInfo, +) +from bittensor.core.errors import ChainQueryError +from bittensor.core.subtensor import Subtensor +from bittensor.utils import RAOPERTAO, u16_normalized_float +from bittensor.utils.balance import Balance + +# Mock Testing Constant +__GLOBAL_MOCK_STATE__ = {} + + +class AxonServeCallParams(TypedDict): + """Axon serve chain call parameters.""" + + version: int + ip: int + port: int + ip_type: int + netuid: int + + +class PrometheusServeCallParams(TypedDict): + """Prometheus serve chain call parameters.""" + + version: int + ip: int + port: int + ip_type: int + netuid: int + + +BlockNumber = int + + +class InfoDict(Mapping): + @classmethod + def default(cls): + raise NotImplementedError + + def __getitem__(self, key): + return getattr(self, key) + + def __setitem__(self, key, value): + return setattr(self, key, value) + + def __iter__(self): + return iter(self.__dict__) + + def __len__(self): + return len(self.__dict__) + + +@dataclass +class AxonInfoDict(InfoDict): + block: int + version: int + ip: int # integer representation of ip address + port: int + ip_type: int + protocol: int + placeholder1: int # placeholder for future use + placeholder2: int + + @classmethod + def default(cls): + return cls( + block=0, + version=0, + ip=0, + port=0, + ip_type=0, + protocol=0, + placeholder1=0, + placeholder2=0, + ) + + +@dataclass +class PrometheusInfoDict(InfoDict): + block: int + version: int + ip: int # integer representation of ip address + port: int + ip_type: int + + @classmethod + def default(cls): + return cls(block=0, version=0, ip=0, port=0, ip_type=0) + + +@dataclass +class MockSubtensorValue: + value: Optional[Any] + + +class MockMapResult: + records: Optional[list[tuple[MockSubtensorValue, MockSubtensorValue]]] + + def __init__( + self, + records: Optional[ + list[tuple[Union[Any, MockSubtensorValue], Union[Any, MockSubtensorValue]]] + ] = None, + ): + _records = [ + ( + ( + MockSubtensorValue(value=record[0]), + MockSubtensorValue(value=record[1]), + ) + # Make sure record is a tuple of MockSubtensorValue (dict with value attr) + if not ( + isinstance(record, tuple) + and all( + isinstance(item, dict) and hasattr(item, "value") + for item in record + ) + ) + else record + ) + for record in records + ] + + self.records = _records + + def __iter__(self): + return iter(self.records) + + +class MockSystemState(TypedDict): + Account: dict[str, dict[int, int]] # address -> block -> balance + + +class MockSubtensorState(TypedDict): + Rho: dict[int, dict[BlockNumber, int]] # netuid -> block -> rho + Kappa: dict[int, dict[BlockNumber, int]] # netuid -> block -> kappa + Difficulty: dict[int, dict[BlockNumber, int]] # netuid -> block -> difficulty + ImmunityPeriod: dict[ + int, dict[BlockNumber, int] + ] # netuid -> block -> immunity_period + ValidatorBatchSize: dict[ + int, dict[BlockNumber, int] + ] # netuid -> block -> validator_batch_size + Active: dict[int, dict[BlockNumber, bool]] # (netuid, uid), block -> active + Stake: dict[str, dict[str, dict[int, int]]] # (hotkey, coldkey) -> block -> stake + + Delegates: dict[str, dict[int, float]] # address -> block -> delegate_take + + NetworksAdded: dict[int, dict[BlockNumber, bool]] # netuid -> block -> added + + +class MockChainState(TypedDict): + System: MockSystemState + SubtensorModule: MockSubtensorState + + +class MockSubtensor(Subtensor): + """ + A Mock Subtensor class for running tests. + This should mock only methods that make queries to the chain. + e.g. We mock `Subtensor.query_subtensor` instead of all query methods. + + This class will also store a local (mock) state of the chain. + """ + + chain_state: MockChainState + block_number: int + + @classmethod + def reset(cls) -> None: + __GLOBAL_MOCK_STATE__.clear() + + _ = cls() + + def setup(self) -> None: + if not hasattr(self, "chain_state") or getattr(self, "chain_state") is None: + self.chain_state = { + "System": {"Account": {}}, + "Balances": {"ExistentialDeposit": {0: 500}}, + "SubtensorModule": { + "NetworksAdded": {}, + "Rho": {}, + "Kappa": {}, + "Difficulty": {}, + "ImmunityPeriod": {}, + "ValidatorBatchSize": {}, + "ValidatorSequenceLength": {}, + "ValidatorEpochsPerReset": {}, + "ValidatorEpochLength": {}, + "MaxAllowedValidators": {}, + "MinAllowedWeights": {}, + "MaxWeightLimit": {}, + "SynergyScalingLawPower": {}, + "ScalingLawPower": {}, + "SubnetworkN": {}, + "MaxAllowedUids": {}, + "NetworkModality": {}, + "BlocksSinceLastStep": {}, + "Tempo": {}, + "NetworkConnect": {}, + "EmissionValues": {}, + "Burn": {}, + "Active": {}, + "Uids": {}, + "Keys": {}, + "Owner": {}, + "IsNetworkMember": {}, + "LastUpdate": {}, + "Rank": {}, + "Emission": {}, + "Incentive": {}, + "Consensus": {}, + "Trust": {}, + "ValidatorTrust": {}, + "Dividends": {}, + "PruningScores": {}, + "ValidatorPermit": {}, + "Weights": {}, + "Bonds": {}, + "Stake": {}, + "TotalStake": {0: 0}, + "TotalIssuance": {0: 0}, + "TotalHotkeyStake": {}, + "TotalColdkeyStake": {}, + "TxRateLimit": {0: 0}, # No limit + "Delegates": {}, + "Axons": {}, + "Prometheus": {}, + "SubnetOwner": {}, + "Commits": {}, + "AdjustmentAlpha": {}, + "BondsMovingAverage": {}, + }, + } + + self.block_number = 0 + + self.network = "mock" + self.chain_endpoint = "ws://mock_endpoint.bt" + self.substrate = MagicMock() + + def __init__(self, *args, **kwargs) -> None: + super().__init__() + self.__dict__ = __GLOBAL_MOCK_STATE__ + + if not hasattr(self, "chain_state") or getattr(self, "chain_state") is None: + self.setup() + + def get_block_hash(self, block_id: int) -> str: + return "0x" + sha256(str(block_id).encode()).hexdigest()[:64] + + def create_subnet(self, netuid: int) -> None: + subtensor_state = self.chain_state["SubtensorModule"] + if netuid not in subtensor_state["NetworksAdded"]: + # Per Subnet + subtensor_state["Rho"][netuid] = {} + subtensor_state["Rho"][netuid][0] = 10 + subtensor_state["Kappa"][netuid] = {} + subtensor_state["Kappa"][netuid][0] = 32_767 + subtensor_state["Difficulty"][netuid] = {} + subtensor_state["Difficulty"][netuid][0] = 10_000_000 + subtensor_state["ImmunityPeriod"][netuid] = {} + subtensor_state["ImmunityPeriod"][netuid][0] = 4096 + subtensor_state["ValidatorBatchSize"][netuid] = {} + subtensor_state["ValidatorBatchSize"][netuid][0] = 32 + subtensor_state["ValidatorSequenceLength"][netuid] = {} + subtensor_state["ValidatorSequenceLength"][netuid][0] = 256 + subtensor_state["ValidatorEpochsPerReset"][netuid] = {} + subtensor_state["ValidatorEpochsPerReset"][netuid][0] = 60 + subtensor_state["ValidatorEpochLength"][netuid] = {} + subtensor_state["ValidatorEpochLength"][netuid][0] = 100 + subtensor_state["MaxAllowedValidators"][netuid] = {} + subtensor_state["MaxAllowedValidators"][netuid][0] = 128 + subtensor_state["MinAllowedWeights"][netuid] = {} + subtensor_state["MinAllowedWeights"][netuid][0] = 1024 + subtensor_state["MaxWeightLimit"][netuid] = {} + subtensor_state["MaxWeightLimit"][netuid][0] = 1_000 + subtensor_state["SynergyScalingLawPower"][netuid] = {} + subtensor_state["SynergyScalingLawPower"][netuid][0] = 50 + subtensor_state["ScalingLawPower"][netuid] = {} + subtensor_state["ScalingLawPower"][netuid][0] = 50 + subtensor_state["SubnetworkN"][netuid] = {} + subtensor_state["SubnetworkN"][netuid][0] = 0 + subtensor_state["MaxAllowedUids"][netuid] = {} + subtensor_state["MaxAllowedUids"][netuid][0] = 4096 + subtensor_state["NetworkModality"][netuid] = {} + subtensor_state["NetworkModality"][netuid][0] = 0 + subtensor_state["BlocksSinceLastStep"][netuid] = {} + subtensor_state["BlocksSinceLastStep"][netuid][0] = 0 + subtensor_state["Tempo"][netuid] = {} + subtensor_state["Tempo"][netuid][0] = 99 + + # subtensor_state['NetworkConnect'][netuid] = {} + # subtensor_state['NetworkConnect'][netuid][0] = {} + subtensor_state["EmissionValues"][netuid] = {} + subtensor_state["EmissionValues"][netuid][0] = 0 + subtensor_state["Burn"][netuid] = {} + subtensor_state["Burn"][netuid][0] = 0 + subtensor_state["Commits"][netuid] = {} + + # Per-UID/Hotkey + + subtensor_state["Uids"][netuid] = {} + subtensor_state["Keys"][netuid] = {} + subtensor_state["Owner"][netuid] = {} + + subtensor_state["LastUpdate"][netuid] = {} + subtensor_state["Active"][netuid] = {} + subtensor_state["Rank"][netuid] = {} + subtensor_state["Emission"][netuid] = {} + subtensor_state["Incentive"][netuid] = {} + subtensor_state["Consensus"][netuid] = {} + subtensor_state["Trust"][netuid] = {} + subtensor_state["ValidatorTrust"][netuid] = {} + subtensor_state["Dividends"][netuid] = {} + subtensor_state["PruningScores"][netuid] = {} + subtensor_state["PruningScores"][netuid][0] = {} + subtensor_state["ValidatorPermit"][netuid] = {} + + subtensor_state["Weights"][netuid] = {} + subtensor_state["Bonds"][netuid] = {} + + subtensor_state["Axons"][netuid] = {} + subtensor_state["Prometheus"][netuid] = {} + + subtensor_state["NetworksAdded"][netuid] = {} + subtensor_state["NetworksAdded"][netuid][0] = True + + subtensor_state["AdjustmentAlpha"][netuid] = {} + subtensor_state["AdjustmentAlpha"][netuid][0] = 1000 + + subtensor_state["BondsMovingAverage"][netuid] = {} + subtensor_state["BondsMovingAverage"][netuid][0] = 1000 + else: + raise Exception("Subnet already exists") + + def set_difficulty(self, netuid: int, difficulty: int) -> None: + subtensor_state = self.chain_state["SubtensorModule"] + if netuid not in subtensor_state["NetworksAdded"]: + raise Exception("Subnet does not exist") + + subtensor_state["Difficulty"][netuid][self.block_number] = difficulty + + @staticmethod + def _convert_to_balance(balance: Union["Balance", float, int]) -> "Balance": + if isinstance(balance, float): + balance = Balance.from_tao(balance) + + if isinstance(balance, int): + balance = Balance.from_rao(balance) + + return balance + + def force_set_balance( + self, ss58_address: str, balance: Union["Balance", float, int] = Balance(0) + ) -> tuple[bool, Optional[str]]: + """ + Returns: + tuple[bool, Optional[str]]: (success, err_msg) + """ + balance = self._convert_to_balance(balance) + + if ss58_address not in self.chain_state["System"]["Account"]: + self.chain_state["System"]["Account"][ss58_address] = { + "data": {"free": {0: 0}} + } + + old_balance = self.get_balance(ss58_address, self.block_number) + diff = balance.rao - old_balance.rao + + # Update total issuance + self.chain_state["SubtensorModule"]["TotalIssuance"][self.block_number] = ( + self._get_most_recent_storage( + self.chain_state["SubtensorModule"]["TotalIssuance"] + ) + + diff + ) + + self.chain_state["System"]["Account"][ss58_address] = { + "data": {"free": {self.block_number: balance.rao}} + } + + return True, None + + # Alias for force_set_balance + sudo_force_set_balance = force_set_balance + + def do_block_step(self) -> None: + self.block_number += 1 + + # Doesn't do epoch + subtensor_state = self.chain_state["SubtensorModule"] + for subnet in subtensor_state["NetworksAdded"]: + subtensor_state["BlocksSinceLastStep"][subnet][self.block_number] = ( + self._get_most_recent_storage( + subtensor_state["BlocksSinceLastStep"][subnet] + ) + + 1 + ) + + def _handle_type_default(self, name: str, params: list[object]) -> object: + defaults_mapping = { + "TotalStake": 0, + "TotalHotkeyStake": 0, + "TotalColdkeyStake": 0, + "Stake": 0, + } + + return defaults_mapping.get(name, None) + + def commit(self, wallet: "Wallet", netuid: int, data: str) -> None: + uid = self.get_uid_for_hotkey_on_subnet( + hotkey_ss58=wallet.hotkey.ss58_address, + netuid=netuid, + ) + if uid is None: + raise Exception("Neuron not found") + subtensor_state = self.chain_state["SubtensorModule"] + subtensor_state["Commits"][netuid].setdefault(self.block_number, {})[uid] = data + + def get_commitment(self, netuid: int, uid: int, block: Optional[int] = None) -> str: + if block and self.block_number < block: + raise Exception("Cannot query block in the future") + block = block or self.block_number + + subtensor_state = self.chain_state["SubtensorModule"] + return subtensor_state["Commits"][netuid][block][uid] + + def query_subtensor( + self, + name: str, + block: Optional[int] = None, + params: Optional[list[object]] = [], + ) -> MockSubtensorValue: + if block: + if self.block_number < block: + raise Exception("Cannot query block in the future") + + else: + block = self.block_number + + state = self.chain_state["SubtensorModule"][name] + if state is not None: + # Use prefix + if len(params) > 0: + while state is not None and len(params) > 0: + state = state.get(params.pop(0), None) + if state is None: + return SimpleNamespace( + value=self._handle_type_default(name, params) + ) + + # Use block + state_at_block = state.get(block, None) + while state_at_block is None and block > 0: + block -= 1 + state_at_block = state.get(block, None) + if state_at_block is not None: + return SimpleNamespace(value=state_at_block) + + return SimpleNamespace(value=self._handle_type_default(name, params)) + else: + return SimpleNamespace(value=self._handle_type_default(name, params)) + + def query_map_subtensor( + self, + name: str, + block: Optional[int] = None, + params: Optional[list[object]] = [], + ) -> Optional[MockMapResult]: + """ + Note: Double map requires one param + """ + if block: + if self.block_number < block: + raise Exception("Cannot query block in the future") + + else: + block = self.block_number + + state = self.chain_state["SubtensorModule"][name] + if state is not None: + # Use prefix + if len(params) > 0: + while state is not None and len(params) > 0: + state = state.get(params.pop(0), None) + if state is None: + return MockMapResult([]) + + # Check if single map or double map + if len(state.keys()) == 0: + return MockMapResult([]) + + inner = list(state.values())[0] + # Should have at least one key + if len(inner.keys()) == 0: + raise Exception("Invalid state") + + # Check if double map + if isinstance(list(inner.values())[0], dict): + # is double map + raise ChainQueryError("Double map requires one param") + + # Iterate over each key and add value to list, max at block + records = [] + for key in state: + result = self._get_most_recent_storage(state[key], block) + if result is None: + continue # Skip if no result for this key at `block` or earlier + + records.append((key, result)) + + return MockMapResult(records) + else: + return MockMapResult([]) + + def query_constant( + self, module_name: str, constant_name: str, block: Optional[int] = None + ) -> Optional[object]: + if block: + if self.block_number < block: + raise Exception("Cannot query block in the future") + + else: + block = self.block_number + + state = self.chain_state.get(module_name, None) + if state is not None: + if constant_name in state: + state = state[constant_name] + else: + return None + + # Use block + state_at_block = self._get_most_recent_storage(state, block) + if state_at_block is not None: + return SimpleNamespace(value=state_at_block) + + return state_at_block["data"]["free"] # Can be None + else: + return None + + def get_current_block(self) -> int: + return self.block_number + + # ==== Balance RPC methods ==== + + def get_balance(self, address: str, block: int = None) -> "Balance": + if block: + if self.block_number < block: + raise Exception("Cannot query block in the future") + + else: + block = self.block_number + + state = self.chain_state["System"]["Account"] + if state is not None: + if address in state: + state = state[address] + else: + return Balance(0) + + # Use block + balance_state = state["data"]["free"] + state_at_block = self._get_most_recent_storage( + balance_state, block + ) # Can be None + if state_at_block is not None: + bal_as_int = state_at_block + return Balance.from_rao(bal_as_int) + else: + return Balance(0) + else: + return Balance(0) + + # ==== Neuron RPC methods ==== + + def neuron_for_uid( + self, uid: int, netuid: int, block: Optional[int] = None + ) -> Optional[NeuronInfo]: + if uid is None: + return NeuronInfo.get_null_neuron() + + if block: + if self.block_number < block: + raise Exception("Cannot query block in the future") + + else: + block = self.block_number + + if netuid not in self.chain_state["SubtensorModule"]["NetworksAdded"]: + return None + + neuron_info = self._neuron_subnet_exists(uid, netuid, block) + if neuron_info is None: + return None + + else: + return neuron_info + + def neurons(self, netuid: int, block: Optional[int] = None) -> list[NeuronInfo]: + if netuid not in self.chain_state["SubtensorModule"]["NetworksAdded"]: + raise Exception("Subnet does not exist") + + neurons = [] + subnet_n = self._get_most_recent_storage( + self.chain_state["SubtensorModule"]["SubnetworkN"][netuid], block + ) + for uid in range(subnet_n): + neuron_info = self.neuron_for_uid(uid, netuid, block) + if neuron_info is not None: + neurons.append(neuron_info) + + return neurons + + @staticmethod + def _get_most_recent_storage( + storage: dict[BlockNumber, Any], block_number: Optional[int] = None + ) -> Any: + if block_number is None: + items = list(storage.items()) + items.sort(key=lambda x: x[0], reverse=True) + if len(items) == 0: + return None + + return items[0][1] + + else: + while block_number >= 0: + if block_number in storage: + return storage[block_number] + + block_number -= 1 + + return None + + def _get_axon_info( + self, netuid: int, hotkey: str, block: Optional[int] = None + ) -> AxonInfoDict: + # Axons [netuid][hotkey][block_number] + subtensor_state = self.chain_state["SubtensorModule"] + if netuid not in subtensor_state["Axons"]: + return AxonInfoDict.default() + + if hotkey not in subtensor_state["Axons"][netuid]: + return AxonInfoDict.default() + + result = self._get_most_recent_storage( + subtensor_state["Axons"][netuid][hotkey], block + ) + if not result: + return AxonInfoDict.default() + + return result + + def _get_prometheus_info( + self, netuid: int, hotkey: str, block: Optional[int] = None + ) -> PrometheusInfoDict: + subtensor_state = self.chain_state["SubtensorModule"] + if netuid not in subtensor_state["Prometheus"]: + return PrometheusInfoDict.default() + + if hotkey not in subtensor_state["Prometheus"][netuid]: + return PrometheusInfoDict.default() + + result = self._get_most_recent_storage( + subtensor_state["Prometheus"][netuid][hotkey], block + ) + if not result: + return PrometheusInfoDict.default() + + return result + + def _neuron_subnet_exists( + self, uid: int, netuid: int, block: Optional[int] = None + ) -> Optional[NeuronInfo]: + subtensor_state = self.chain_state["SubtensorModule"] + if netuid not in subtensor_state["NetworksAdded"]: + return None + + if self._get_most_recent_storage(subtensor_state["SubnetworkN"][netuid]) <= uid: + return None + + hotkey = self._get_most_recent_storage(subtensor_state["Keys"][netuid][uid]) + if hotkey is None: + return None + + axon_info_ = self._get_axon_info(netuid, hotkey, block) + + prometheus_info = self._get_prometheus_info(netuid, hotkey, block) + + coldkey = self._get_most_recent_storage(subtensor_state["Owner"][hotkey], block) + active = self._get_most_recent_storage( + subtensor_state["Active"][netuid][uid], block + ) + rank = self._get_most_recent_storage( + subtensor_state["Rank"][netuid][uid], block + ) + emission = self._get_most_recent_storage( + subtensor_state["Emission"][netuid][uid], block + ) + incentive = self._get_most_recent_storage( + subtensor_state["Incentive"][netuid][uid], block + ) + consensus = self._get_most_recent_storage( + subtensor_state["Consensus"][netuid][uid], block + ) + trust = self._get_most_recent_storage( + subtensor_state["Trust"][netuid][uid], block + ) + validator_trust = self._get_most_recent_storage( + subtensor_state["ValidatorTrust"][netuid][uid], block + ) + dividends = self._get_most_recent_storage( + subtensor_state["Dividends"][netuid][uid], block + ) + pruning_score = self._get_most_recent_storage( + subtensor_state["PruningScores"][netuid][uid], block + ) + last_update = self._get_most_recent_storage( + subtensor_state["LastUpdate"][netuid][uid], block + ) + validator_permit = self._get_most_recent_storage( + subtensor_state["ValidatorPermit"][netuid][uid], block + ) + + weights = self._get_most_recent_storage( + subtensor_state["Weights"][netuid][uid], block + ) + bonds = self._get_most_recent_storage( + subtensor_state["Bonds"][netuid][uid], block + ) + + stake_dict = { + coldkey: Balance.from_rao( + self._get_most_recent_storage( + subtensor_state["Stake"][hotkey][coldkey], block + ) + ) + for coldkey in subtensor_state["Stake"][hotkey] + } + + stake = sum(stake_dict.values()) + + weights = [[int(weight[0]), int(weight[1])] for weight in weights] + bonds = [[int(bond[0]), int(bond[1])] for bond in bonds] + rank = u16_normalized_float(rank) + emission = emission / RAOPERTAO + incentive = u16_normalized_float(incentive) + consensus = u16_normalized_float(consensus) + trust = u16_normalized_float(trust) + validator_trust = u16_normalized_float(validator_trust) + dividends = u16_normalized_float(dividends) + prometheus_info = PrometheusInfo.fix_decoded_values(prometheus_info) + axon_info_ = AxonInfo.from_neuron_info( + {"hotkey": hotkey, "coldkey": coldkey, "axon_info": axon_info_} + ) + + neuron_info = NeuronInfo( + hotkey=hotkey, + coldkey=coldkey, + uid=uid, + netuid=netuid, + active=active, + rank=rank, + emission=emission, + incentive=incentive, + consensus=consensus, + trust=trust, + validator_trust=validator_trust, + dividends=dividends, + pruning_score=pruning_score, + last_update=last_update, + validator_permit=validator_permit, + stake=stake, + stake_dict=stake_dict, + total_stake=stake, + prometheus_info=prometheus_info, + axon_info=axon_info_, + weights=weights, + bonds=bonds, + is_null=False, + ) + + return neuron_info + + def neurons_lite( + self, netuid: int, block: Optional[int] = None + ) -> list[NeuronInfoLite]: + if netuid not in self.chain_state["SubtensorModule"]["NetworksAdded"]: + raise Exception("Subnet does not exist") + + neurons = [] + subnet_n = self._get_most_recent_storage( + self.chain_state["SubtensorModule"]["SubnetworkN"][netuid] + ) + for uid in range(subnet_n): + neuron_info = self.neuron_for_uid_lite(uid, netuid, block) + if neuron_info is not None: + neurons.append(neuron_info) + + return neurons + + def get_transfer_fee( + self, wallet: "Wallet", dest: str, value: Union["Balance", float, int] + ) -> "Balance": + return Balance(700) + + def do_transfer( + self, + wallet: "Wallet", + dest: str, + transfer_balance: "Balance", + wait_for_inclusion: bool = True, + wait_for_finalization: bool = False, + ) -> tuple[bool, Optional[str], Optional[str]]: + bal = self.get_balance(wallet.coldkeypub.ss58_address) + dest_bal = self.get_balance(dest) + transfer_fee = self.get_transfer_fee(wallet, dest, transfer_balance) + + existential_deposit = self.get_existential_deposit() + + if bal < transfer_balance + existential_deposit + transfer_fee: + raise Exception("Insufficient balance") + + # Remove from the free balance + self.chain_state["System"]["Account"][wallet.coldkeypub.ss58_address]["data"][ + "free" + ][self.block_number] = (bal - transfer_balance - transfer_fee).rao + + # Add to the free balance + if dest not in self.chain_state["System"]["Account"]: + self.chain_state["System"]["Account"][dest] = {"data": {"free": {}}} + + self.chain_state["System"]["Account"][dest]["data"]["free"][ + self.block_number + ] = (dest_bal + transfer_balance).rao + + return True, None, None + + @staticmethod + def min_required_stake(): + """ + As the minimum required stake may change, this method allows us to dynamically + update the amount in the mock without updating the tests + """ + # valid minimum threshold as of 2024/05/01 + return 100_000_000 # RAO + + def do_serve_prometheus( + self, + wallet: "Wallet", + call_params: "PrometheusServeCallParams", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, + ) -> tuple[bool, Optional[str]]: + return True, None + + def do_set_weights( + self, + wallet: "Wallet", + netuid: int, + uids: int, + vals: list[int], + version_key: int, + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, + ) -> tuple[bool, Optional[str]]: + return True, None + + def do_serve_axon( + self, + wallet: "Wallet", + call_params: "AxonServeCallParams", + wait_for_inclusion: bool = False, + wait_for_finalization: bool = True, + ) -> tuple[bool, Optional[str]]: + return True, None diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py new file mode 100644 index 0000000000..4c0c475851 --- /dev/null +++ b/bittensor/utils/networking.py @@ -0,0 +1,199 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +"""Utils for handling local network with ip and ports.""" + +import json +import os +import socket +import urllib +from functools import wraps +from typing import Optional + +import netaddr +import requests + +from bittensor.utils.btlogging import logging + + +def int_to_ip(int_val: int) -> str: + """Maps an integer to a unique ip-string + Args: + int_val (int): + The integer representation of an ip. Must be in the range (0, 3.4028237e+38). + + Returns: + str_val (str): + The string representation of an ip. Of form *.*.*.* for ipv4 or *::*:*:*:* for ipv6 + + Raises: + netaddr.core.AddrFormatError (Exception): Raised when the passed int_vals is not a valid ip int value. + """ + return str(netaddr.IPAddress(int_val)) + + +def ip_to_int(str_val: str) -> int: + """Maps an ip-string to a unique integer. + arg: + str_val (:tyep:`str`, `required): + The string representation of an ip. Of form *.*.*.* for ipv4 or *::*:*:*:* for ipv6 + + Returns: + int_val (:type:`int128`, `required`): + The integer representation of an ip. Must be in the range (0, 3.4028237e+38). + + Raises: + netaddr.core.AddrFormatError (Exception): + Raised when the passed str_val is not a valid ip string value. + """ + return int(netaddr.IPAddress(str_val)) + + +def ip_version(str_val: str) -> int: + """Returns the ip version (IPV4 or IPV6). + arg: + str_val (:tyep:`str`, `required): + The string representation of an ip. Of form *.*.*.* for ipv4 or *::*:*:*:* for ipv6 + + Returns: + int_val (:type:`int128`, `required`): + The ip version (Either 4 or 6 for IPv4/IPv6) + + Raises: + netaddr.core.AddrFormatError (Exception): + Raised when the passed str_val is not a valid ip string value. + """ + return int(netaddr.IPAddress(str_val).version) + + +def ip__str__(ip_type: int, ip_str: str, port: int): + """Return a formatted ip string""" + return "/ipv%i/%s:%i" % (ip_type, ip_str, port) + + +class ExternalIPNotFound(Exception): + """Raised if we cannot attain your external ip from CURL/URLLIB/IPIFY/AWS""" + + +def get_external_ip() -> str: + """Checks CURL/URLLIB/IPIFY/AWS for your external ip. + Returns: + external_ip (:obj:`str` `required`): + Your routers external facing ip as a string. + + Raises: + ExternalIPNotFound (Exception): + Raised if all external ip attempts fail. + """ + # --- Try AWS + try: + external_ip = requests.get("https://checkip.amazonaws.com").text.strip() + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + # --- Try ipconfig. + try: + process = os.popen("curl -s ifconfig.me") + external_ip = process.readline() + process.close() + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + # --- Try ipinfo. + try: + process = os.popen("curl -s https://ipinfo.io") + external_ip = json.loads(process.read())["ip"] + process.close() + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + # --- Try myip.dnsomatic + try: + process = os.popen("curl -s myip.dnsomatic.com") + external_ip = process.readline() + process.close() + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + # --- Try urllib ipv6 + try: + external_ip = urllib.request.urlopen("https://ident.me").read().decode("utf8") + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + # --- Try Wikipedia + try: + external_ip = requests.get("https://www.wikipedia.org").headers["X-Client-IP"] + assert isinstance(ip_to_int(external_ip), int) + return str(external_ip) + except Exception: + pass + + raise ExternalIPNotFound + + +def get_formatted_ws_endpoint_url(endpoint_url: Optional[str]) -> Optional[str]: + """ + Returns a formatted websocket endpoint url. + Note: The port (or lack thereof) is left unchanged + Args: + endpoint_url (Optional[str]): + The endpoint url to format. + Returns: + formatted_endpoint_url (Optional[str]): The formatted endpoint url. In the form of ws:// or wss:// + """ + if endpoint_url is None: + return None + + if endpoint_url[0:6] != "wss://" and endpoint_url[0:5] != "ws://": + endpoint_url = f"ws://{endpoint_url}" + + return endpoint_url + + +def ensure_connected(func): + """Decorator ensuring the function executes with an active substrate connection.""" + + @wraps(func) + def wrapper(self, *args, **kwargs): + """Wrapper function where `self` argument is Subtensor instance with the substrate connection.""" + # Check the socket state before method execution + if ( + # connection was closed correctly + self.substrate.websocket.sock is None + # connection has a broken pipe + or self.substrate.websocket.sock.getsockopt( + socket.SOL_SOCKET, socket.SO_ERROR + ) + != 0 + ): + logging.info("Reconnection substrate...") + self._get_substrate() + # Execute the method if the connection is active or after reconnecting + return func(self, *args, **kwargs) + + return wrapper diff --git a/bittensor/utils/registration.py b/bittensor/utils/registration.py new file mode 100644 index 0000000000..4d0cdb93d6 --- /dev/null +++ b/bittensor/utils/registration.py @@ -0,0 +1,99 @@ +# The MIT License (MIT) +# Copyright © 2024 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 functools +import os +from typing import TYPE_CHECKING + +import numpy + +from bittensor.utils.btlogging import logging + + +def use_torch() -> bool: + """Force the use of torch over numpy for certain operations.""" + return True if os.getenv("USE_TORCH") == "1" else False + + +def legacy_torch_api_compat(func): + """ + Convert function operating on numpy Input&Output to legacy torch Input&Output API if `use_torch()` is True. + + Args: + func (function): Function with numpy Input/Output to be decorated. + + Returns: + decorated (function): Decorated function. + """ + + @functools.wraps(func) + def decorated(*args, **kwargs): + if use_torch(): + # if argument is a Torch tensor, convert it to numpy + args = [ + arg.cpu().numpy() if isinstance(arg, torch.Tensor) else arg + for arg in args + ] + kwargs = { + key: value.cpu().numpy() if isinstance(value, torch.Tensor) else value + for key, value in kwargs.items() + } + ret = func(*args, **kwargs) + if use_torch(): + # if return value is a numpy array, convert it to Torch tensor + if isinstance(ret, numpy.ndarray): + ret = torch.from_numpy(ret) + return ret + + return decorated + + +@functools.cache +def _get_real_torch(): + try: + import torch as _real_torch + except ImportError: + _real_torch = None + return _real_torch + + +def log_no_torch_error(): + logging.error( + "This command requires torch. You can install torch for bittensor" + ' with `pip install bittensor[torch]` or `pip install ".[torch]"`' + " if installing from source, and then run the command with USE_TORCH=1 {command}" + ) + + +class LazyLoadedTorch: + """A lazy-loading proxy for the torch module.""" + + def __bool__(self): + return bool(_get_real_torch()) + + def __getattr__(self, name): + if real_torch := _get_real_torch(): + return getattr(real_torch, name) + else: + log_no_torch_error() + raise ImportError("torch not installed") + + +if TYPE_CHECKING: + import torch +else: + torch = LazyLoadedTorch() diff --git a/bittensor/utils/subnets.py b/bittensor/utils/subnets.py new file mode 100644 index 0000000000..2b42bead98 --- /dev/null +++ b/bittensor/utils/subnets.py @@ -0,0 +1,77 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from abc import ABC, abstractmethod +from typing import Any, Union, Optional, TYPE_CHECKING + +from bittensor.core.axon import Axon +from bittensor.core.dendrite import Dendrite +from bittensor.utils.btlogging import logging + +# For annotation purposes +if TYPE_CHECKING: + from bittensor_wallet import Wallet + from bittensor.core.synapse import Synapse + + +# Community uses this class +class SubnetsAPI(ABC): + """This class is not used within the bittensor package, but is actively used by the community.""" + + def __init__(self, wallet: "Wallet"): + self.wallet = wallet + self.dendrite = Dendrite(wallet=wallet) + + async def __call__(self, *args, **kwargs): + return await self.query_api(*args, **kwargs) + + @abstractmethod + def prepare_synapse(self, *args, **kwargs) -> Any: + """Prepare the synapse-specific payload.""" + + @abstractmethod + def process_responses(self, responses: list[Union["Synapse", Any]]) -> Any: + """Process the responses from the network.""" + + async def query_api( + self, + axons: Union["Axon", list["Axon"]], + deserialize: Optional[bool] = False, + timeout: Optional[int] = 12, + **kwargs, + ) -> Any: + """ + Queries the API nodes of a subnet using the given synapse and bespoke query function. + + Args: + axons (Union[bt.axon, list[bt.axon]]): The list of axon(s) to query. + deserialize (Optional[bool]): Whether to deserialize the responses. Defaults to False. + timeout (Optional[int]): The timeout in seconds for the query. Defaults to 12. + **kwargs: Keyword arguments for the prepare_synapse_fn. + + Returns: + Any: The result of the process_responses_fn. + """ + synapse = self.prepare_synapse(**kwargs) + logging.debug(f"Querying validator axons with synapse {synapse.name}...") + responses = await self.dendrite( + axons=axons, + synapse=synapse, + deserialize=deserialize, + timeout=timeout, + ) + return self.process_responses(responses) diff --git a/bittensor/utils/version.py b/bittensor/utils/version.py new file mode 100644 index 0000000000..1134361ade --- /dev/null +++ b/bittensor/utils/version.py @@ -0,0 +1,134 @@ +# The MIT License (MIT) +# Copyright © 2024 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 time +from pathlib import Path +from typing import Optional + +import requests +from packaging.version import Version + +from bittensor.core.settings import __version__, PIPADDRESS +from bittensor.utils.btlogging import logging + +VERSION_CHECK_THRESHOLD = 86400 + + +class VersionCheckError(Exception): + """Exception raised for errors in the version check process.""" + + +def _get_version_file_path() -> Path: + return Path.home() / ".bittensor" / ".last_known_version" + + +def _get_version_from_file(version_file: Path) -> Optional[str]: + try: + mtime = version_file.stat().st_mtime + logging.debug(f"Found version file, last modified: {mtime}") + diff = time.time() - mtime + + if diff >= VERSION_CHECK_THRESHOLD: + logging.debug("Version file expired") + return None + + return version_file.read_text() + except FileNotFoundError: + logging.debug("No bittensor version file found") + return None + except OSError: + logging.exception("Failed to read version file") + return None + + +def _get_version_from_pypi(timeout: int = 15) -> str: + logging.debug(f"Checking latest Bittensor version at: {PIPADDRESS}") + try: + response = requests.get(PIPADDRESS, timeout=timeout) + latest_version = response.json()["info"]["version"] + return latest_version + except requests.exceptions.RequestException: + logging.exception("Failed to get latest version from pypi") + raise + + +def get_and_save_latest_version(timeout: int = 15) -> str: + """ + Retrieves and saves the latest version of Bittensor. + + Args: + timeout (int): The timeout for the request to PyPI in seconds. Default is ``15``. + + Returns: + str: The latest version of Bittensor. + """ + version_file = _get_version_file_path() + + if last_known_version := _get_version_from_file(version_file): + return last_known_version + + latest_version = _get_version_from_pypi(timeout) + + try: + version_file.write_text(latest_version) + except OSError: + logging.exception("Failed to save latest version to file") + + return latest_version + + +def check_version(timeout: int = 15): + """ + Check if the current version of Bittensor is up-to-date with the latest version on PyPi. + Raises a VersionCheckError if the version check fails. + + Args: + timeout (int): The timeout for the request to PyPI in seconds. Default is ``15``. + """ + + try: + latest_version = get_and_save_latest_version(timeout) + + if Version(latest_version) > Version(__version__): + print( + f"\u001b[33mBittensor Version: Current {__version__}/Latest {latest_version}\n" + f"Please update to the latest version at your earliest convenience. " + "Run the following command to upgrade:\n\n\u001b[0mpython -m pip install --upgrade bittensor" + ) + pass + except Exception as e: + raise VersionCheckError("Version check failed") from e + + +def version_checking(timeout: int = 15): + """Deprecated, kept for backwards compatibility. Use check_version() instead. + + Args: + timeout (int): The timeout for calling :func:``check_version`` function. Default is ``15``. + """ + + from warnings import warn + + warn( + "version_checking() is deprecated, please use check_version() instead", + DeprecationWarning, + ) + + try: + check_version(timeout) + except VersionCheckError: + logging.exception("Version check failed") diff --git a/bittensor/utils/weight_utils.py b/bittensor/utils/weight_utils.py new file mode 100644 index 0000000000..d7c86bcdca --- /dev/null +++ b/bittensor/utils/weight_utils.py @@ -0,0 +1,414 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +"""Conversion for weight between chain representation and np.array or torch.Tensor""" + +import hashlib +import logging +import typing +from typing import Union, Optional + +import numpy as np + +from numpy.typing import NDArray +from scalecodec import U16, ScaleBytes, Vec +from substrateinterface import Keypair + +from bittensor.utils.btlogging import logging +from bittensor.utils.registration import legacy_torch_api_compat, torch, use_torch + +if typing.TYPE_CHECKING: + from bittensor.core.metagraph import Metagraph + from bittensor.core.subtensor import Subtensor + + +U32_MAX = 4294967295 +U16_MAX = 65535 + + +# Uses in `bittensor.utils.weight_utils.process_weights_for_netuid` +@legacy_torch_api_compat +def normalize_max_weight( + x: Union[NDArray[np.float32], "torch.FloatTensor"], limit: float = 0.1 +) -> Union[NDArray[np.float32], "torch.FloatTensor"]: + """Normalizes the tensor x so that sum(x) = 1 and the max value is not greater than the limit. + Args: + x (:obj:`np.float32`): Tensor to be max_value normalized. + limit: float: Max value after normalization. + + Returns: + y (:obj:`np.float32`): Normalized x tensor. + """ + epsilon = 1e-7 # For numerical stability after normalization + + weights = x.copy() + values = np.sort(weights) + + if x.sum() == 0 or x.shape[0] * limit <= 1: + return np.ones_like(x) / x.shape[0] + else: + estimation = values / values.sum() + + if estimation.max() <= limit: + return weights / weights.sum() + + # Find the cumulative sum and sorted tensor + cumsum = np.cumsum(estimation, 0) + + # Determine the index of cutoff + estimation_sum = np.array( + [(len(values) - i - 1) * estimation[i] for i in range(len(values))] + ) + n_values = (estimation / (estimation_sum + cumsum + epsilon) < limit).sum() + + # Determine the cutoff based on the index + cutoff_scale = (limit * cumsum[n_values - 1] - epsilon) / ( + 1 - (limit * (len(estimation) - n_values)) + ) + cutoff = cutoff_scale * values.sum() + + # Applying the cutoff + weights[weights > cutoff] = cutoff + + y = weights / weights.sum() + + return y + + +# Metagraph uses this function. +def convert_weight_uids_and_vals_to_tensor( + n: int, uids: list[int], weights: list[int] +) -> Union[NDArray[np.float32], "torch.FloatTensor"]: + """ + Converts weights and uids from chain representation into a np.array (inverse operation from convert_weights_and_uids_for_emit). + + Args: + n (int): number of neurons on network. + uids (list[int]): Tensor of uids as destinations for passed weights. + weights (list[int]): Tensor of weights. + + Returns: + row_weights (np.float32 or torch.FloatTensor): Converted row weights. + """ + row_weights = ( + torch.zeros([n], dtype=torch.float32) + if use_torch() + else np.zeros([n], dtype=np.float32) + ) + for uid_j, wij in list(zip(uids, weights)): + row_weights[uid_j] = float( + wij + ) # assumes max-upscaled values (w_max = U16_MAX). + row_sum = row_weights.sum() + if row_sum > 0: + row_weights /= row_sum # normalize + return row_weights + + +# Metagraph uses this function. +def convert_root_weight_uids_and_vals_to_tensor( + n: int, uids: list[int], weights: list[int], subnets: list[int] +) -> Union[NDArray[np.float32], "torch.FloatTensor"]: + """Converts root weights and uids from chain representation into a np.array or torch FloatTensor (inverse operation from convert_weights_and_uids_for_emit) + Args: + n (int): number of neurons on network. + uids (list[int]): Tensor of uids as destinations for passed weights. + weights (list[int]): Tensor of weights. + subnets (list[int]): list of subnets on the network. + + Returns: + row_weights (np.float32): Converted row weights. + """ + row_weights = ( + torch.zeros([n], dtype=torch.float32) + if use_torch() + else np.zeros([n], dtype=np.float32) + ) + for uid_j, wij in list(zip(uids, weights)): + if uid_j in subnets: + index_s = subnets.index(uid_j) + row_weights[index_s] = float( + wij + ) # assumes max-upscaled values (w_max = U16_MAX). + else: + logging.warning( + f"Incorrect Subnet uid {uid_j} in Subnets {subnets}. The subnet is unavailable at the moment." + ) + continue + row_sum = row_weights.sum() + if row_sum > 0: + row_weights /= row_sum # normalize + return row_weights + + +# Metagraph uses this function. +def convert_bond_uids_and_vals_to_tensor( + n: int, uids: list[int], bonds: list[int] +) -> Union[NDArray[np.int64], "torch.LongTensor"]: + """Converts bond and uids from chain representation into a np.array. + + Args: + n (int): number of neurons on network. + uids (list[int]): Tensor of uids as destinations for passed bonds. + bonds (list[int]): Tensor of bonds. + + Returns: + row_bonds (np.float32): Converted row bonds. + """ + row_bonds = ( + torch.zeros([n], dtype=torch.int64) + if use_torch() + else np.zeros([n], dtype=np.int64) + ) + for uid_j, bij in list(zip(uids, bonds)): + row_bonds[uid_j] = int(bij) + return row_bonds + + +# This is used by the community via `bittensor.api.extrinsics.set_weights.set_weights_extrinsic` +def convert_weights_and_uids_for_emit( + uids: Union[NDArray[np.int64], "torch.LongTensor"], + weights: Union[NDArray[np.float32], "torch.FloatTensor"], +) -> tuple[list[int], list[int]]: + """Converts weights into integer u32 representation that sum to MAX_INT_WEIGHT. + + Args: + uids (np.int64):Tensor of uids as destinations for passed weights. + weights (np.float32):Tensor of weights. + + Returns: + weight_uids (list[int]): Uids as a list. + weight_vals (list[int]): Weights as a list. + """ + # Checks. + weights = weights.tolist() + uids = uids.tolist() + if min(weights) < 0: + raise ValueError(f"Passed weight is negative cannot exist on chain {weights}") + if min(uids) < 0: + raise ValueError(f"Passed uid is negative cannot exist on chain {uids}") + if len(uids) != len(weights): + raise ValueError( + f"Passed weights and uids must have the same length, got {len(uids)} and {len(weights)}" + ) + if sum(weights) == 0: + return [], [] # Nothing to set on chain. + else: + max_weight = float(max(weights)) + weights = [ + float(value) / max_weight for value in weights + ] # max-upscale values (max_weight = 1). + + weight_vals = [] + weight_uids = [] + for i, (weight_i, uid_i) in enumerate(list(zip(weights, uids))): + uint16_val = round( + float(weight_i) * int(U16_MAX) + ) # convert to int representation. + + # Filter zeros + if uint16_val != 0: # Filter zeros + weight_vals.append(uint16_val) + weight_uids.append(uid_i) + + return weight_uids, weight_vals + + +# The community uses / bittensor does not +def process_weights_for_netuid( + uids: Union[NDArray[np.int64], "torch.Tensor"], + weights: Union[NDArray[np.float32], "torch.Tensor"], + netuid: int, + subtensor: "Subtensor", + metagraph: Optional["Metagraph"] = None, + exclude_quantile: int = 0, +) -> Union[ + tuple["torch.Tensor", "torch.FloatTensor"], + tuple[NDArray[np.int64], NDArray[np.float32]], +]: + """ + Processes weight tensors for a given subnet id using the provided weight and UID arrays, applying constraints and normalization based on the subtensor and metagraph data. This function can handle both NumPy arrays and PyTorch tensors. + + Args: + uids (Union[NDArray[np.int64], "torch.Tensor"]): Array of unique identifiers of the neurons. + weights (Union[NDArray[np.float32], "torch.Tensor"]): Array of weights associated with the user IDs. + netuid (int): The network uid to process weights for. + subtensor (Subtensor): Subtensor instance to access blockchain data. + metagraph (Optional[Metagraph]): Metagraph instance for additional network data. If None, it is fetched from the subtensor using the netuid. + exclude_quantile (int): Quantile threshold for excluding lower weights. Defaults to ``0``. + + Returns: + Union[tuple["torch.Tensor", "torch.FloatTensor"], tuple[NDArray[np.int64], NDArray[np.float32]]]: tuple containing the array of user IDs and the corresponding normalized weights. The data type of the return matches the type of the input weights (NumPy or PyTorch). + """ + + logging.debug("process_weights_for_netuid()") + logging.debug("weights", *weights) + logging.debug("netuid", netuid) + logging.debug("subtensor", subtensor) + logging.debug("metagraph", metagraph) + + # Get latest metagraph from chain if metagraph is None. + if metagraph is None: + metagraph = subtensor.metagraph(netuid) + + # Cast weights to floats. + if use_torch(): + if not isinstance(weights, torch.FloatTensor): + weights = weights.type(torch.float32) + else: + if not isinstance(weights, np.float32): + weights = weights.astype(np.float32) + + # Network configuration parameters from an subtensor. + # These parameters determine the range of acceptable weights for each neuron. + quantile = exclude_quantile / U16_MAX + min_allowed_weights = subtensor.min_allowed_weights(netuid=netuid) + max_weight_limit = subtensor.max_weight_limit(netuid=netuid) + logging.debug("quantile", quantile) + logging.debug("min_allowed_weights", min_allowed_weights) + logging.debug("max_weight_limit", max_weight_limit) + + # Find all non zero weights. + non_zero_weight_idx = ( + torch.argwhere(weights > 0).squeeze(dim=1) + if use_torch() + else np.argwhere(weights > 0).squeeze(axis=1) + ) + non_zero_weight_uids = uids[non_zero_weight_idx] + non_zero_weights = weights[non_zero_weight_idx] + nzw_size = non_zero_weights.numel() if use_torch() else non_zero_weights.size + if nzw_size == 0 or metagraph.n < min_allowed_weights: + logging.warning("No non-zero weights returning all ones.") + final_weights = ( + torch.ones((metagraph.n)).to(metagraph.n) / metagraph.n + if use_torch() + else np.ones((metagraph.n), dtype=np.int64) / metagraph.n + ) + logging.debug("final_weights", final_weights) + final_weights_count = ( + torch.tensor(list(range(len(final_weights)))) + if use_torch() + else np.arange(len(final_weights)) + ) + return ( + (final_weights_count, final_weights) + if use_torch() + else (final_weights_count, final_weights) + ) + + elif nzw_size < min_allowed_weights: + logging.warning( + "No non-zero weights less then min allowed weight, returning all ones." + ) + # ( const ): Should this be np.zeros( ( metagraph.n ) ) to reset everyone to build up weight? + weights = ( + torch.ones((metagraph.n)).to(metagraph.n) * 1e-5 + if use_torch() + else np.ones((metagraph.n), dtype=np.int64) * 1e-5 + ) # creating minimum even non-zero weights + weights[non_zero_weight_idx] += non_zero_weights + logging.debug("final_weights", *weights) + normalized_weights = normalize_max_weight(x=weights, limit=max_weight_limit) + nw_arange = ( + torch.tensor(list(range(len(normalized_weights)))) + if use_torch() + else np.arange(len(normalized_weights)) + ) + return nw_arange, normalized_weights + + logging.debug("non_zero_weights", *non_zero_weights) + + # Compute the exclude quantile and find the weights in the lowest quantile + max_exclude = max(0, len(non_zero_weights) - min_allowed_weights) / len( + non_zero_weights + ) + exclude_quantile = min([quantile, max_exclude]) + lowest_quantile = ( + non_zero_weights.quantile(exclude_quantile) + if use_torch() + else np.quantile(non_zero_weights, exclude_quantile) + ) + logging.debug("max_exclude", max_exclude) + logging.debug("exclude_quantile", exclude_quantile) + logging.debug("lowest_quantile", lowest_quantile) + + # Exclude all weights below the allowed quantile. + non_zero_weight_uids = non_zero_weight_uids[lowest_quantile <= non_zero_weights] + non_zero_weights = non_zero_weights[lowest_quantile <= non_zero_weights] + logging.debug("non_zero_weight_uids", *non_zero_weight_uids) + logging.debug("non_zero_weights", *non_zero_weights) + + # Normalize weights and return. + normalized_weights = normalize_max_weight( + x=non_zero_weights, limit=max_weight_limit + ) + logging.debug("final_weights", normalized_weights) + + return non_zero_weight_uids, normalized_weights + + +def generate_weight_hash( + address: str, + netuid: int, + uids: list[int], + values: list[int], + version_key: int, + salt: list[int], +) -> str: + """ + Generate a valid commit hash from the provided weights. + + Args: + address (str): The account identifier. Wallet ss58_address. + netuid (int): The network unique identifier. + uids (list[int]): The list of UIDs. + salt (list[int]): The salt to add to hash. + values (list[int]): The list of weight values. + version_key (int): The version key. + + Returns: + str: The generated commit hash. + """ + # Encode data using SCALE codec + wallet_address = ScaleBytes(Keypair(ss58_address=address).public_key) + netuid = ScaleBytes(netuid.to_bytes(2, "little")) + + vec_uids = Vec(data=None, sub_type="U16") + vec_uids.value = [U16(ScaleBytes(uid.to_bytes(2, "little"))) for uid in uids] + uids = ScaleBytes(vec_uids.encode().data) + + vec_values = Vec(data=None, sub_type="U16") + vec_values.value = [ + U16(ScaleBytes(value.to_bytes(2, "little"))) for value in values + ] + values = ScaleBytes(vec_values.encode().data) + + version_key = ScaleBytes(version_key.to_bytes(8, "little")) + + vec_salt = Vec(data=None, sub_type="U16") + vec_salt.value = [U16(ScaleBytes(salts.to_bytes(2, "little"))) for salts in salt] + salt = ScaleBytes(vec_salt.encode().data) + + data = wallet_address + netuid + uids + values + salt + version_key + + # Generate Blake2b hash of the data tuple + blake2b_hash = hashlib.blake2b(data.data, digest_size=32) + + # Convert the hash to hex string and add "0x" prefix + commit_hash = "0x" + blake2b_hash.hexdigest() + + return commit_hash diff --git a/contrib/CODE_REVIEW_DOCS.md b/contrib/CODE_REVIEW_DOCS.md new file mode 100644 index 0000000000..9909606a89 --- /dev/null +++ b/contrib/CODE_REVIEW_DOCS.md @@ -0,0 +1,72 @@ +# Code Review +### Conceptual Review + +A review can be a conceptual review, where the reviewer leaves a comment + * `Concept (N)ACK`, meaning "I do (not) agree with the general goal of this pull + request", + * `Approach (N)ACK`, meaning `Concept ACK`, but "I do (not) agree with the + approach of this change". + +A `NACK` needs to include a rationale why the change is not worthwhile. +NACKs without accompanying reasoning may be disregarded. +After conceptual agreement on the change, code review can be provided. A review +begins with `ACK BRANCH_COMMIT`, where `BRANCH_COMMIT` is the top of the PR +branch, followed by a description of how the reviewer did the review. The +following language is used within pull request comments: + + - "I have tested the code", involving change-specific manual testing in + addition to running the unit, functional, or fuzz tests, and in case it is + not obvious how the manual testing was done, it should be described; + - "I have not tested the code, but I have reviewed it and it looks + OK, I agree it can be merged"; + - A "nit" refers to a trivial, often non-blocking issue. + +### Code Review +Project maintainers reserve the right to weigh the opinions of peer reviewers +using common sense judgement and may also weigh based on merit. Reviewers that +have demonstrated a deeper commitment and understanding of the project over time +or who have clear domain expertise may naturally have more weight, as one would +expect in all walks of life. + +Where a patch set affects consensus-critical code, the bar will be much +higher in terms of discussion and peer review requirements, keeping in mind that +mistakes could be very costly to the wider community. This includes refactoring +of consensus-critical code. + +Where a patch set proposes to change the Bittensor consensus, it must have been +discussed extensively on the discord server and other channels, be accompanied by a widely +discussed BIP and have a generally widely perceived technical consensus of being +a worthwhile change based on the judgement of the maintainers. + +### Finding Reviewers + +As most reviewers are themselves developers with their own projects, the review +process can be quite lengthy, and some amount of patience is required. If you find +that you've been waiting for a pull request to be given attention for several +months, there may be a number of reasons for this, some of which you can do something +about: + + - It may be because of a feature freeze due to an upcoming release. During this time, + only bug fixes are taken into consideration. If your pull request is a new feature, + it will not be prioritized until after the release. Wait for the release. + - It may be because the changes you are suggesting do not appeal to people. Rather than + nits and critique, which require effort and means they care enough to spend time on your + contribution, thundering silence is a good sign of widespread (mild) dislike of a given change + (because people don't assume *others* won't actually like the proposal). Don't take + that personally, though! Instead, take another critical look at what you are suggesting + and see if it: changes too much, is too broad, doesn't adhere to the + [developer notes](DEVELOPMENT_WORKFLOW.md), is dangerous or insecure, is messily written, etc. + Identify and address any of the issues you find. Then ask e.g. on IRC if someone could give + their opinion on the concept itself. + - It may be because your code is too complex for all but a few people, and those people + may not have realized your pull request even exists. A great way to find people who + are qualified and care about the code you are touching is the + [Git Blame feature](https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/tracking-changes-in-a-file). Simply + look up who last modified the code you are changing and see if you can find + them and give them a nudge. Don't be incessant about the nudging, though. + - Finally, if all else fails, ask on IRC or elsewhere for someone to give your pull request + a look. If you think you've been waiting for an unreasonably long time (say, + more than a month) for no particular reason (a few lines changed, etc.), + this is totally fine. Try to return the favor when someone else is asking + for feedback on their code, and the universe balances out. + - Remember that the best thing you can do while waiting is give review to others! \ No newline at end of file diff --git a/contrib/CONTRIBUTING.md b/contrib/CONTRIBUTING.md new file mode 100644 index 0000000000..f9f4ed5f34 --- /dev/null +++ b/contrib/CONTRIBUTING.md @@ -0,0 +1,299 @@ +# Contributing to Bittensor + +The following is a set of guidelines for contributing to Bittensor, which are hosted in the [Opentensor Organization](https://github.com/opentensor) on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. + +## Table Of Contents +1. [I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question) +1. [What should I know before I get started?](#what-should-i-know-before-i-get-started) +1. [Getting Started](#getting-started) + 1. [Good First Issue Label](#good-first-issue-label) + 1. [Beginner and Help-wanted Issues Label](#beginner-and-help-wanted-issues-label) +1. [How Can I Contribute?](#how-can-i-contribute) + 1. [Code Contribution General Guideline](#code-contribution-general-guidelines) + 1. [Pull Request Philosophy](#pull-request-philosophy) + 1. [Pull Request Process](#pull-request-process) + 1. [Testing](#testing) + 1. [Addressing Feedback](#addressing-feedback) + 1. [Squashing Commits](#squashing-commits) + 1. [Refactoring](#refactoring) + 1. [Peer Review](#peer-review) + 1. [Reporting Bugs](#reporting-bugs) + 1. [Suggesting Features](#suggesting-enhancements) + + +## I don't want to read this whole thing I just have a question! + +> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below. + +We have an official Discord server where the community chimes in with helpful advice if you have questions. +This is the fastest way to get an answer and the core development team is active on Discord. + +* [Official Bittensor Discord](https://discord.gg/7wvFuPJZgq) + +## What should I know before I get started? +Bittensor is still in the Alpha stages, and as such you will likely run into some problems in deploying your model or installing Bittensor itself. If you run into an issue or end up resolving an issue yourself, feel free to create a pull request with a fix or with a fix to the documentation. The documentation repository can be found [here](https://github.com/opentensor/docs). + +Additionally, note that the core implementation of Bittensor consists of two separate repositories: [The core Bittensor code](https://github.com/opentensor/bittensor) and the Bittensor Blockchain [subtensor](https://github.com/opentensor/subtensor). + +Supplemental repository for the Bittensor subnet template can be found [here](https://github.com/opentensor/bittensor-subnet-template). This is a great first place to look for getting your hands dirty and started learning and building on Bittensor. See the subnet links [page](https://github.com/opentensor/bittensor-subnet-template/blob/main/subnet_links.json) for a list of all the repositories for the active registered subnets. + +## Getting Started +New contributors are very welcome and needed. +Reviewing and testing is highly valued and the most effective way you can contribute as a new contributor. It also will teach you much more about the code and process than opening pull requests. + +Before you start contributing, familiarize yourself with the Bittensor Core build system and tests. Refer to the documentation in the repository on how to build Bittensor core and how to run the unit tests, functional tests. + +There are many open issues of varying difficulty waiting to be fixed. If you're looking for somewhere to start contributing, check out the [good first issue](https://github.com/opentensor/bittensor/labels/good%20first%20issue) list or changes that are up for grabs. Some of them might no longer be applicable. So if you are interested, but unsure, you might want to leave a comment on the issue first. Also peruse the [issues](https://github.com/opentensor/bittensor/issues) tab for all open issues. + +### Good First Issue Label +The purpose of the good first issue label is to highlight which issues are suitable for a new contributor without a deep understanding of the codebase. + +However, good first issues can be solved by anyone. If they remain unsolved for a longer time, a frequent contributor might address them. + +You do not need to request permission to start working on an issue. However, you are encouraged to leave a comment if you are planning to work on it. This will help other contributors monitor which issues are actively being addressed and is also an effective way to request assistance if and when you need it. + +### Beginner and Help-wanted Issues Label +You can start by looking through these `beginner` and `help-wanted` issues: + +* [Beginner issues](https://github.com/opentensor/bittensor/labels/beginner) - issues which should only require a few lines of code, and a test or two. +* [Help wanted issues](https://github.com/opentensor/bittensor/labels/help%20wanted) - issues which should be a bit more involved than `beginner` issues. + +## Communication Channels +Most communication about Bittensor development happens on Discord channel. +Here's the link of Discord community. +[Bittensor Discord](https://discord.com/channels/799672011265015819/799672011814862902) + +And also here. +[Bittensor Community Discord](https://discord.com/channels/1120750674595024897/1120799375703162950) + +## How Can I Contribute? + +You can contribute to Bittensor in one of two main ways (as well as many others): +1. [Bug](#reporting-bugs) reporting and fixes +2. New features and Bittensor [enhancements](#suggesting-enhancements) + +> Please follow the Bittensor [style guide](./STYLE.md) regardless of your contribution type. + +Here is a high-level summary: +- Code consistency is crucial; adhere to established programming language conventions. +- Use `ruff format .` to format your Python code; it ensures readability and consistency. +- Write concise Git commit messages; summarize changes in ~50 characters. +- Follow these six commit rules: + - Atomic Commits: Focus on one task or fix per commit. + - Subject and Body Separation: Use a blank line to separate the subject from the body. + - Subject Line Length: Keep it under 50 characters for readability. + - Imperative Mood: Write subject line as if giving a command or instruction. + - Body Text Width: Wrap text manually at 72 characters. + - Body Content: Explain what changed and why, not how. +- Make use of your commit messages to simplify project understanding and maintenance. + +> For clear examples of each of the commit rules, see the style guide's [rules](./STYLE.md#the-six-rules-of-a-great-commit) section. + +### Code Contribution General Guidelines + +> Review the Bittensor [style guide](./STYLE.md) and [development workflow](./DEVELOPMENT_WORKFLOW.md) before contributing. + +If you're looking to contribute to Bittensor but unsure where to start, please join our community [discord](https://discord.gg/bittensor), a developer-friendly Bittensor town square. Start with [#development](https://discord.com/channels/799672011265015819/799678806159392768) and [#bounties](https://discord.com/channels/799672011265015819/1095684873810890883) to see what issues are currently posted. For a greater understanding of Bittensor's usage and development, check the [Bittensor Documentation](https://bittensor.com/docs). + +#### Pull Request Philosophy + +Patchsets and enhancements should always be focused. A pull request could add a feature, fix a bug, or refactor code, but it should not contain a mixture of these. Please also avoid 'super' pull requests which attempt to do too much, are overly large, or overly complex as this makes review difficult. + +Specifically, pull requests must adhere to the following criteria: +- **Must** branch off from `staging`. Make sure that all your PRs are using `staging` branch as a base or will be closed. +- Contain fewer than 50 files. PRs with more than 50 files will be closed. +- Use the specific [template](./.github/pull_request_template.md) appropriate to your contribution. +- If a PR introduces a new feature, it *must* include corresponding tests. +- Other PRs (bug fixes, refactoring, etc.) should ideally also have tests, as they provide proof of concept and prevent regression. +- Categorize your PR properly by using GitHub labels. This aids in the review process by informing reviewers about the type of change at a glance. +- Make sure your code includes adequate comments. These should explain why certain decisions were made and how your changes work. +- If your changes are extensive, consider breaking your PR into smaller, related PRs. This makes your contributions easier to understand and review. +- Be active in the discussion about your PR. Respond promptly to comments and questions to help reviewers understand your changes and speed up the acceptance process. + +Generally, all pull requests must: + + - Have a clear use case, fix a demonstrable bug or serve the greater good of the project (e.g. refactoring for modularisation). + - Be well peer-reviewed. + - Follow code style guidelines. + - Not break the existing test suite. + - Where bugs are fixed, where possible, there should be unit tests demonstrating the bug and also proving the fix. + - Change relevant comments and documentation when behaviour of code changes. + +#### Pull Request Process + +Please follow these steps to have your contribution considered by the maintainers: + +*Before* creating the PR: +1. Read the [development workflow](./DEVELOPMENT_WORKFLOW.md) defined for this repository to understand our workflow. +2. Ensure your PR meets the criteria stated in the 'Pull Request Philosophy' section. +3. Include relevant tests for any fixed bugs or new features as stated in the [testing guide](./TESTING.md). +4. Follow all instructions in [the template](https://github.com/opentensor/bittensor/blob/master/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md) to create the PR. +5. Ensure your commit messages are clear and concise. Include the issue number if applicable. +6. If you have multiple commits, rebase them into a single commit using `git rebase -i`. +7. Explain what your changes do and why you think they should be merged in the PR description consistent with the [style guide](./STYLE.md). + +*After* creating the PR: +1. Verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing after you submit your pull request. +2. Label your PR using GitHub's labeling feature. The labels help categorize the PR and streamline the review process. +3. Document your code with comments that provide a clear understanding of your changes. Explain any non-obvious parts of your code or design decisions you've made. +4. If your PR has extensive changes, consider splitting it into smaller, related PRs. This reduces the cognitive load on the reviewers and speeds up the review process. + +Please be responsive and participate in the discussion on your PR! This aids in clarifying any confusion or concerns and leads to quicker resolution and merging of your PR. + +> Note: If your changes are not ready for merge but you want feedback, create a draft pull request. + +Following these criteria will aid in quicker review and potential merging of your PR. +While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted. + +When you are ready to submit your changes, create a pull request: + +> **Always** follow the [style guide](./STYLE.md) and [development workflow](./DEVELOPMENT_WORKFLOW.md) before submitting pull requests. + +After you submit a pull request, it will be reviewed by the maintainers. They may ask you to make changes. Please respond to any comments and push your changes as a new commit. + +> Note: Be sure to merge the latest from "upstream" before making a pull request: + +```bash +git remote add upstream https://github.com/opentensor/bittensor.git +git fetch upstream +git merge upstream/ +git push origin +``` + +#### Testing +Before making a PR for any code changes, please write adequate testing with unittest and/or pytest if it is warranted. This is **mandatory** for new features and enhancements. See the [testing guide](./TESTING.md) for more complete information. + +You may also like to view the [/tests](https://github.com/opentensor/bittensor/tree/master/tests) for starter examples. + +Here is a quick summary: +- **Running Tests**: Use `pytest` from the root directory of the Bittensor repository to run all tests. To run a specific test file or a specific test within a file, specify it directly (e.g., `pytest tests/test_wallet.py::test_create_new_coldkey`). +- **Writing Tests**: When writing tests, cover both the "happy path" and any potential error conditions. Use the `assert` statement to verify the expected behavior of a function. +- **Mocking**: Use the `unittest.mock` library to mock certain functions or objects when you need to isolate the functionality you're testing. This allows you to control the behavior of these functions or objects during testing. +- **Test Coverage**: Use the `pytest-cov` plugin to measure your test coverage. Aim for high coverage but also ensure your tests are meaningful and accurately represent the conditions under which your code will run. +- **Continuous Integration**: Bittensor uses GitHub Actions for continuous integration. Tests are automatically run every time you push changes to the repository. Check the "Actions" tab of the Bittensor GitHub repository to view the results. + +Remember, testing is crucial for maintaining code health, catching issues early, and facilitating the addition of new features or refactoring of existing code. + +#### Addressing Feedback + +After submitting your pull request, expect comments and reviews from other contributors. You can add more commits to your pull request by committing them locally and pushing to your fork. + +You are expected to reply to any review comments before your pull request is merged. You may update the code or reject the feedback if you do not agree with it, but you should express so in a reply. If there is outstanding feedback and you are not actively working on it, your pull request may be closed. + +#### Squashing Commits + +If your pull request contains fixup commits (commits that change the same line of code repeatedly) or too fine-grained commits, you may be asked to [squash](https://git-scm.com/docs/git-rebase#_interactive_mode) your commits before it will be reviewed. The basic squashing workflow is shown below. + + git checkout your_branch_name + git rebase -i HEAD~n + # n is normally the number of commits in the pull request. + # Set commits (except the one in the first line) from 'pick' to 'squash', save and quit. + # On the next screen, edit/refine commit messages. + # Save and quit. + git push -f # (force push to GitHub) + +Please update the resulting commit message, if needed. It should read as a coherent message. In most cases, this means not just listing the interim commits. + +If your change contains a merge commit, the above workflow may not work and you will need to remove the merge commit first. See the next section for details on how to rebase. + +Please refrain from creating several pull requests for the same change. Use the pull request that is already open (or was created earlier) to amend changes. This preserves the discussion and review that happened earlier for the respective change set. + +The length of time required for peer review is unpredictable and will vary from pull request to pull request. + +#### Refactoring + +Refactoring is a necessary part of any software project's evolution. The following guidelines cover refactoring pull requests for the Bittensor project. + +There are three categories of refactoring: code-only moves, code style fixes, and code refactoring. In general, refactoring pull requests should not mix these three kinds of activities in order to make refactoring pull requests easy to review and uncontroversial. In all cases, refactoring PRs must not change the behaviour of code within the pull request (bugs must be preserved as is). + +Project maintainers aim for a quick turnaround on refactoring pull requests, so where possible keep them short, uncomplex and easy to verify. + +Pull requests that refactor the code should not be made by new contributors. It requires a certain level of experience to know where the code belongs to and to understand the full ramification (including rebase effort of open pull requests). Trivial pull requests or pull requests that refactor the code with no clear benefits may be immediately closed by the maintainers to reduce unnecessary workload on reviewing. + +#### Peer Review + +Anyone may participate in peer review which is expressed by comments in the pull request. Typically reviewers will review the code for obvious errors, as well as test out the patch set and opine on the technical merits of the patch. Project maintainers take into account the peer review when determining if there is consensus to merge a pull request (remember that discussions may have taken place elsewhere, not just on GitHub). The following language is used within pull-request comments: + +- ACK means "I have tested the code and I agree it should be merged"; +- NACK means "I disagree this should be merged", and must be accompanied by sound technical justification. NACKs without accompanying reasoning may be disregarded; +- utACK means "I have not tested the code, but I have reviewed it and it looks OK, I agree it can be merged"; +- Concept ACK means "I agree in the general principle of this pull request"; +- Nit refers to trivial, often non-blocking issues. + +Reviewers should include the commit(s) they have reviewed in their comments. This can be done by copying the commit SHA1 hash. + +A pull request that changes consensus-critical code is considerably more involved than a pull request that adds a feature to the wallet, for example. Such patches must be reviewed and thoroughly tested by several reviewers who are knowledgeable about the changed subsystems. Where new features are proposed, it is helpful for reviewers to try out the patch set on a test network and indicate that they have done so in their review. Project maintainers will take this into consideration when merging changes. + +For a more detailed description of the review process, see the [Code Review Guidelines](CODE_REVIEW_DOCS.md). + +### Reporting Bugs + +This section guides you through submitting a bug report for Bittensor. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. + +When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). + +> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. + +#### Before Submitting A Bug Report + +* **Check the [debugging guide](./DEBUGGING.md).** You might be able to find the cause of the problem and fix things yourself. Most importantly, check if you can reproduce the problem in the latest version of Bittensor by updating to the latest Master branch changes. +* **Check the [Discord Server](https://discord.gg/7wvFuPJZgq)** and ask in [#finney-issues](https://discord.com/channels/799672011265015819/1064247007688007800) or [#subnet-1-issues](https://discord.com/channels/799672011265015819/1096187495667998790). +* **Determine which repository the problem should be reported in**: if it has to do with your ML model, then it's likely [Bittensor](https://github.com/opentensor/bittensor). If you are having problems with your emissions or Blockchain, then it is in [subtensor](https://github.com/opentensor/subtensor) + +#### How Do I Submit A (Good) Bug Report? + +Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). You can find Bittensor's issues [here](https://github.com/opentensor/bittensor/issues). After you've determined which repository ([Bittensor](https://github.com/opentensor/bittensor) or [subtensor](https://github.com/opentensor/subtensor)) your bug is related to, create an issue on that repository. + +Explain the problem and include additional details to help maintainers reproduce the problem: + +* **Use a clear and descriptive title** for the issue to identify the problem. +* **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you started Bittensor, e.g. which command exactly you used in the terminal, or how you started Bittensor otherwise. When listing steps, **don't just say what you did, but explain how you did it**. For example, if you ran Bittensor with a set of custom configs, explain if you used a config file or command line arguments. +* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. +* **Explain which behavior you expected to see instead and why.** +* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +* **If you're reporting that Bittensor crashed**, include a crash report with a stack trace from the operating system. On macOS, the crash report will be available in `Console.app` under "Diagnostic and usage information" > "User diagnostic reports". Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines), a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/), or put it in a [gist](https://gist.github.com/) and provide link to that gist. +* **If the problem is related to performance or memory**, include a CPU profile capture with your report, if you're using a GPU then include a GPU profile capture as well. Look into the [PyTorch Profiler](https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) to look at memory usage of your model. +* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below. + +Provide more context by answering these questions: + +* **Did the problem start happening recently** (e.g. after updating to a new version of Bittensor) or was this always a problem? +* If the problem started happening recently, **can you reproduce the problem in an older version of Bittensor?** +* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens. + +Include details about your configuration and environment: + +* **Which version of Bittensor are you using?** You can get the version by checking for `__version__` in [`bittensor/bittensor/__init.py`](https://github.com/opentensor/bittensor/blob/master/bittensor/__init__.py#L30). This is not sufficient. Also add the commit hash of the branch you are on. +* **What commit hash are you on?** You can get the exact commit hash by checking `git log` and pasting the full commit hash. +* **What's the name and version of the OS you're using**? +* **Are you running Bittensor in a virtual machine?** If so, which VM software are you using and which operating systems and versions are used for the host and the guest? +* **Are you running Bittensor in a dockerized container?** If so, have you made sure that your docker container contains your latest changes and is up to date with Master branch? +* **Are you using [local configuration files](https://opentensor.github.io/getting-started/configuration.html)** `config.yaml` to customize your Bittensor experiment? If so, provide the contents of that config file, preferably in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines) or with a link to a [gist](https://gist.github.com/). + +### Suggesting Enhancements and Features + +This section guides you through submitting an enhancement suggestion for Bittensor, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. + +When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). + +#### Before Submitting An Enhancement Suggestion + +* **Check the [debugging guide](./DEBUGGING.md).** for tips — you might discover that the enhancement is already available. Most importantly, check if you're using the latest version of Bittensor by pulling the latest changes from the Master branch and if you can get the desired behavior by changing [Bittensor's config settings](https://opentensor.github.io/getting-started/configuration.html). +* **Determine which repository the problem should be reported in: if it has to do with your ML model, then it's likely [Bittensor](https://github.com/opentensor/bittensor). If you are having problems with your emissions or Blockchain, then it is in [subtensor](https://github.com/opentensor/subtensor) + +#### How Submit A (Good) Feature Suggestion + +Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository ([Bittensor](https://github.com/opentensor/bittensor) or [subtensor](https://github.com/opentensor/subtensor)) your enhancement suggestion is related to, create an issue on that repository and provide the following information: + +* **Use a clear and descriptive title** for the issue to identify the problem. +* **Provide a step-by-step description of the suggested enhancement** in as many details as possible. +* **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +* **Describe the current behavior** and **explain which behavior you expected to see instead** and why. +* **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of Bittensor which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +* **Explain why this enhancement would be useful** to most Bittensor users. +* **List some other text editors or applications where this enhancement exists.** +* **Specify which version of Bittensor are you using?** You can get the exact version by checking for `__version__` in [`bittensor/bittensor/__init.py`](https://github.com/opentensor/bittensor/blob/master/bittensor/__init__.py#L30). +* **Specify the name and version of the OS you're using.** + +Thank you for considering contributing to Bittensor! Any help is greatly appreciated along this journey to incentivize open and permissionless intelligence. diff --git a/contrib/DEBUGGING.md b/contrib/DEBUGGING.md new file mode 100644 index 0000000000..093e3432bf --- /dev/null +++ b/contrib/DEBUGGING.md @@ -0,0 +1,161 @@ +## Installation + +First, make sure you have Bittensor installed correctly. There are three ways to install Bittensor: + +1. Through the installer: + +```bash +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/opentensor/bittensor/master/scripts/install.sh)" +``` + +2. With pip: + +```bash +pip install bittensor +``` + +3. From source: + +```bash +git clone https://github.com/opentensor/bittensor.git +python3 -m pip install -e bittensor/ +``` + +You can test your installation by running: + +```bash +python3 -c "import bittensor; print(bittensor.__version__)" +``` +## Logging +Make good use of the `bittensor.logging` module. It can be your friend and will help you find things that are otherwise difficult to get visibility on. + +You can enable debug or trace modes by running: +``` +import bittensor +bittensor.trace() # lowest level of granularity, best for figuring out what went wrong. +bittensor.debug() # for most everything else that you don't want to see normally at runtime +``` +at the top of your script or source file to enable more verbose output logs. + +You can also write your own in the code simply: +```python +# Bittensor's wallet maintenance class. +wallet = bittensor.wallet() + +bittensor.logging.debug( f"wallet keypair: {wallet.hotkey}" ) + +... + +# Bittensor's chain state object. +metagraph = bittensor.metagraph(netuid=1) + +bittensor.logging.trace( f"metagraph created! netuid {metagraph.netuid}" ) +``` + + +## Querying the Network + +Ensure you can query the Bittensor network using the Python API. If something is broken with your installation or the chain, this won't work out of the box. Here's an example of how to do this: + +```python +import bittensor +bittensor.trace() + +# Attempt to query through the foundation endpoint. +print(bittensor.prompt("Heraclitus was a ")) +``` + +## Debugging Miners + + +First, try registering and running on a testnet: +```bash +btcli register --netuid --subtensor.chain_endpoint wss://test.finney.opentensor.ai:443 +``` + +If that works, then try to register a miner on mainnet: + +```bash +btcli register --netuid +``` + +See if you can observe your slot specified by UID: + +```bash +btcli overview --netuid +``` + +Here's an example of how to run a pre-configured miner: + +```bash +python3 bittensor/neurons/text_prompting/miners/GPT4ALL/neuron.py --netuid +``` + +## Debugging with the Bittensor Package + +The Bittensor package contains data structures for interacting with the Bittensor ecosystem, writing miners, validators, and querying the network. + +Try to use the Bittensor package to create a wallet, connect to the axon running on slot 10, and send a prompt to this endpoint and see where things are breaking along this typical codepath: + +```python +import bittensor + +# Bittensor's wallet maintenance class. +wallet = bittensor.wallet() + +# Bittensor's chain interface. +subtensor = bittensor.subtensor() + +# Bittensor's chain state object. +metagraph = bittensor.metagraph(netuid=1) + +# Instantiate a Bittensor endpoint. +axon = bittensor.axon(wallet=wallet, metagraph=metagraph) + +# Start servicing messages on the wire. +axon.start() + +# Register this axon on a subnetwork +subtensor.serve_axon(netuid=1, axon=axon) + +# Connect to the axon running on slot 10, use the wallet to sign messages. +dendrite = bittensor.text_prompting(keypair=wallet.hotkey, axon=metagraph.axons[10]) + +# Send a prompt to this endpoint +dendrite.forward(roles=['user'], messages=['Who is Rick James?']) +``` + +> NOTE: It may be helpful to throw in breakpoints such as with `pdb`. +```python +# some code ... +import pdb; pdb.set_trace() # breakpoint! +# more code ... + +``` +This will stop execution at the breakpoint you set and can operate on the stack directly in the terminal. + +## Searching for strings +Use `ag`. It's fast, convenient, and widely available on unix systems. Ag will highlight all occurnaces of a given pattern. + +```bash +apt-get install silversearcher-ag +``` + +Usage: +```bash +$ ag "query_subtensor" + +>>> bittensor/_subtensor/subtensor_mock.py +>>> 165: e.g. We mock `Subtensor.query_subtensor` instead of all query methods. +>>> 536: def query_subtensor( +>>> 1149: curr_total_hotkey_stake = self.query_subtensor( +>>> 1154: curr_total_coldkey_stake = self.query_subtensor( +>>> 1345: return self.query_subtensor(name=name, block=block, params=[netuid]).value +>>> +>>> bittensor/_subtensor/subtensor_impl.py +>>> 902: def query_subtensor( +>>> 1017: return self.query_subtensor("Rho", block, [netuid]).value +... +``` + +Remember, debugging involves a lot of trial and error. Don't be discouraged if things don't work right away. Keep trying different things, and don't hesitate to ask for help if you need it. diff --git a/contrib/DEVELOPMENT_WORKFLOW.md b/contrib/DEVELOPMENT_WORKFLOW.md new file mode 100644 index 0000000000..91e781ffcc --- /dev/null +++ b/contrib/DEVELOPMENT_WORKFLOW.md @@ -0,0 +1,159 @@ +# Bittensor Development Workflow + +## Table of contents + +- [Bittensor Development Workflow](#bittensor-development-workflow) + - [Main Branches](#main-branches) + - [Development Model](#development-model) + - [Feature Branches](#feature-branches) + - [Release Branches](#release-branches) + - [Hotfix Branches](#hotfix-branches) + - [Git Operations](#git-operations) + - [Creating a Feature Branch](#creating-a-feature-branch) + - [Merging Feature Branch into Staging](#merging-feature-branch-into-staging) + - [Creating a Release Branch](#creating-a-release-branch) + - [Finishing a Release Branch](#finishing-a-release-branch) + - [Creating a Hotfix Branch](#creating-a-hotfix-branch) + - [Finishing a Hotfix Branch](#finishing-a-hotfix-branch) + - [Continuous Integration (CI) and Continuous Deployment (CD)](#continuous-integration-ci-and-continuous-deployment-cd) + - [Versioning and Release Notes](#versioning-and-release-notes) + - [Pending Tasks](#pending-tasks) + +## Main Branches + +Bittensor's codebase consists of two main branches: **master** and **staging**. + +**master** +- This is Bittensor's live production branch, which should only be updated by the core development team. This branch is protected, so refrain from pushing or merging into it unless authorized. + +**staging** +- This branch is continuously updated and is where you propose and merge changes. It's essentially Bittensor's active development branch. + +## Development Model + +### Feature Branches + +- Branch off from: `staging` +- Merge back into: `staging` +- Naming convention: `feature//` + +Feature branches are used to develop new features for upcoming or future releases. They exist as long as the feature is in development, but will eventually be merged into `staging` or discarded. Always delete your feature branch after merging to avoid unnecessary clutter. + +### Release Branches + +- Branch off from: `staging` +- Merge back into: `staging` and then `master` +- Naming convention: `release///` + +Release branches support the preparation of a new production release, allowing for minor bug fixes and preparation of metadata (version number, configuration, etc). All new features should be merged into `staging` and wait for the next big release. + +### Hotfix Branches + +General workflow: + +- Branch off from: `master` or `staging` +- Merge back into: `staging` then `master` +- Naming convention: `hotfix///` + +Hotfix branches are meant for quick fixes in the production environment. When a critical bug in a production version must be resolved immediately, a hotfix branch is created. + +## Git Operations + +#### Create a feature branch + +1. Branch from the **staging** branch. + 1. Command: `git checkout -b feature/my-feature staging` + +> Rebase frequently with the updated staging branch so you do not face big conflicts before submitting your pull request. Remember, syncing your changes with other developers could also help you avoid big conflicts. + +#### Merge feature branch into staging + +In other words, integrate your changes into a branch that will be tested and prepared for release. + +1. Switch branch to staging: `git checkout staging` +2. Merging feature branch into staging: `git merge --no-ff feature/my-feature` +3. Pushing changes to staging: `git push origin staging` +4. Delete feature branch: `git branch -d feature/my-feature` (alternatively, this can be navigated on the GitHub web UI) + +This operation is done by Github when merging a PR. + +So, what you have to keep in mind is: +- Open the PR against the `staging` branch. +- After merging a PR you should delete your feature branch. This will be strictly enforced. + +#### Creating a release branch + +1. Create branch from staging: `git checkout -b release/3.4.0/descriptive-message/creator's_name staging` +2. Updating version with major or minor: `./scripts/update_version.sh major|minor` +3. Commit file changes with new version: `git commit -a -m "Updated version to 3.4.0"` + + +#### Finishing a Release Branch + +This involves releasing stable code and generating a new version for bittensor. + +1. Switch branch to master: `git checkout master` +2. Merge release branch into master: `git merge --no-ff release/3.4.0/optional-descriptive-message` +3. Tag changeset: `git tag -a v3.4.0 -m "Releasing v3.4.0: some comment about it"` +4. Push changes to master: `git push origin master` +5. Push tags to origin: `git push origin --tags` + +To keep the changes made in the __release__ branch, we need to merge those back into `staging`: + +- Switch branch to staging: `git checkout staging`. +- Merging release branch into staging: `git merge --no-ff release/3.4.0/optional-descriptive-message` + +This step may well lead to a merge conflict (probably even, since we have changed the version number). If so, fix it and commit. + + +#### Creating a hotfix branch +1. Create branch from master: `git checkout -b hotfix/3.3.4/descriptive-message/creator's-name master` +2. Update patch version: `./scripts/update_version.sh patch` +3. Commit file changes with new version: `git commit -a -m "Updated version to 3.3.4"` +4. Fix the bug and commit the fix: `git commit -m "Fixed critical production issue X"` + +#### Finishing a Hotfix Branch + +Finishing a hotfix branch involves merging the bugfix into both `master` and `staging`. + +1. Switch branch to master: `git checkout master` +2. Merge hotfix into master: `git merge --no-ff hotfix/3.3.4/optional-descriptive-message` +3. Tag new version: `git tag -a v3.3.4 -m "Releasing v3.3.4: descriptive comment about the hotfix"` +4. Push changes to master: `git push origin master` +5. Push tags to origin: `git push origin --tags` +6. Switch branch to staging: `git checkout staging` +7. Merge hotfix into staging: `git merge --no-ff hotfix/3.3.4/descriptive-message/creator's-name` +8. Push changes to origin/staging: `git push origin staging` +9. Delete hotfix branch: `git branch -d hotfix/3.3.4/optional-descriptive-message` + +The one exception to the rule here is that, **when a release branch currently exists, the hotfix changes need to be merged into that release branch, instead of** `staging`. Back-merging the bugfix into the __release__ branch will eventually result in the bugfix being merged into `develop` too, when the release branch is finished. (If work in develop immediately requires this bugfix and cannot wait for the release branch to be finished, you may safely merge the bugfix into develop now already as well.) + +Finally, we remove the temporary branch: + +- `git branch -d hotfix/3.3.4/optional-descriptive-message` +## Continuous Integration (CI) and Continuous Deployment (CD) + +Continuous Integration (CI) is a software development practice where members of a team integrate their work frequently. Each integration is verified by an automated build and test process to detect integration errors as quickly as possible. + +Continuous Deployment (CD) is a software engineering approach in which software functionalities are delivered frequently through automated deployments. + +- **CircleCI job**: Create jobs in CircleCI to automate the merging of staging into master and release version (needed to release code) and building and testing Bittensor (needed to merge PRs). + +## Versioning and Release Notes + +Semantic versioning helps keep track of the different versions of the software. When code is merged into master, generate a new version. + +Release notes provide documentation for each version released to the users, highlighting the new features, improvements, and bug fixes. When merged into master, generate GitHub release and release notes. + +## Pending Tasks + +- Determine if master and staging are different +- Determine what is in staging that is not merged yet + - Document not released developments + - When merged into staging, generate information about what's merged into staging but not released. + - When merged into master, generate GitHub release and release notes. +- CircleCI jobs + - Merge staging into master and release version (needed to release code) + - Build and Test Bittensor (needed to merge PRs) + +This document can be improved as the Bittensor project continues to develop and change. diff --git a/contrib/RELEASE_GUIDELINES.md b/contrib/RELEASE_GUIDELINES.md new file mode 100644 index 0000000000..d6bda7c860 --- /dev/null +++ b/contrib/RELEASE_GUIDELINES.md @@ -0,0 +1,87 @@ +# Release Guidelines + +The release manager in charge can release a Bittensor version using two scripts: + - [../scripts/release/versioning.sh](../scripts/release/versioning.sh) + - [../scripts/release/release.sh](../scripts/release/release.sh) + +The release manager will need the right permissions for: + - github.com + - pypi.org + - hub.docker.com + +If you are new in this role, ask for the proper setup you need to run this process manually. + +## Process of release + +1. Create a branch called `release/VERSION`, having VERSION with the version to release. +1. Make sure twine is installed: `pip install twine` +1. Within the release branch: + 1. Update the version executing:`./scripts/release/versioning.sh --update UPDATE_TYPE` + 1. **UPDATE_TYPE** could be *major*, *minor* or *patch*. + 1. Add release notes to CHANGELOG executing: `./scripts/release/add_notes_changelog.sh -A -V NEW_VERSION -P PREVIOUS_TAG -T GH_ACCESS_TOKEN` + 1. **NEW_VERSION**: e.g.: 3.6.4 + 1. **PREVIOUS_TAG**: e.g.: v3.6.3 + 1. **GH_ACCESS_TOKEN**: A github [personal access token](https://docs.github.com/en/enterprise-server@3.4/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) you need. + +1. Test the release branch and verify that it meets the requirements. +1. After merging the release branch; Run the release script + +## Versioning script usage + +Options: + - -U, --update: type of update. It could be major, minor, patch or rc (release candidate). + - -A, --apply: This specify to apply the release. Without this the versioning will just show a dry run with no changes. + +## Release script usage + +Options: + - -A, --apply: This specify to apply the release. Without this the release will just show a dry run with no changes. + - -T,--github-token: A github personal access token to interact with the Github API. + +### Github token + +Since you need to use a secret when releasing bittensor (github personal access token), I encourage you to use [pass](https://www.passwordstore.org/) or a similar tool that allows you to store the secret safely and not expose it in the history of the machine you use. + +So you can have: +``` +GITHUB_ACCESS_TOKEN=$(pass github/your_personal_token_with_permisions) +``` + +or +``` +GITHUB_ACCESS_TOKEN=$(whatever you need to get the token safely) +``` + +### Executions + +So, executing the script to release a minor version will be: + +``` +# For a dry run +./scripts/release/release.sh +``` + +``` +# Applying changes +./scripts/release/release.sh --apply --github-token $GITHUB_ACCESS_TOKEN` +``` + +## Checking release + +After the execution of the release script we would have generated: + - A new git tag in [github.com](https://github.com/opentensor/bittensor/tags) + - A new github release in [github.com](https://github.com/opentensor/bittensor/releases) + - A new pip package in [pypi.org](https://pypi.org/project/bittensor/#history) + - A new docker image in [hub.docker.com](https://hub.docker.com/r/opentensorfdn/bittensor/tags) + +## After release + +After a Bittensor release we have to +- Update [cubit](https://github.com/opentensor/cubit). + +### Updating cubit + +1. Updating the [Dockerfile](https://github.com/opentensor/cubit/blob/master/docker/Dockerfile) +1. Building its docker image (follow its README instructions) +1. Push it to hub.docker.com + 1. The generated name will be the same but with `-cubit` in its name \ No newline at end of file diff --git a/contrib/STYLE.md b/contrib/STYLE.md new file mode 100644 index 0000000000..7804359d22 --- /dev/null +++ b/contrib/STYLE.md @@ -0,0 +1,350 @@ +# Style Guide + +A project’s long-term success rests (among other things) on its maintainability, and a maintainer has few tools more powerful than his or her project’s log. It’s worth taking the time to learn how to care for one properly. What may be a hassle at first soon becomes habit, and eventually a source of pride and productivity for all involved. + +Most programming languages have well-established conventions as to what constitutes idiomatic style, i.e. naming, formatting and so on. There are variations on these conventions, of course, but most developers agree that picking one and sticking to it is far better than the chaos that ensues when everybody does their own thing. + +# Table of Contents +1. [Code Style](#code-style) +2. [Naming Conventions](#naming-conventions) +3. [Git Commit Style](#git-commit-style) +4. [The Six Rules of a Great Commit](#the-six-rules-of-a-great-commit) + - [1. Atomic Commits](#1-atomic-commits) + - [2. Separate Subject from Body with a Blank Line](#2-separate-subject-from-body-with-a-blank-line) + - [3. Limit the Subject Line to 50 Characters](#3-limit-the-subject-line-to-50-characters) + - [4. Use the Imperative Mood in the Subject Line](#4-use-the-imperative-mood-in-the-subject-line) + - [5. Wrap the Body at 72 Characters](#5-wrap-the-body-at-72-characters) + - [6. Use the Body to Explain What and Why vs. How](#6-use-the-body-to-explain-what-and-why-vs-how) +5. [Tools Worth Mentioning](#tools-worth-mentioning) + - [Using `--fixup`](#using---fixup) + - [Interactive Rebase](#interactive-rebase) +6. [Pull Request and Squashing Commits Caveats](#pull-request-and-squashing-commits-caveats) + + +### Code style + +#### General Style +Python's official style guide is PEP 8, which provides conventions for writing code for the main Python distribution. Here are some key points: + +- `Indentation:` Use 4 spaces per indentation level. + +- `Line Length:` Limit all lines to a maximum of 79 characters. + +- `Blank Lines:` Surround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line. + +- `Imports:` Imports should usually be on separate lines and should be grouped in the following order: + + - Standard library imports. + - Related third party imports. + - Local application/library specific imports. +- `Whitespace:` Avoid extraneous whitespace in the following situations: + + - Immediately inside parentheses, brackets or braces. + - Immediately before a comma, semicolon, or colon. + - Immediately before the open parenthesis that starts the argument list of a function call. +- `Comments:` Comments should be complete sentences and should be used to clarify code and are not a substitute for poorly written code. + +#### For Python + +- `List Comprehensions:` Use list comprehensions for concise and readable creation of lists. + +- `Generators:` Use generators when dealing with large amounts of data to save memory. + +- `Context Managers:` Use context managers (with statement) for resource management. + +- `String Formatting:` Use f-strings for formatting strings in Python 3.6 and above. + +- `Error Handling:` Use exceptions for error handling whenever possible. + +#### More details + +Use [`ruff` to format](https://docs.astral.sh/ruff/formatter/#the-ruff-formatter) your python code before commiting for consistency across such a large pool of contributors. +Black code [style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#code-style) ensures consistent and opinionated code formatting. +Ruff automatically formats your Python code according to the Black style guide, enhancing code readability and maintainability. + +Key Features of ruff & Black code style: + + Consistency: ruff enforces a single, consistent coding style across your project, eliminating style debates and allowing developers to focus on code logic. + + Readability: By applying a standard formatting style, Black improves code readability, making it easier to understand and collaborate on projects. + + Automation: ruff automates the code formatting process, saving time and effort. It eliminates the need for manual formatting and reduces the likelihood of inconsistencies. + +### Naming Conventions + +- `Classes:` Class names should normally use the CapWords Convention. +- `Functions and Variables:` Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. + +- `Constants:` Constants are usually defined on a module level and written in all capital letters with underscores separating words. + +- `Non-public Methods and Instance Variables:` Use a single leading underscore (_). This is a weak "internal use" indicator. + +- `Strongly "private" methods and variables:` Use a double leading underscore (__). This triggers name mangling in Python. + + +### Git commit style + +Here’s a model Git commit message when contributing: +``` +Summarize changes in around 50 characters or less + +More detailed explanatory text, if necessary. Wrap it to about 72 +characters or so. In some contexts, the first line is treated as the +subject of the commit and the rest of the text as the body. The +blank line separating the summary from the body is critical (unless +you omit the body entirely); various tools like `log`, `shortlog` +and `rebase` can get confused if you run the two together. + +Explain the problem that this commit is solving. Focus on why you +are making this change as opposed to how (the code explains that). +Are there side effects or other unintuitive consequences of this +change? Here's the place to explain them. + +Further paragraphs come after blank lines. + + - Bullet points are okay, too + + - Typically a hyphen or asterisk is used for the bullet, preceded + by a single space, with blank lines in between, but conventions + vary here + +If you use an issue tracker, put references to them at the bottom, +like this: + +Resolves: #123 +See also: #456, #789 +``` + + +## The six rules of a great commit. + +#### 1. Atomic Commits +An “atomic” change revolves around one task or one fix. + +Atomic Approach + - Commit each fix or task as a separate change + - Only commit when a block of work is complete + - Commit each layout change separately + - Joint commit for layout file, code behind file, and additional resources + +Benefits + +- Easy to roll back without affecting other changes +- Easy to make other changes on the fly +- Easy to merge features to other branches + +#### Avoid trivial commit messages + +Commit messages like "fix", "fix2", or "fix3" don't provide any context or clear understanding of what changes the commit introduces. Here are some examples of good vs. bad commit messages: + +**Bad Commit Message:** + + $ git commit -m "fix" + +**Good Commit Message:** + + $ git commit -m "Fix typo in README file" + +> **Caveat**: When working with new features, an atomic commit will often consist of multiple files, since a layout file, code behind file, and additional resources may have been added/modified. You don’t want to commit all of these separately, because if you had to roll back the application to a state before the feature was added, it would involve multiple commit entries, and that can get confusing + +#### 2. Separate subject from body with a blank line + +Not every commit requires both a subject and a body. Sometimes a single line is fine, especially when the change is so simple that no further context is necessary. + +For example: + + Fix typo in introduction to user guide + +Nothing more need be said; if the reader wonders what the typo was, she can simply take a look at the change itself, i.e. use git show or git diff or git log -p. + +If you’re committing something like this at the command line, it’s easy to use the -m option to git commit: + + $ git commit -m"Fix typo in introduction to user guide" + +However, when a commit merits a bit of explanation and context, you need to write a body. For example: + + Derezz the master control program + + MCP turned out to be evil and had become intent on world domination. + This commit throws Tron's disc into MCP (causing its deresolution) + and turns it back into a chess game. + +Commit messages with bodies are not so easy to write with the -m option. You’re better off writing the message in a proper text editor. [See Pro Git](https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration). + +In any case, the separation of subject from body pays off when browsing the log. Here’s the full log entry: + + $ git log + commit 42e769bdf4894310333942ffc5a15151222a87be + Author: Kevin Flynn + Date: Fri Jan 01 00:00:00 1982 -0200 + + Derezz the master control program + + MCP turned out to be evil and had become intent on world domination. + This commit throws Tron's disc into MCP (causing its deresolution) + and turns it back into a chess game. + + +#### 3. Limit the subject line to 50 characters +50 characters is not a hard limit, just a rule of thumb. Keeping subject lines at this length ensures that they are readable, and forces the author to think for a moment about the most concise way to explain what’s going on. + +GitHub’s UI is fully aware of these conventions. It will warn you if you go past the 50 character limit. Git will truncate any subject line longer than 72 characters with an ellipsis, thus keeping it to 50 is best practice. + +#### 4. Use the imperative mood in the subject line +Imperative mood just means “spoken or written as if giving a command or instruction”. A few examples: + + Clean your room + Close the door + Take out the trash + +Each of the seven rules you’re reading about right now are written in the imperative (“Wrap the body at 72 characters”, etc.). + +The imperative can sound a little rude; that’s why we don’t often use it. But it’s perfect for Git commit subject lines. One reason for this is that Git itself uses the imperative whenever it creates a commit on your behalf. + +For example, the default message created when using git merge reads: + + Merge branch 'myfeature' + +And when using git revert: + + Revert "Add the thing with the stuff" + + This reverts commit cc87791524aedd593cff5a74532befe7ab69ce9d. + +Or when clicking the “Merge” button on a GitHub pull request: + + Merge pull request #123 from someuser/somebranch + +So when you write your commit messages in the imperative, you’re following Git’s own built-in conventions. For example: + + Refactor subsystem X for readability + Update getting started documentation + Remove deprecated methods + Release version 1.0.0 + +Writing this way can be a little awkward at first. We’re more used to speaking in the indicative mood, which is all about reporting facts. That’s why commit messages often end up reading like this: + + Fixed bug with Y + Changing behavior of X + +And sometimes commit messages get written as a description of their contents: + + More fixes for broken stuff + Sweet new API methods + +To remove any confusion, here’s a simple rule to get it right every time. + +**A properly formed Git commit subject line should always be able to complete the following sentence:** + + If applied, this commit will + +For example: + + If applied, this commit will refactor subsystem X for readability + If applied, this commit will update getting started documentation + If applied, this commit will remove deprecated methods + If applied, this commit will release version 1.0.0 + If applied, this commit will merge pull request #123 from user/branch + +#### 5. Wrap the body at 72 characters +Git never wraps text automatically. When you write the body of a commit message, you must mind its right margin, and wrap text manually. + +The recommendation is to do this at 72 characters, so that Git has plenty of room to indent text while still keeping everything under 80 characters overall. + +A good text editor can help here. It’s easy to configure Vim, for example, to wrap text at 72 characters when you’re writing a Git commit. + +#### 6. Use the body to explain what and why vs. how +This [commit](https://github.com/bitcoin/bitcoin/commit/eb0b56b19017ab5c16c745e6da39c53126924ed6) from Bitcoin Core is a great example of explaining what changed and why: + +``` +commit eb0b56b19017ab5c16c745e6da39c53126924ed6 +Author: Pieter Wuille +Date: Fri Aug 1 22:57:55 2014 +0200 + + Simplify serialize.h's exception handling + + Remove the 'state' and 'exceptmask' from serialize.h's stream + implementations, as well as related methods. + + As exceptmask always included 'failbit', and setstate was always + called with bits = failbit, all it did was immediately raise an + exception. Get rid of those variables, and replace the setstate + with direct exception throwing (which also removes some dead + code). + + As a result, good() is never reached after a failure (there are + only 2 calls, one of which is in tests), and can just be replaced + by !eof(). + + fail(), clear(n) and exceptions() are just never called. Delete + them. +``` + +Take a look at the [full diff](https://github.com/bitcoin/bitcoin/commit/eb0b56b19017ab5c16c745e6da39c53126924ed6) and just think how much time the author is saving fellow and future committers by taking the time to provide this context here and now. If he didn’t, it would probably be lost forever. + +In most cases, you can leave out details about how a change has been made. Code is generally self-explanatory in this regard (and if the code is so complex that it needs to be explained in prose, that’s what source comments are for). Just focus on making clear the reasons why you made the change in the first place—the way things worked before the change (and what was wrong with that), the way they work now, and why you decided to solve it the way you did. + +The future maintainer that thanks you may be yourself! + + + +#### Tools worth mentioning + +##### Using `--fixup` + +If you've made a commit and then realize you've missed something or made a minor mistake, you can use the `--fixup` option. + +For example, suppose you've made a commit with a hash `9fceb02`. Later, you realize you've left a debug statement in your code. Instead of making a new commit titled "remove debug statement" or "fix", you can do the following: + + $ git commit --fixup 9fceb02 + +This will create a new commit to fix the issue, with a message like "fixup! The original commit message". + +##### Interactive Rebase + +Interactive rebase, or `rebase -i`, can be used to squash these fixup commits into the original commits they're fixing, which cleans up your commit history. You can use the `autosquash` option to automatically squash any commits marked as "fixup" into their target commits. + +For example: + + $ git rebase -i --autosquash HEAD~5 + +This command starts an interactive rebase for the last 5 commits (`HEAD~5`). Any commits marked as "fixup" will be automatically moved to squash with their target commits. + +The benefit of using `--fixup` and interactive rebase is that it keeps your commit history clean and readable. It groups fixes with the commits they are related to, rather than having a separate "fix" commit that might not make sense to other developers (or even to you) in the future. + + +--- + +#### Pull Request and Squashing Commits Caveats + +While atomic commits are great for development and for understanding the changes within the branch, the commit history can get messy when merging to the main branch. To keep a cleaner and more understandable commit history in our main branch, we encourage squashing all the commits of a PR into one when merging. + +This single commit should provide an overview of the changes that the PR introduced. It should follow the guidelines for atomic commits (an atomic commit is complete, self-contained, and understandable) but on the scale of the entire feature, task, or fix that the PR addresses. This approach combines the benefits of atomic commits during development with a clean commit history in our main branch. + +Here is how you can squash commits: + +```bash +git rebase -i HEAD~n +``` + +where `n` is the number of commits to squash. After running the command, replace `pick` with `squash` for the commits you want to squash into the previous commit. This will combine the commits and allow you to write a new commit message. + +In this context, an atomic commit message could look like: + +``` +Add feature X + +This commit introduces feature X which does A, B, and C. It adds +new files for layout, updates the code behind the file, and introduces +new resources. This change is important because it allows users to +perform task Y more efficiently. + +It includes: +- Creation of new layout file +- Updates in the code-behind file +- Addition of new resources + +Resolves: #123 +``` + +In your PRs, remember to detail what the PR is introducing or fixing. This will be helpful for reviewers to understand the context and the reason behind the changes. diff --git a/contrib/TESTING.md b/contrib/TESTING.md new file mode 100644 index 0000000000..59dc1d81a3 --- /dev/null +++ b/contrib/TESTING.md @@ -0,0 +1,94 @@ +# Testing Guide for Bittensor + +Testing is an essential part of software development that ensures the correctness and performance of your code. Bittensor uses a combination of unit tests and integration tests to verify the functionality of its components. This guide will walk you through how to run and write tests for Bittensor. + +## Running Tests + +Bittensor uses `pytest` for running its tests. To run all tests, navigate to the root directory of the Bittensor repository and run: + +```bash +pytest +``` + +This will automatically discover all test files (those that start with `test_`) and run them. + +If you want to run a specific test file, you can specify it directly. For example, to run the tests in `test_wallet.py`, you would use: + +```bash +pytest tests/test_wallet.py +``` + +Similarly, you can run a specific test within a file by appending `::` and the test name. For example: + +```bash +pytest tests/test_wallet.py::test_create_new_coldkey +``` + +## Writing Tests + +When writing tests for Bittensor, you should aim to cover both the "happy path" (where everything works as expected) and any potential error conditions. Here's a basic structure for a test file: + +```python +import pytest +import bittensor + +def test_some_functionality(): + # Setup any necessary objects or state. + wallet = bittensor.wallet() + + # Call the function you're testing. + result = wallet.create_new_coldkey() + + # Assert that the function behaved as expected. + assert result is not None +``` + +In this example, we're testing the `create_new_coldkey` function of the `wallet` object. We assert that the result is not `None`, which is the expected behavior. + +## Mocking + +In some cases, you may need to mock certain functions or objects to isolate the functionality you're testing. Bittensor uses the `unittest.mock` library for this. Here's a simple example from the axon unittest: + +```python +def test_axon_start(self): + mock_wallet = MagicMock( + spec=bittensor.Wallet, + coldkey=MagicMock(), + coldkeypub=MagicMock( + # mock ss58 address + ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm" + ), + hotkey=MagicMock( + ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg" + ), + ) + axon = bittensor.axon(wallet=mock_wallet, metagraph=None) + axon.start() + assert axon.server._state.stage == grpc._server._ServerStage.STARTED +``` + +In this example, we're mocking the `coldkey`, `coldkeypub` and `hotkey` for a wallet. This allows us to test how the axon code behaves when `bittensor.Wallet()` would normally be called, without actually calling the constructor. +## Test Coverage + +It's important to ensure that your tests cover as much of your code as possible. You can use the `pytest-cov` plugin to measure your test coverage. To use it, first install it with pip: + +```bash +pip install pytest-cov +``` + +Then, you can run your tests with coverage like this: + +```bash +pytest --cov=bittensor +``` + +This will output a coverage report showing the percentage of your code that's covered by tests. + +Remember, while high test coverage is a good goal, it's also important to write meaningful tests. A test isn't very useful if it doesn't accurately represent the conditions under which your code will run. + +## Continuous Integration + +Bittensor uses CircleCI for continuous integration. This means that every time you push changes to the repository, all tests are automatically run. If any tests fail, you'll be notified so you can fix the issue before merging your changes. + + +Remember, tests are an important part of maintaining the health of a codebase. They help catch issues early and make it easier to add new features or refactor existing code. Happy testing! \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..7e6933ed25 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +version: "3.2" + +services: + dev: + container_name: node-bittensor + image: "bittensor/bittensor:latest" + ports: + - "8091:8091" + volumes: + - ~/.bittensor:/root/.bittensor \ No newline at end of file diff --git a/example.env b/example.env new file mode 100644 index 0000000000..35d405fb58 --- /dev/null +++ b/example.env @@ -0,0 +1,5 @@ +# To use legacy Torch-based of bittensor, you must set USE_TORCH=1 +USE_TORCH=0 +# If set to 0 (or anything else than 1), it will use current, numpy-based, bittensor interface. +# This is generally what you want unless you want legacy interoperability. +# Please note that the legacy interface is deprecated, and is not tested nearly as much. diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000000..d38bdc7172 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,18 @@ +[mypy] +ignore_missing_imports = True +ignore_errors = True + +[mypy-*.axon.*] +ignore_errors = False + +[mypy-*.dendrite.*] +ignore_errors = False + +[mypy-bittensor.metagraph.*] +ignore_errors = False + +[mypy-*.subtensor.*] +ignore_errors = False + +[mypy-*.synapse.*] +ignore_errors = False diff --git a/requirements/btcli.txt b/requirements/btcli.txt new file mode 100644 index 0000000000..6a86c87bcb --- /dev/null +++ b/requirements/btcli.txt @@ -0,0 +1 @@ +bittensor-cli \ No newline at end of file diff --git a/requirements/cubit.txt b/requirements/cubit.txt new file mode 100644 index 0000000000..5af1316836 --- /dev/null +++ b/requirements/cubit.txt @@ -0,0 +1,3 @@ +torch>=1.13.1 +cubit>=1.1.0 +cubit @ git+https://github.com/opentensor/cubit.git diff --git a/requirements/dev.txt b/requirements/dev.txt new file mode 100644 index 0000000000..14d616b48b --- /dev/null +++ b/requirements/dev.txt @@ -0,0 +1,19 @@ +pytest==7.2.0 +pytest-asyncio==0.23.7 +pytest-mock==3.12.0 +pytest-split==0.8.0 +pytest-xdist==3.0.2 +pytest-rerunfailures==10.2 +coveralls==3.3.1 +pytest-cov==4.0.0 +ddt==1.6.0 +hypothesis==6.81.1 +flake8==7.0.0 +mypy==1.8.0 +types-retry==0.9.9.4 +freezegun==1.5.0 +torch>=1.13.1 +httpx==0.27.0 +ruff==0.4.7 +aioresponses==0.7.6 +factory-boy==3.3.0 diff --git a/requirements/prod.txt b/requirements/prod.txt new file mode 100644 index 0000000000..631f949be3 --- /dev/null +++ b/requirements/prod.txt @@ -0,0 +1,23 @@ +wheel +setuptools~=70.0.0 +aiohttp~=3.9 +bt-decode +colorama~=0.4.6 +fastapi~=0.110.1 +munch~=2.5.0 +numpy~=2.0.1 +msgpack-numpy-opentensor~=0.5.0 +nest_asyncio +netaddr +packaging +python-statemachine~=2.1 +pyyaml +retry +requests +rich +pydantic>=2.3, <3 +python-Levenshtein +scalecodec==1.2.11 +substrate-interface~=1.7.9 +uvicorn +bittensor-wallet==1.0.0 \ No newline at end of file diff --git a/requirements/torch.txt b/requirements/torch.txt new file mode 100644 index 0000000000..028dec0810 --- /dev/null +++ b/requirements/torch.txt @@ -0,0 +1 @@ +torch>=1.13.1 diff --git a/scripts/check_compatibility.sh b/scripts/check_compatibility.sh new file mode 100755 index 0000000000..b9c89c24dd --- /dev/null +++ b/scripts/check_compatibility.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +if [ -z "$1" ]; then + echo "Please provide a Python version as an argument." + exit 1 +fi + +python_version="$1" +all_passed=true + +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +RED='\033[0;31m' +NC='\033[0m' # No Color + +check_compatibility() { + all_supported=0 + + while read -r requirement; do + # Skip lines starting with git+ + if [[ "$requirement" == git+* ]]; then + continue + fi + + package_name=$(echo "$requirement" | awk -F'[!=<>~]' '{print $1}' | awk -F'[' '{print $1}') # Strip off brackets + echo -n "Checking $package_name... " + + url="https://pypi.org/pypi/$package_name/json" + response=$(curl -s $url) + status_code=$(curl -s -o /dev/null -w "%{http_code}" $url) + + if [ "$status_code" != "200" ]; then + echo -e "${RED}Information not available for $package_name. Failure.${NC}" + all_supported=1 + continue + fi + + classifiers=$(echo "$response" | jq -r '.info.classifiers[]') + requires_python=$(echo "$response" | jq -r '.info.requires_python') + + base_version="Programming Language :: Python :: ${python_version%%.*}" + specific_version="Programming Language :: Python :: $python_version" + + if echo "$classifiers" | grep -q "$specific_version" || echo "$classifiers" | grep -q "$base_version"; then + echo -e "${GREEN}Supported${NC}" + elif [ "$requires_python" != "null" ]; then + if echo "$requires_python" | grep -Eq "==$python_version|>=$python_version|<=$python_version"; then + echo -e "${GREEN}Supported${NC}" + else + echo -e "${RED}Not compatible with Python $python_version due to constraint $requires_python.${NC}" + all_supported=1 + fi + else + echo -e "${YELLOW}Warning: Specific version not listed, assuming compatibility${NC}" + fi + done < requirements/prod.txt + + return $all_supported +} + +echo "Checking compatibility for Python $python_version..." +check_compatibility +if [ $? -eq 0 ]; then + echo -e "${GREEN}All requirements are compatible with Python $python_version.${NC}" +else + echo -e "${RED}All requirements are NOT compatible with Python $python_version.${NC}" + all_passed=false +fi + +echo "" +if $all_passed; then + echo -e "${GREEN}All tests passed.${NC}" +else + echo -e "${RED}All tests did not pass.${NC}" + exit 1 +fi diff --git a/scripts/check_pre_submit.sh b/scripts/check_pre_submit.sh new file mode 100755 index 0000000000..4dbe7747f6 --- /dev/null +++ b/scripts/check_pre_submit.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# ruff checks formating +echo ">>> Run the pre-submit format check with \`ruff format .\`." +ruff format . + +echo ">>> Run the pre-submit format check with \`mypy\`." + +# mypy checks python versions compatibility +versions=("3.9" "3.10" "3.11") +for version in "${versions[@]}"; do + echo "Running mypy for Python $version..." + mypy --ignore-missing-imports bittensor/ --python-version="$version" +done + +# flake8 checks errors count in bittensor folder +error_count=$(flake8 bittensor/ --count) +echo ">>> Flake8 found ${error_count} errors." diff --git a/scripts/check_requirements_changes.sh b/scripts/check_requirements_changes.sh new file mode 100755 index 0000000000..5fcd27ea3f --- /dev/null +++ b/scripts/check_requirements_changes.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# Check if requirements files have changed in the last commit +if git diff --name-only HEAD~1 | grep -E 'requirements/prod.txt|requirements/dev.txt'; then + echo "Requirements files have changed. Running compatibility checks..." + echo 'export REQUIREMENTS_CHANGED="true"' >> $BASH_ENV +else + echo "Requirements files have not changed. Skipping compatibility checks..." + echo 'export REQUIREMENTS_CHANGED="false"' >> $BASH_ENV +fi diff --git a/scripts/create_wallet.sh b/scripts/create_wallet.sh new file mode 100755 index 0000000000..d0ee08b69f --- /dev/null +++ b/scripts/create_wallet.sh @@ -0,0 +1,13 @@ +mkdir -p ~/.bittensor/wallets/default/hotkeys +rm ~/.bittensor/wallets/default/coldkeypub.txt +rm ~/.bittensor/wallets/default/hotkeys/default +touch ~/.bittensor/wallets/default/coldkeypub.txt +touch ~/.bittensor/wallets/default/hotkeys/default +echo "0x74acaa8d7829336dfff7569f19225818cc593335b9aafcde3f69db23c3538561" >> ~/.bittensor/wallets/default/coldkeypub.txt +echo '{"accountId": "0x9cf7085aa3304c21dc0f571c0134abb12f2e8e1bc9dbfc82440b8d6ba7908655", "publicKey": "0x9cf7085aa3304c21dc0f571c0134abb12f2e8e1bc9dbfc82440b8d6ba7908655", "secretPhrase": "document usage siren cross across crater shrug jump marine distance absurd caught", "secretSeed": "0x2465ae0757117bea271ad622e1cd0c4b319c96896a3c7d9469a68e63cf7f9646", "ss58Address": "5FcWiCiFoSspGGocSxzatNL5kT6cjxjXQ9LuAuYbvFNUqcfX"}' >> ~/.bittensor/wallets/default/hotkeys/default +chmod 0600 ~/.bittensor/wallets/default/coldkeypub.txt +chmod 0600 ~/.bittensor/wallets/default/hotkeys/default +echo "~/.bittensor/wallets/default/coldkeypub.txt" +cat ~/.bittensor/wallets/default/coldkeypub.txt +echo "~/.bittensor/wallets/default/hotkeys/default" +cat ~/.bittensor/wallets/default/hotkeys/default \ No newline at end of file diff --git a/scripts/environments/README.md b/scripts/environments/README.md new file mode 100644 index 0000000000..0caa0d2ae4 --- /dev/null +++ b/scripts/environments/README.md @@ -0,0 +1,21 @@ +## 04 Installation on Apple M chip +There are quite a few Python libraries that are not yet compatible with Apple M chipset architecture. The best way to use Bittensor on this hardware is through Conda and Miniforge. The Opentensor team has created a Conda environment that makes installing Bittensor on these systems very easy. + +> NOTE: This tutorial assumes you have installed conda on mac, if you have not done so already you can install it from [here](https://conda.io/projects/conda/en/latest/user-guide/install/macos.html). + +1. Create the conda environment from the `apple_m1_environment.yml` file here: + ```bash + conda env create -f apple_m1_environment.yml + ``` + +2. Activate the new environment: `conda activate bittensor`. +3. Verify that the new environment was installed correctly: + ```bash + conda env list + ``` + +4. Install bittensor (without dependencies): + ```bash + conda activate bittensor # activate the env + pip install --no-deps bittensor # install bittensor + ``` diff --git a/scripts/environments/apple_m1_environment.yml b/scripts/environments/apple_m1_environment.yml new file mode 100644 index 0000000000..25824aa64e --- /dev/null +++ b/scripts/environments/apple_m1_environment.yml @@ -0,0 +1,272 @@ +name: bittensor +channels: + - conda-forge +dependencies: + - anyio=3.6.2=pyhd8ed1ab_0 + - appnope=0.1.3=pyhd8ed1ab_0 + - argon2-cffi=21.3.0=pyhd8ed1ab_0 + - argon2-cffi-bindings=21.2.0=py310h8e9501a_3 + - asttokens=2.2.1=pyhd8ed1ab_0 + - async-lru=2.0.2=pyhd8ed1ab_0 + - attrs=23.1.0=pyh71513ae_1 + - babel=2.12.1=pyhd8ed1ab_1 + - backcall=0.2.0=pyh9f0ad1d_0 + - backports=1.0=pyhd8ed1ab_3 + - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 + - beautifulsoup4=4.12.2=pyha770c72_0 + - bleach=6.0.0=pyhd8ed1ab_0 + - brotli=1.0.9=h1a8c8d9_8 + - brotli-bin=1.0.9=h1a8c8d9_8 + - bzip2=1.0.8=h3422bc3_4 + - c-ares=1.18.1=h3422bc3_0 + - ca-certificates=2023.5.7=hf0a4a13_0 + - cffi=1.15.1=py310h2399d43_3 + - charset-normalizer=3.1.0=pyhd8ed1ab_0 + - comm=0.1.3=pyhd8ed1ab_0 + - debugpy=1.6.7=py310h0f1eb42_0 + - decorator=5.1.1=pyhd8ed1ab_0 + - defusedxml=0.7.1=pyhd8ed1ab_0 + - entrypoints=0.4=pyhd8ed1ab_0 + - executing=1.2.0=pyhd8ed1ab_0 + - flit-core=3.9.0=pyhd8ed1ab_0 + - gmp=6.2.1=h9f76cd9_0 + - grpcio=1.42.0=py310h00ca444_0 + - importlib-metadata=6.6.0=pyha770c72_0 + - importlib_metadata=6.6.0=hd8ed1ab_0 + - importlib_resources=5.12.0=pyhd8ed1ab_0 + - ipython=8.13.2=pyhd1c38e8_0 + - jedi=0.18.2=pyhd8ed1ab_0 + - json5=0.9.5=pyh9f0ad1d_0 + - jupyter-lsp=2.1.0=pyhd8ed1ab_0 + - jupyter_client=8.2.0=pyhd8ed1ab_0 + - jupyter_core=5.3.0=py310hbe9552e_0 + - jupyter_events=0.6.3=pyhd8ed1ab_0 + - jupyter_server=2.5.0=pyhd8ed1ab_0 + - jupyter_server_terminals=0.4.4=pyhd8ed1ab_1 + - jupyterlab=4.0.0=pyhd8ed1ab_1 + - jupyterlab_pygments=0.2.2=pyhd8ed1ab_0 + - jupyterlab_server=2.22.1=pyhd8ed1ab_0 + - libabseil=20230125.0=cxx17_hb7217d7_1 + - libbrotlicommon=1.0.9=h1a8c8d9_8 + - libbrotlidec=1.0.9=h1a8c8d9_8 + - libbrotlienc=1.0.9=h1a8c8d9_8 + - libcxx=16.0.3=h4653b0c_0 + - libffi=3.4.2=h3422bc3_5 + - libgrpc=1.54.1=h9dbdbd0_0 + - libsodium=1.0.18=h27ca646_1 + - libsqlite=3.41.2=hb31c410_1 + - libzlib=1.2.13=h03a7124_4 + - matplotlib-inline=0.1.6=pyhd8ed1ab_0 + - mistune=2.0.5=pyhd8ed1ab_0 + - nb_conda_kernels=2.3.1=py310hbe9552e_2 + - nbconvert-core=7.4.0=pyhd8ed1ab_0 + - nbformat=5.8.0=pyhd8ed1ab_0 + - ncurses=6.3=h07bb92c_1 + - nest-asyncio=1.5.6=pyhd8ed1ab_0 + - notebook-shim=0.2.3=pyhd8ed1ab_0 + - openssl=3.1.0=h53f4e23_3 + - packaging=23.1=pyhd8ed1ab_0 + - pandocfilters=1.5.0=pyhd8ed1ab_0 + - parso=0.8.3=pyhd8ed1ab_0 + - pexpect=4.8.0=pyh1a96a4e_2 + - pickleshare=0.7.5=py_1003 + - pip=23.1.2=pyhd8ed1ab_0 + - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_0 + - prompt-toolkit=3.0.38=pyha770c72_0 + - prompt_toolkit=3.0.38=hd8ed1ab_0 + - ptyprocess=0.7.0=pyhd3deb0d_0 + - pure_eval=0.2.2=pyhd8ed1ab_0 + - pycparser=2.21=pyhd8ed1ab_0 + - pycryptodome=3.19.0=py310hd71b1c6_1 + - pygments=2.15.1=pyhd8ed1ab_0 + - python-levenshtein=0.12.2=py310he2143c4_1 + - pyobjc-core=9.1.1=py310h44ed3dd_0 + - pyobjc-framework-cocoa=9.1.1=py310h44ed3dd_0 + - pyrsistent=0.19.3=py310h8e9501a_0 + - pysocks=1.7.1=pyha2e5f31_6 + - pytest-asyncio=0.21.0=pyhd8ed1ab_0 + - python=3.10.10=h3ba56d0_0_cpython + - python-dateutil=2.8.2=pyhd8ed1ab_0 + - python-json-logger=2.0.7=pyhd8ed1ab_0 + - python_abi=3.10=3_cp310 + - pytz=2023.3=pyhd8ed1ab_0 + - pyzmq=25.0.2=py310hc407298_0 + - re2=2023.02.02=hb7217d7_0 + - readline=8.2=h92ec313_1 + - rfc3339-validator=0.1.4=pyhd8ed1ab_0 + - rfc3986-validator=0.1.1=pyh9f0ad1d_0 + - send2trash=1.8.2=pyhd1c38e8_0 + - setuptools=67.7.2=pyhd8ed1ab_0 + - six=1.16.0=pyh6c4a22f_0 + - sniffio=1.3.0=pyhd8ed1ab_0 + - stack_data=0.6.2=pyhd8ed1ab_0 + - terminado=0.17.1=pyhd1c38e8_0 + - tinycss2=1.2.1=pyhd8ed1ab_0 + - tk=8.6.12=he1e0b03_0 + - tomli=2.0.1=pyhd8ed1ab_0 + - traitlets=5.9.0=pyhd8ed1ab_0 + - typing_extensions=4.6.1=pyha770c72_0 + - tzdata=2023c=h71feb2d_0 + - uvicorn=0.22.0=py310hbe9552e_0 + - wcwidth=0.2.6=pyhd8ed1ab_0 + - xz=5.2.6=h57fd34a_0 + - yaml=0.2.5=h3422bc3_2 + - zeromq=4.3.4=hbdafb3b_1 + - zipp=3.15.0=pyhd8ed1ab_0 + - zlib=1.2.13=h03a7124_4 + - pip: + - addict==2.4.0 + - aiohttp==3.9.0 + - aiosignal==1.3.1 + - altair==4.2.2 + - ansible==6.7.0 + - ansible-core==2.13.7 + - ansible-vault==2.1.0 + - appdirs==1.4.4 + - argparse==1.4.0 + - arrow==1.2.3 + - async-timeout==4.0.2 + - backoff==2.1.0 + - blinker==1.6.2 + - cachetools==4.2.4 + - certifi==2024.2.2 + - cfgv==3.4.0 + - chardet==3.0.4 + - click==8.1.3 + - colorama==0.4.6 + - commonmark==0.9.1 + - cryptography==42.0.5 + - cytoolz==0.12.2 + - dataclasses-json==0.5.13 + - ddt==1.6.0 + - dill==0.3.6 + - distlib==0.3.7 + - docker-pycreds==0.4.0 + - ecdsa==0.18.0 + - eth-hash==0.5.2 + - eth-keys==0.4.0 + - eth-typing==3.4.0 + - eth-utils==2.2.0 + - exceptiongroup==1.1.2 + - fastapi==0.110.1 + - filelock==3.12.2 + - fqdn==1.5.1 + - frozenlist==1.4.0 + - fsspec==2023.6.0 + - fuzzywuzzy==0.18.0 + - gitdb==4.0.10 + - gitpython==3.1.32 + - google-api-core==1.34.0 + - google-api-python-client==2.7.0 + - google-auth==1.35.0 + - google-auth-httplib2==0.1.0 + - googleapis-common-protos==1.59.0 + - grpcio-tools==1.42.0 + - httplib2==0.22.0 + - huggingface-hub==0.16.4 + - hypothesis==6.47.4 + - identify==2.5.26 + - ipykernel==6.26.0 + - ipython-genutils==0.2.0 + - ipywidgets==8.0.6 + - isoduration==20.11.0 + - jinja2==3.1.2 + - joblib==1.2.0 + - jsonpointer==2.3 + - jupyter==1.0.0 + - jupyter-console==6.6.3 + - jupyterlab-widgets==3.0.7 + - markupsafe==2.0.1 + - marshmallow==3.19.0 + - marshmallow-enum==1.5.1 + - more-itertools==10.0.0 + - msgpack-numpy-opentensor==0.5.0 + - multidict==6.0.4 + - multiprocess==0.70.14 + - munch==2.5.0 + - mypy-extensions==1.0.0 + - nbclassic==1.0.0 + - nbclient==0.7.4 + - netaddr==0.8.0 + - networkx==3.1 + - nltk==3.8.1 + - nodeenv==1.8.0 + - notebook==6.5.4 + - numexpr==2.8.4 + - openapi-schema-pydantic==1.2.4 + - password-strength==0.0.3.post2 + - pathtools==0.1.2 + - pillow==10.1.0 + - platformdirs==3.10.0 + - plotly==5.14.1 + - pre-commit==3.3.2 + - prometheus-client==0.14.1 + - promise==2.3 + - py==1.11.0 + - py-bip39-bindings==0.1.11 + - py-ed25519-bindings==1.0.2 + - py-ed25519-zebra-bindings==1.0.1 + - py-sr25519-bindings==0.2.0 + - pyarrow==12.0.1 + - pyasn1==0.5.0 + - pyasn1-modules==0.3.0 + - pydantic==2.7.1 + - pydeck==0.8.1b0 + - pyinstrument==4.4.0 + - pympler==1.0.1 + - pynacl==1.5.0 + - pyparsing==3.1.1 + - python-statemachine==2.1.2 + - pytest==7.4.0 + - qqdm==0.0.7 + - qtconsole==5.4.3 + - qtpy==2.3.1 + - regex==2023.6.3 + - requests==2.31.0 + - resolvelib==0.8.1 + - responses==0.18.0 + - retry==0.9.2 + - rich==12.5.1 + - rsa==4.9 + - scalecodec==1.2.11 + - scikit-learn==1.2.2 + - scipy==1.10.1 + - sentencepiece==0.1.99 + - sentry-sdk==1.28.1 + - setproctitle==1.3.2 + - shortuuid==1.0.11 + - shtab==1.6.5 + - smmap==5.0.0 + - sortedcontainers==2.4.0 + - soupsieve==2.4.1 + - sqlalchemy==2.0.19 + - starlette==0.37.2 + - streamlit==1.22.0 + - substrate-interface==1.7.9 + - tenacity==8.2.2 + - termcolor==2.1.1 + - threadpoolctl==3.1.0 + - tokenizers==0.13.3 + - toml==0.10.2 + - toolz==0.12.0 + - torch==2.0.1 + - torchvision==0.15.2 + - tornado==6.3.3 + - tqdm==4.64.1 + - typing-extensions==4.8.0 + - typing-inspect==0.8.0 + - tzlocal==5.0.1 + - uri-template==1.2.0 + - uritemplate==3.0.1 + - urllib3==1.26.15 + - validators==0.20.0 + - virtualenv==20.24.3 + - wandb==0.15.10 + - webcolors==1.13 + - webencodings==0.5.1 + - websocket-client==1.6.1 + - wheel==0.37.1 + - widgetsnbextension==4.0.7 + - xxhash==3.2.0 + - yarl==1.9.2 +prefix: /opt/homebrew/Caskroom/miniforge/base/envs/bittensor diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000000..5111d75afb --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,298 @@ + +#!/bin/bash +set -u + +# enable command completion +set -o history -o histexpand + +python="python3" + +abort() { + printf "%s\n" "$1" + exit 1 +} + +getc() { + local save_state + save_state=$(/bin/stty -g) + /bin/stty raw -echo + IFS= read -r -n 1 -d '' "$@" + /bin/stty "$save_state" +} + +exit_on_error() { + exit_code=$1 + last_command=${@:2} + if [ $exit_code -ne 0 ]; then + >&2 echo "\"${last_command}\" command failed with exit code ${exit_code}." + exit $exit_code + fi +} + +wait_for_user() { + local c + echo + echo "Press RETURN to continue or any other key to abort" + getc c + # we test for \r and \n because some stuff does \r instead + if ! [[ "$c" == $'\r' || "$c" == $'\n' ]]; then + exit 1 + fi +} + +shell_join() { + local arg + printf "%s" "$1" + shift + for arg in "$@"; do + printf " " + printf "%s" "${arg// /\ }" + done +} + +# string formatters +if [[ -t 1 ]]; then + tty_escape() { printf "\033[%sm" "$1"; } +else + tty_escape() { :; } +fi +tty_mkbold() { tty_escape "1;$1"; } +tty_underline="$(tty_escape "4;39")" +tty_blue="$(tty_mkbold 34)" +tty_red="$(tty_mkbold 31)" +tty_bold="$(tty_mkbold 39)" +tty_reset="$(tty_escape 0)" + +ohai() { + printf "${tty_blue}==>${tty_bold} %s${tty_reset}\n" "$(shell_join "$@")" +} + +# Things can fail later if `pwd` doesn't exist. +# Also sudo prints a warning message for no good reason +cd "/usr" || exit 1 + +linux_install_pre() { + sudo apt-get update + sudo apt-get install --no-install-recommends --no-install-suggests -y apt-utils curl git cmake build-essential + exit_on_error $? +} + +linux_install_python() { + which $python + if [[ $? != 0 ]] ; then + ohai "Installing python" + sudo apt-get install --no-install-recommends --no-install-suggests -y $python + else + ohai "Updating python" + sudo apt-get install --only-upgrade $python + fi + exit_on_error $? + ohai "Installing python tools" + sudo apt-get install --no-install-recommends --no-install-suggests -y $python-pip $python-dev + exit_on_error $? +} + +linux_update_pip() { + PYTHONPATH=$(which $python) + ohai "You are using python@ $PYTHONPATH$" + ohai "Installing python tools" + $python -m pip install --upgrade pip +} + +linux_install_bittensor() { + ohai "Cloning bittensor@master into ~/.bittensor/bittensor" + mkdir -p ~/.bittensor/bittensor + git clone https://github.com/opentensor/bittensor.git ~/.bittensor/bittensor/ 2> /dev/null || (cd ~/.bittensor/bittensor/ ; git fetch origin master ; git checkout master ; git pull --ff-only ; git reset --hard ; git clean -xdf) + ohai "Installing bittensor" + $python -m pip install -e ~/.bittensor/bittensor/ + exit_on_error $? +} + +linux_increase_ulimit(){ + ohai "Increasing ulimit to 1,000,000" + prlimit --pid=$PPID --nofile=1000000 +} + + +mac_install_xcode() { + which -s xcode-select + if [[ $? != 0 ]] ; then + ohai "Installing xcode:" + xcode-select --install + exit_on_error $? + fi +} + +mac_install_brew() { + which -s brew + if [[ $? != 0 ]] ; then + ohai "Installing brew:" + ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" + else + ohai "Updating brew:" + brew update --verbose + fi + exit_on_error $? +} + +mac_install_cmake() { + which -s cmake + if [[ $? != 0 ]] ; then + ohai "Installing cmake:" + brew install cmake + else + ohai "Updating cmake:" + brew upgrade cmake + fi +} + +mac_install_python() { + which -s python3 + ohai "Installing python3" + brew list python@3 &>/dev/null || brew install python@3; + ohai "Updating python3" + brew upgrade python@3 + exit_on_error $? +} + +mac_update_pip() { + PYTHONPATH=$(which $python) + ohai "You are using python@ $PYTHONPATH$" + ohai "Installing python tools" + $python -m pip install --upgrade pip +} + +mac_install_bittensor() { + ohai "Cloning bittensor@text_prompting into ~/.bittensor/bittensor" + git clone https://github.com/opentensor/bittensor.git ~/.bittensor/bittensor/ 2> /dev/null || (cd ~/.bittensor/bittensor/ ; git fetch origin master ; git checkout master ; git pull --ff-only ; git reset --hard; git clean -xdf) + ohai "Installing bittensor" + $python -m pip install -e ~/.bittensor/bittensor/ + exit_on_error $? + deactivate +} + +# Do install. +OS="$(uname)" +if [[ "$OS" == "Linux" ]]; then + + which -s apt + if [[ $? == 0 ]] ; then + abort "This linux based install requires apt. To run with other distros (centos, arch, etc), you will need to manually install the requirements" + fi + echo """ + +██████╗░██╗████████╗████████╗███████╗███╗░░██╗░██████╗░█████╗░██████╗░ +██╔══██╗██║╚══██╔══╝╚══██╔══╝██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗ +██████╦╝██║░░░██║░░░░░░██║░░░█████╗░░██╔██╗██║╚█████╗░██║░░██║██████╔╝ +██╔══██╗██║░░░██║░░░░░░██║░░░██╔══╝░░██║╚████║░╚═══██╗██║░░██║██╔══██╗ +██████╦╝██║░░░██║░░░░░░██║░░░███████╗██║░╚███║██████╔╝╚█████╔╝██║░░██║ +╚═════╝░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚══════╝╚═╝░░╚══╝╚═════╝░░╚════╝░╚═╝░░╚═╝ + + - Mining a new element. + """ + ohai "This script will install:" + echo "git" + echo "curl" + echo "cmake" + echo "build-essential" + echo "python3" + echo "python3-pip" + echo "bittensor" + + wait_for_user + linux_install_pre + linux_install_python + linux_update_pip + linux_install_bittensor + + ohai "Would you like to increase the ulimit? This will allow your miner to run for a longer time" + wait_for_user + linux_increase_ulimit + echo "" + echo "" + echo "######################################################################" + echo "## ##" + echo "## BITTENSOR SETUP ##" + echo "## ##" + echo "######################################################################" + echo "" + echo "" + +elif [[ "$OS" == "Darwin" ]]; then + echo """ + +██████╗░██╗████████╗████████╗███████╗███╗░░██╗░██████╗░█████╗░██████╗░ +██╔══██╗██║╚══██╔══╝╚══██╔══╝██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗ +██████╦╝██║░░░██║░░░░░░██║░░░█████╗░░██╔██╗██║╚█████╗░██║░░██║██████╔╝ +██╔══██╗██║░░░██║░░░░░░██║░░░██╔══╝░░██║╚████║░╚═══██╗██║░░██║██╔══██╗ +██████╦╝██║░░░██║░░░░░░██║░░░███████╗██║░╚███║██████╔╝╚█████╔╝██║░░██║ +╚═════╝░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚══════╝╚═╝░░╚══╝╚═════╝░░╚════╝░╚═╝░░╚═╝ + + - Mining a new element. + """ + ohai "This script will install:" + echo "xcode" + echo "homebrew" + echo "git" + echo "cmake" + echo "python3" + echo "python3-pip" + echo "bittensor" + + wait_for_user + mac_install_brew + mac_install_cmake + mac_install_python + mac_update_pip + mac_install_bittensor + echo "" + echo "" + echo "######################################################################" + echo "## ##" + echo "## BITTENSOR SETUP ##" + echo "## ##" + echo "######################################################################" +else + abort "Bittensor is only supported on macOS and Linux" +fi + +# Use the shell's audible bell. +if [[ -t 1 ]]; then +printf "\a" +fi + +echo "" +echo "" +ohai "Welcome. Installation successful" +echo "" +echo "- 1. Create a wallet " +echo " $ btcli new_coldkey (for holding funds)" +echo " $ btcli new_hotkey (for running miners)" +echo "" +echo "- 2. Run a miner on the prompting network. " +echo " $ python3 ~/.bittensor/bittensor/neurons/text/prompting/miners/gpt4all/neuron.py" +echo "" +ohai "Extras:" +echo "" +echo "- Check your tao balance: " +echo " $ btcli wallet overview" +echo "" +echo "- Stake to your miners:" +echo " $ btcli stake add" +echo " $ btcli stake remove" +echo "" +echo "- Create/list/register wallets" +echo " $ btcli w new_coldkey" +echo " $ btcli w new_hotkey" +echo " $ btcli w list" +echo " $ btcli s register" +echo "" +echo "- Use the Python API" +echo " $ python3"echo " >> import bittensor" +echo "" +echo "- Join the discussion: " +echo " ${tty_underline}https://discord.gg/3rUr6EcvbB${tty_reset}" +echo "" + + + diff --git a/scripts/post_install_cli.py b/scripts/post_install_cli.py new file mode 100644 index 0000000000..bfaca34c37 --- /dev/null +++ b/scripts/post_install_cli.py @@ -0,0 +1,29 @@ +import os +import subprocess +import sys + + +def post_install(): + # Determine the shell type (bash, zsh, etc.) + shell = os.environ.get("SHELL") + if "bash" in shell: + shell_config = "~/.bashrc" + elif "zsh" in shell: + shell_config = "~/.zshrc" + else: + print("Unsupported shell for autocompletion.") + return + + # Generate the completion script + completion_script = subprocess.check_output( + [sys.executable, "-m", "bittensor.cli", "--print-completion", shell] + ).decode() + + # Append the completion script to the shell configuration file + with open(os.path.expanduser(shell_config), "a") as file: + file.write("\n# Bittensor CLI Autocompletion\n") + file.write(completion_script) + + +if __name__ == "__main__": + post_install() diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000..290274bd84 --- /dev/null +++ b/setup.py @@ -0,0 +1,98 @@ +# The MIT License (MIT) +# Copyright © 2024 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 codecs +import os +import pathlib +import re +from io import open +from os import path + +from setuptools import setup, find_packages + + +def read_requirements(path): + requirements = [] + + with pathlib.Path(path).open() as requirements_txt: + for line in requirements_txt: + if line.startswith("git+"): + pkg_name = re.search(r"egg=([a-zA-Z0-9_-]+)", line.strip()).group(1) + requirements.append(pkg_name + " @ " + line.strip()) + else: + requirements.append(line.strip()) + + return requirements + + +requirements = read_requirements("requirements/prod.txt") +extra_requirements_btcli = read_requirements("requirements/btcli.txt") +extra_requirements_dev = read_requirements("requirements/dev.txt") +extra_requirements_cubit = read_requirements("requirements/cubit.txt") +extra_requirements_torch = read_requirements("requirements/torch.txt") + +here = path.abspath(path.dirname(__file__)) + +with open(path.join(here, "README.md"), encoding="utf-8") as f: + long_description = f.read() + + +# loading version from setup.py +with codecs.open( + os.path.join(here, "bittensor/core/settings.py"), encoding="utf-8" +) as init_file: + version_match = re.search( + r"^__version__ = ['\"]([^'\"]*)['\"]", init_file.read(), re.M + ) + version_string = version_match.group(1) + +setup( + name="bittensor", + version=version_string, + description="bittensor", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/opentensor/bittensor", + author="bittensor.com", + packages=find_packages(exclude=["tests", "tests.*"]), + include_package_data=True, + author_email="", + license="MIT", + python_requires=">=3.9", + install_requires=requirements, + extras_require={ + "btcli": extra_requirements_btcli, + "dev": extra_requirements_dev, + "torch": extra_requirements_torch, + }, + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Build Tools", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Mathematics", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Software Development", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Libraries :: Python Modules", + ], +) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..1c7bc4757e --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,18 @@ +# The MIT License (MIT) +# Copyright © 2022 Yuma Rao +# Copyright © 2022-2023 Opentensor Foundation +# Copyright © 2023 Opentensor Technologies Inc + +# 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. diff --git a/tests/e2e_tests/__init__.py b/tests/e2e_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/e2e_tests/conftest.py b/tests/e2e_tests/conftest.py new file mode 100644 index 0000000000..d82944afd5 --- /dev/null +++ b/tests/e2e_tests/conftest.py @@ -0,0 +1,84 @@ +import os +import re +import shlex +import signal +import subprocess +import time + +import pytest +from substrateinterface import SubstrateInterface + +from bittensor import logging +from tests.e2e_tests.utils.e2e_test_utils import ( + clone_or_update_templates, + install_templates, + template_path, + uninstall_templates, +) + + +# Fixture for setting up and tearing down a localnet.sh chain between tests +@pytest.fixture(scope="function") +def local_chain(request): + param = request.param if hasattr(request, "param") else None + # Get the environment variable for the script path + script_path = os.getenv("LOCALNET_SH_PATH") + + if not script_path: + # Skip the test if the localhost.sh path is not set + logging.warning("LOCALNET_SH_PATH env variable is not set, e2e test skipped.") + pytest.skip("LOCALNET_SH_PATH environment variable is not set.") + + # Check if param is None, and handle it accordingly + args = "" if param is None else f"{param}" + + # Compile commands to send to process + cmds = shlex.split(f"{script_path} {args}") + + # Start new node process + process = subprocess.Popen( + cmds, stdout=subprocess.PIPE, text=True, preexec_fn=os.setsid + ) + + # Pattern match indicates node is compiled and ready + pattern = re.compile(r"Imported #1") + + # install neuron templates + logging.info("downloading and installing neuron templates from github") + templates_dir = clone_or_update_templates() + install_templates(templates_dir) + + timestamp = int(time.time()) + + def wait_for_node_start(process, pattern): + for line in process.stdout: + print(line.strip()) + # 10 min as timeout + if int(time.time()) - timestamp > 10 * 60: + print("Subtensor not started in time") + break + if pattern.search(line): + print("Node started!") + break + + wait_for_node_start(process, pattern) + + # Run the test, passing in substrate interface + yield SubstrateInterface(url="ws://127.0.0.1:9945") + + # Terminate the process group (includes all child processes) + os.killpg(os.getpgid(process.pid), signal.SIGTERM) + + # Give some time for the process to terminate + time.sleep(1) + + # If the process is not terminated, send SIGKILL + if process.poll() is None: + os.killpg(os.getpgid(process.pid), signal.SIGKILL) + + # Ensure the process has terminated + process.wait() + + # uninstall templates + logging.info("uninstalling neuron templates") + uninstall_templates(template_path) diff --git a/tests/e2e_tests/test_axon.py b/tests/e2e_tests/test_axon.py new file mode 100644 index 0000000000..853719f85d --- /dev/null +++ b/tests/e2e_tests/test_axon.py @@ -0,0 +1,128 @@ +import asyncio +import sys + +import pytest + +import bittensor +from bittensor import logging +from bittensor.utils import networking +from tests.e2e_tests.utils.chain_interactions import register_neuron, register_subnet +from tests.e2e_tests.utils.e2e_test_utils import ( + setup_wallet, + template_path, + templates_repo, +) + + +@pytest.mark.asyncio +async def test_axon(local_chain): + """ + Test the Axon mechanism and successful registration on the network. + + Steps: + 1. Register a subnet and register Alice + 2. Check if metagraph.axon is updated and check axon attributes + 3. Run Alice as a miner on the subnet + 4. Check the metagraph again after running the miner and verify all attributes + Raises: + AssertionError: If any of the checks or verifications fail + """ + + logging.info("Testing test_axon") + + netuid = 1 + # Register root as Alice - the subnet owner + alice_keypair, wallet = setup_wallet("//Alice") + + # Register a subnet, netuid 1 + assert register_subnet(local_chain, wallet), "Subnet wasn't created" + + # Verify subnet created successfully + assert local_chain.query( + "SubtensorModule", "NetworksAdded", [netuid] + ).serialize(), "Subnet wasn't created successfully" + + # Register Alice to the network + assert register_neuron( + local_chain, wallet, netuid + ), f"Neuron wasn't registered to subnet {netuid}" + + metagraph = bittensor.Metagraph(netuid=netuid, network="ws://localhost:9945") + + # Validate current metagraph stats + old_axon = metagraph.axons[0] + assert len(metagraph.axons) == 1, f"Expected 1 axon, but got {len(metagraph.axons)}" + assert old_axon.hotkey == alice_keypair.ss58_address, "Hotkey mismatch for the axon" + assert ( + old_axon.coldkey == alice_keypair.ss58_address + ), "Coldkey mismatch for the axon" + assert old_axon.ip == "0.0.0.0", f"Expected IP 0.0.0.0, but got {old_axon.ip}" + assert old_axon.port == 0, f"Expected port 0, but got {old_axon.port}" + assert old_axon.ip_type == 0, f"Expected IP type 0, but got {old_axon.ip_type}" + + # Prepare to run the miner + cmd = " ".join( + [ + f"{sys.executable}", + f'"{template_path}{templates_repo}/neurons/miner.py"', + "--no_prompt", + "--netuid", + str(netuid), + "--subtensor.network", + "local", + "--subtensor.chain_endpoint", + "ws://localhost:9945", + "--wallet.path", + wallet.path, + "--wallet.name", + wallet.name, + "--wallet.hotkey", + "default", + ] + ) + + # Run the miner in the background + await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + + logging.info("Neuron Alice is now mining") + + # Waiting for 5 seconds for metagraph to be updated + await asyncio.sleep(5) + + # Refresh the metagraph + metagraph = bittensor.Metagraph(netuid=netuid, network="ws://localhost:9945") + updated_axon = metagraph.axons[0] + external_ip = networking.get_external_ip() + + # Assert updated attributes + assert ( + len(metagraph.axons) == 1 + ), f"Expected 1 axon, but got {len(metagraph.axons)} after mining" + + assert ( + len(metagraph.neurons) == 1 + ), f"Expected 1 neuron, but got {len(metagraph.neurons)}" + + assert ( + updated_axon.ip == external_ip + ), f"Expected IP {external_ip}, but got {updated_axon.ip}" + + assert ( + updated_axon.ip_type == networking.ip_version(external_ip) + ), f"Expected IP type {networking.ip_version(external_ip)}, but got {updated_axon.ip_type}" + + assert updated_axon.port == 8091, f"Expected port 8091, but got {updated_axon.port}" + + assert ( + updated_axon.hotkey == alice_keypair.ss58_address + ), "Hotkey mismatch after mining" + + assert ( + updated_axon.coldkey == alice_keypair.ss58_address + ), "Coldkey mismatch after mining" + + logging.info("✅ Passed test_axon") diff --git a/tests/e2e_tests/test_commit_weights.py b/tests/e2e_tests/test_commit_weights.py new file mode 100644 index 0000000000..ca9b0a0a2c --- /dev/null +++ b/tests/e2e_tests/test_commit_weights.py @@ -0,0 +1,165 @@ +import time + +import numpy as np +import pytest + +import bittensor +from bittensor import logging +from bittensor.utils.weight_utils import convert_weights_and_uids_for_emit +from tests.e2e_tests.utils.chain_interactions import ( + add_stake, + register_neuron, + register_subnet, + sudo_set_hyperparameter_bool, + sudo_set_hyperparameter_values, + wait_interval, +) +from tests.e2e_tests.utils.e2e_test_utils import setup_wallet + + +@pytest.mark.asyncio +async def test_commit_and_reveal_weights(local_chain): + """ + Tests the commit/reveal weights mechanism + + Steps: + 1. Register a subnet through Alice + 2. Register Alice's neuron and add stake + 3. Enable commit-reveal mechanism on the subnet + 4. Lower the commit_reveal interval and rate limit + 5. Commit weights and verify + 6. Wait interval & reveal weights and verify + Raises: + AssertionError: If any of the checks or verifications fail + """ + netuid = 1 + logging.info("Testing test_commit_and_reveal_weights") + # Register root as Alice + keypair, alice_wallet = setup_wallet("//Alice") + assert register_subnet(local_chain, alice_wallet), "Unable to register the subnet" + + # Verify subnet 1 created successfully + assert local_chain.query( + "SubtensorModule", "NetworksAdded", [1] + ).serialize(), "Subnet wasn't created successfully" + + assert register_neuron( + local_chain, alice_wallet, netuid + ), "Unable to register Alice as a neuron" + + # Stake to become to top neuron after the first epoch + add_stake(local_chain, alice_wallet, bittensor.Balance.from_tao(100_000)) + + # Enable commit_reveal on the subnet + assert sudo_set_hyperparameter_bool( + local_chain, + alice_wallet, + "sudo_set_commit_reveal_weights_enabled", + True, + netuid, + ), "Unable to enable commit reveal on the subnet" + + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + assert subtensor.get_subnet_hyperparameters( + netuid=netuid + ).commit_reveal_weights_enabled, "Failed to enable commit/reveal" + + # Lower the commit_reveal interval + assert sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_commit_reveal_weights_interval", + call_params={"netuid": netuid, "interval": "370"}, + return_error_message=True, + ) + + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + assert ( + subtensor.get_subnet_hyperparameters( + netuid=netuid + ).commit_reveal_weights_interval + == 370 + ), "Failed to set commit/reveal interval" + + assert ( + subtensor.weights_rate_limit(netuid=netuid) > 0 + ), "Weights rate limit is below 0" + # Lower the rate limit + assert sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_weights_set_rate_limit", + call_params={"netuid": netuid, "weights_set_rate_limit": "0"}, + return_error_message=True, + ) + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + assert ( + subtensor.get_subnet_hyperparameters(netuid=netuid).weights_rate_limit == 0 + ), "Failed to set weights_rate_limit" + assert subtensor.weights_rate_limit(netuid=netuid) == 0 + + # Commit-reveal values + uids = np.array([0], dtype=np.int64) + weights = np.array([0.1], dtype=np.float32) + salt = [18, 179, 107, 0, 165, 211, 141, 197] + weight_uids, weight_vals = convert_weights_and_uids_for_emit( + uids=uids, weights=weights + ) + + # Commit weights + success, message = subtensor.commit_weights( + alice_wallet, + netuid, + salt=salt, + uids=weight_uids, + weights=weight_vals, + wait_for_inclusion=True, + wait_for_finalization=True, + ) + + weight_commits = subtensor.query_module( + module="SubtensorModule", + name="WeightCommits", + params=[netuid, alice_wallet.hotkey.ss58_address], + ) + # Assert that the committed weights are set correctly + assert weight_commits.value is not None, "Weight commit not found in storage" + commit_hash, commit_block = weight_commits.value + assert commit_block > 0, f"Invalid block number: {commit_block}" + + # Query the WeightCommitRevealInterval storage map + weight_commit_reveal_interval = subtensor.query_module( + module="SubtensorModule", name="WeightCommitRevealInterval", params=[netuid] + ) + interval = weight_commit_reveal_interval.value + assert interval > 0, "Invalid WeightCommitRevealInterval" + + # Wait until the reveal block range + await wait_interval(interval, subtensor) + + # Reveal weights + success, message = subtensor.reveal_weights( + alice_wallet, + netuid, + uids=weight_uids, + weights=weight_vals, + salt=salt, + wait_for_inclusion=True, + wait_for_finalization=True, + ) + time.sleep(10) + + # Query the Weights storage map + revealed_weights = subtensor.query_module( + module="SubtensorModule", + name="Weights", + params=[netuid, 0], # netuid and uid + ) + + # Assert that the revealed weights are set correctly + assert revealed_weights.value is not None, "Weight reveal not found in storage" + + assert ( + weight_vals[0] == revealed_weights.value[0][1] + ), f"Incorrect revealed weights. Expected: {weights[0]}, Actual: {revealed_weights.value[0][1]}" + logging.info("✅ Passed test_commit_and_reveal_weights") diff --git a/tests/e2e_tests/test_dendrite.py b/tests/e2e_tests/test_dendrite.py new file mode 100644 index 0000000000..e075326ca5 --- /dev/null +++ b/tests/e2e_tests/test_dendrite.py @@ -0,0 +1,136 @@ +import asyncio +import sys + +import pytest + +import bittensor +from bittensor import logging, Subtensor + +from tests.e2e_tests.utils.e2e_test_utils import ( + setup_wallet, + template_path, + templates_repo, +) +from tests.e2e_tests.utils.chain_interactions import ( + register_neuron, + register_subnet, + add_stake, + wait_epoch, +) + + +@pytest.mark.asyncio +async def test_dendrite(local_chain): + """ + Test the Dendrite mechanism + + Steps: + 1. Register a subnet through Alice + 2. Register Bob as a validator + 3. Add stake to Bob and ensure neuron is not a validator yet + 4. Run Bob as a validator and wait epoch + 5. Ensure Bob's neuron has all correct attributes of a validator + Raises: + AssertionError: If any of the checks or verifications fail + """ + + logging.info("Testing test_dendrite") + netuid = 1 + + # Register root as Alice - the subnet owner + alice_keypair, alice_wallet = setup_wallet("//Alice") + + # Register a subnet, netuid 1 + assert register_subnet(local_chain, alice_wallet), "Subnet wasn't created" + + # Verify subnet created successfully + assert local_chain.query( + "SubtensorModule", "NetworksAdded", [netuid] + ).serialize(), "Subnet wasn't created successfully" + + # Register Bob + bob_keypair, bob_wallet = setup_wallet("//Bob") + + # Register Bob to the network + assert register_neuron( + local_chain, bob_wallet, netuid + ), f"Neuron wasn't registered to subnet {netuid}" + + metagraph = bittensor.Metagraph(netuid=netuid, network="ws://localhost:9945") + subtensor = Subtensor(network="ws://localhost:9945") + + # Assert one neuron is Bob + assert len(subtensor.neurons(netuid=netuid)) == 1 + neuron = metagraph.neurons[0] + assert neuron.hotkey == bob_keypair.ss58_address + assert neuron.coldkey == bob_keypair.ss58_address + + # Assert stake is 0 + assert neuron.stake.tao == 0 + + # Stake to become to top neuron after the first epoch + assert add_stake(local_chain, bob_wallet, bittensor.Balance.from_tao(10_000)) + + # Refresh metagraph + metagraph = bittensor.Metagraph(netuid=netuid, network="ws://localhost:9945") + old_neuron = metagraph.neurons[0] + + # Assert stake is 10000 + assert ( + old_neuron.stake.tao == 10_000.0 + ), f"Expected 10_000.0 staked TAO, but got {neuron.stake.tao}" + + # Assert neuron is not a validator yet + assert old_neuron.active is True + assert old_neuron.validator_permit is False + assert old_neuron.validator_trust == 0.0 + assert old_neuron.pruning_score == 0 + + # Prepare to run the validator + cmd = " ".join( + [ + f"{sys.executable}", + f'"{template_path}{templates_repo}/neurons/validator.py"', + "--no_prompt", + "--netuid", + str(netuid), + "--subtensor.network", + "local", + "--subtensor.chain_endpoint", + "ws://localhost:9945", + "--wallet.path", + bob_wallet.path, + "--wallet.name", + bob_wallet.name, + "--wallet.hotkey", + "default", + ] + ) + + # Run the validator in the background + await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + logging.info("Neuron Alice is now validating") + await asyncio.sleep( + 5 + ) # wait for 5 seconds for the metagraph and subtensor to refresh with latest data + + await wait_epoch(subtensor, netuid=netuid) + + # Refresh metagraph + metagraph = bittensor.Metagraph(netuid=netuid, network="ws://localhost:9945") + + # Refresh validator neuron + updated_neuron = metagraph.neurons[0] + + assert len(metagraph.neurons) == 1 + assert updated_neuron.active is True + assert updated_neuron.validator_permit is True + assert updated_neuron.hotkey == bob_keypair.ss58_address + assert updated_neuron.coldkey == bob_keypair.ss58_address + assert updated_neuron.pruning_score != 0 + + logging.info("✅ Passed test_dendrite") diff --git a/tests/e2e_tests/test_incentive.py b/tests/e2e_tests/test_incentive.py new file mode 100644 index 0000000000..3e309f4f64 --- /dev/null +++ b/tests/e2e_tests/test_incentive.py @@ -0,0 +1,184 @@ +import asyncio +import sys + +import pytest + +from bittensor import Subtensor, logging +from tests.e2e_tests.utils.chain_interactions import ( + add_stake, + register_neuron, + register_subnet, + wait_epoch, +) +from tests.e2e_tests.utils.e2e_test_utils import ( + setup_wallet, + template_path, + templates_repo, +) +from bittensor.utils.balance import Balance +from bittensor.core.extrinsics.set_weights import do_set_weights +from bittensor.core.metagraph import Metagraph + + +@pytest.mark.asyncio +async def test_incentive(local_chain): + """ + Test the incentive mechanism and interaction of miners/validators + + Steps: + 1. Register a subnet and register Alice & Bob + 2. Add Stake by Alice + 3. Run Alice as validator & Bob as miner. Wait Epoch + 4. Verify miner has correct: trust, rank, consensus, incentive + 5. Verify validator has correct: validator_permit, validator_trust, dividends, stake + Raises: + AssertionError: If any of the checks or verifications fail + """ + + logging.info("Testing test_incentive") + netuid = 1 + + # Register root as Alice - the subnet owner and validator + alice_keypair, alice_wallet = setup_wallet("//Alice") + register_subnet(local_chain, alice_wallet) + + # Verify subnet created successfully + assert local_chain.query( + "SubtensorModule", "NetworksAdded", [netuid] + ).serialize(), "Subnet wasn't created successfully" + + # Register Bob as miner + bob_keypair, bob_wallet = setup_wallet("//Bob") + + # Register Alice as a neuron on the subnet + register_neuron(local_chain, alice_wallet, netuid) + + # Register Bob as a neuron on the subnet + register_neuron(local_chain, bob_wallet, netuid) + + subtensor = Subtensor(network="ws://localhost:9945") + # Assert two neurons are in network + assert ( + len(subtensor.neurons(netuid=netuid)) == 2 + ), "Alice & Bob not registered in the subnet" + + # Alice to stake to become to top neuron after the first epoch + add_stake(local_chain, alice_wallet, Balance.from_tao(10_000)) + + # Prepare to run Bob as miner + cmd = " ".join( + [ + f"{sys.executable}", + f'"{template_path}{templates_repo}/neurons/miner.py"', + "--no_prompt", + "--netuid", + str(netuid), + "--subtensor.network", + "local", + "--subtensor.chain_endpoint", + "ws://localhost:9945", + "--wallet.path", + bob_wallet.path, + "--wallet.name", + bob_wallet.name, + "--wallet.hotkey", + "default", + "--logging.trace", + ] + ) + + # Run Bob as miner in the background + await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + logging.info("Neuron Bob is now mining") + await asyncio.sleep( + 5 + ) # wait for 5 seconds for the metagraph to refresh with latest data + + # Prepare to run Alice as validator + cmd = " ".join( + [ + f"{sys.executable}", + f'"{template_path}{templates_repo}/neurons/validator.py"', + "--no_prompt", + "--netuid", + str(netuid), + "--subtensor.network", + "local", + "--subtensor.chain_endpoint", + "ws://localhost:9945", + "--wallet.path", + alice_wallet.path, + "--wallet.name", + alice_wallet.name, + "--wallet.hotkey", + "default", + "--logging.trace", + ] + ) + + # Run Alice as validator in the background + await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + logging.info("Neuron Alice is now validating") + await asyncio.sleep( + 5 + ) # wait for 5 seconds for the metagraph and subtensor to refresh with latest data + + # Get latest metagraph + metagraph = Metagraph(netuid=netuid, network="ws://localhost:9945") + + # Get current miner/validator stats + bob_neuron = metagraph.neurons[1] + assert bob_neuron.incentive == 0 + assert bob_neuron.consensus == 0 + assert bob_neuron.rank == 0 + assert bob_neuron.trust == 0 + + alice_neuron = metagraph.neurons[0] + assert alice_neuron.validator_permit is False + assert alice_neuron.dividends == 0 + assert alice_neuron.stake.tao == 10_000.0 + assert alice_neuron.validator_trust == 0 + + # Wait until next epoch + await wait_epoch(subtensor) + + # Set weights by Alice on the subnet + do_set_weights( + self=subtensor, + wallet=alice_wallet, + uids=[1], + vals=[65535], + netuid=netuid, + version_key=0, + wait_for_inclusion=True, + wait_for_finalization=True, + ) + logging.info("Alice neuron set weights successfully") + + await wait_epoch(subtensor) + + # Refresh metagraph + metagraph = Metagraph(netuid=netuid, network="ws://localhost:9945") + + # Get current emissions and validate that Alice has gotten tao + bob_neuron = metagraph.neurons[1] + assert bob_neuron.incentive == 1 + assert bob_neuron.consensus == 1 + assert bob_neuron.rank == 1 + assert bob_neuron.trust == 1 + + alice_neuron = metagraph.neurons[0] + assert alice_neuron.validator_permit is True + assert alice_neuron.dividends == 1 + assert alice_neuron.stake.tao == 10_000.0 + assert alice_neuron.validator_trust == 1 + + logging.info("✅ Passed test_incentive") diff --git a/tests/e2e_tests/test_liquid_alpha.py b/tests/e2e_tests/test_liquid_alpha.py new file mode 100644 index 0000000000..d73162fbb4 --- /dev/null +++ b/tests/e2e_tests/test_liquid_alpha.py @@ -0,0 +1,186 @@ +import bittensor +from bittensor import logging +from tests.e2e_tests.utils.chain_interactions import ( + add_stake, + register_neuron, + register_subnet, + sudo_set_hyperparameter_bool, + sudo_set_hyperparameter_values, +) +from tests.e2e_tests.utils.e2e_test_utils import setup_wallet + + +def liquid_alpha_call_params(netuid: int, alpha_values: str): + alpha_low, alpha_high = [v.strip() for v in alpha_values.split(",")] + return { + "netuid": netuid, + "alpha_low": alpha_low, + "alpha_high": alpha_high, + } + + +def test_liquid_alpha(local_chain): + """ + Test the liquid alpha mechanism + + Steps: + 1. Register a subnet through Alice + 2. Register Alice's neuron and add stake + 3. Verify we can't set alpha values without enabling liquid_alpha + 4. Test setting alpha values after enabling liquid_alpha + 5. Verify failures when setting incorrect values (upper and lower bounds) + Raises: + AssertionError: If any of the checks or verifications fail + """ + u16_max = 65535 + netuid = 1 + logging.info("Testing test_liquid_alpha_enabled") + + # Register root as Alice + keypair, alice_wallet = setup_wallet("//Alice") + register_subnet(local_chain, alice_wallet), "Unable to register the subnet" + + # Verify subnet 1 created successfully + assert local_chain.query("SubtensorModule", "NetworksAdded", [1]).serialize() + + # Register a neuron to the subnet + assert register_neuron( + local_chain, alice_wallet, netuid + ), "Unable to register Alice as a neuron" + + # Stake to become to top neuron after the first epoch + add_stake(local_chain, alice_wallet, bittensor.Balance.from_tao(100_000)) + + # Assert liquid alpha is disabled + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + assert ( + subtensor.get_subnet_hyperparameters(netuid=netuid).liquid_alpha_enabled + is False + ), "Liquid alpha is enabled by default" + + # Attempt to set alpha high/low while disabled (should fail) + alpha_values = "6553, 53083" + call_params = liquid_alpha_call_params(netuid, alpha_values) + result, error_message = sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + return_error_message=True, + ) + assert result is False, "Alpha values set while being disabled" + assert error_message["name"] == "LiquidAlphaDisabled" + + # Enabled liquid alpha on the subnet + assert sudo_set_hyperparameter_bool( + local_chain, alice_wallet, "sudo_set_liquid_alpha_enabled", True, netuid + ), "Unable to enable liquid alpha" + + assert subtensor.get_subnet_hyperparameters( + netuid=1 + ).liquid_alpha_enabled, "Failed to enable liquid alpha" + + # Attempt to set alpha high & low after enabling the hyperparameter + alpha_values = "87, 54099" + call_params = liquid_alpha_call_params(netuid, alpha_values) + assert sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + ), "Unable to set alpha_values" + assert ( + subtensor.get_subnet_hyperparameters(netuid=1).alpha_high == 54099 + ), "Failed to set alpha high" + assert ( + subtensor.get_subnet_hyperparameters(netuid=1).alpha_low == 87 + ), "Failed to set alpha low" + + # Testing alpha high upper and lower bounds + + # 1. Test setting Alpha_high too low + alpha_high_too_low = ( + u16_max * 4 // 5 + ) - 1 # One less than the minimum acceptable value + call_params = liquid_alpha_call_params(netuid, f"6553, {alpha_high_too_low}") + result, error_message = sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + return_error_message=True, + ) + + assert result is False, "Able to set incorrect alpha_high value" + assert error_message["name"] == "AlphaHighTooLow" + + # 2. Test setting Alpha_high too high + alpha_high_too_high = u16_max + 1 # One more than the max acceptable value + call_params = liquid_alpha_call_params(netuid, f"6553, {alpha_high_too_high}") + try: + result, error_message = sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + return_error_message=True, + ) + except Exception as e: + assert str(e) == "65536 out of range for u16", f"Unexpected error: {e}" + + # Testing alpha low upper and lower bounds + + # 1. Test setting Alpha_low too low + alpha_low_too_low = 0 + call_params = liquid_alpha_call_params(netuid, f"{alpha_low_too_low}, 53083") + result, error_message = sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + return_error_message=True, + ) + assert result is False, "Able to set incorrect alpha_low value" + assert error_message["name"] == "AlphaLowOutOfRange" + + # 2. Test setting Alpha_low too high + alpha_low_too_high = ( + u16_max * 4 // 5 + ) + 1 # One more than the maximum acceptable value + call_params = liquid_alpha_call_params(netuid, f"{alpha_low_too_high}, 53083") + result, error_message = sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + return_error_message=True, + ) + assert result is False, "Able to set incorrect alpha_low value" + assert error_message["name"] == "AlphaLowOutOfRange" + + # Setting normal alpha values + alpha_values = "6553, 53083" + call_params = liquid_alpha_call_params(netuid, alpha_values) + assert sudo_set_hyperparameter_values( + local_chain, + alice_wallet, + call_function="sudo_set_alpha_values", + call_params=call_params, + ), "Unable to set liquid alpha values" + + assert ( + subtensor.get_subnet_hyperparameters(netuid=1).alpha_high == 53083 + ), "Failed to set alpha high" + assert ( + subtensor.get_subnet_hyperparameters(netuid=1).alpha_low == 6553 + ), "Failed to set alpha low" + + # Disable Liquid Alpha + assert sudo_set_hyperparameter_bool( + local_chain, alice_wallet, "sudo_set_liquid_alpha_enabled", False, netuid + ), "Unable to disable liquid alpha" + + assert ( + subtensor.get_subnet_hyperparameters(netuid=1).liquid_alpha_enabled is False + ), "Failed to disable liquid alpha" + logging.info("✅ Passed test_liquid_alpha") diff --git a/tests/e2e_tests/test_metagraph.py b/tests/e2e_tests/test_metagraph.py new file mode 100644 index 0000000000..ff16dde369 --- /dev/null +++ b/tests/e2e_tests/test_metagraph.py @@ -0,0 +1,177 @@ +import time + +import bittensor +from bittensor import logging +from tests.e2e_tests.utils.chain_interactions import ( + add_stake, + register_neuron, + register_subnet, +) +from tests.e2e_tests.utils.e2e_test_utils import ( + setup_wallet, +) + + +def neuron_to_dict(neuron): + """ + Convert a neuron object to a dictionary, excluding private attributes, methods, and specific fields. + Returns: + dict: A dictionary of the neuron's public attributes. + + Note: + Excludes 'weights' and 'bonds' fields. These are present in subtensor + but not in metagraph + """ + excluded_fields = {"weights", "bonds"} + return { + attr: getattr(neuron, attr) + for attr in dir(neuron) + if not attr.startswith("_") + and not callable(getattr(neuron, attr)) + and attr not in excluded_fields + } + + +def test_metagraph(local_chain): + """ + Tests the metagraph + + Steps: + 1. Register a subnet through Alice + 2. Assert metagraph's initial state + 3. Register Bob and validate info in metagraph + 4. Fetch neuron info of Bob through subtensor & metagraph and verify + 5. Register Dave and validate info in metagraph + 6. Verify low balance stake fails & add stake thru Bob and verify + 7. Load pre_dave metagraph from latest save and verify both instances + Raises: + AssertionError: If any of the checks or verifications fail + """ + logging.info("Testing test_metagraph_command") + netuid = 1 + + # Register Alice, Bob, and Dave + alice_keypair, alice_wallet = setup_wallet("//Alice") + bob_keypair, bob_wallet = setup_wallet("//Bob") + dave_keypair, dave_wallet = setup_wallet("//Dave") + + # Register the subnet through Alice + register_subnet(local_chain, alice_wallet), "Unable to register the subnet" + + # Verify subnet was created successfully + assert local_chain.query( + "SubtensorModule", "NetworksAdded", [1] + ).serialize(), "Subnet wasn't created successfully" + + # Initialize metagraph + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + metagraph = subtensor.metagraph(netuid=1) + + # Assert metagraph is empty + assert len(metagraph.uids) == 0, "Metagraph is not empty" + + # Register Bob to the subnet + assert register_neuron( + local_chain, bob_wallet, netuid + ), "Unable to register Bob as a neuron" + + # Refresh the metagraph + metagraph.sync(subtensor=subtensor) + + # Assert metagraph has Bob neuron + assert len(metagraph.uids) == 1, "Metagraph doesn't have exactly 1 neuron" + assert ( + metagraph.hotkeys[0] == bob_keypair.ss58_address + ), "Bob's hotkey doesn't match in metagraph" + assert len(metagraph.coldkeys) == 1, "Metagraph doesn't have exactly 1 coldkey" + assert metagraph.n.max() == 1, "Metagraph's max n is not 1" + assert metagraph.n.min() == 1, "Metagraph's min n is not 1" + assert len(metagraph.addresses) == 1, "Metagraph doesn't have exactly 1 address" + + # Fetch UID of Bob + uid = subtensor.get_uid_for_hotkey_on_subnet( + bob_keypair.ss58_address, netuid=netuid + ) + + # Fetch neuron info of Bob through subtensor and metagraph + neuron_info_bob = subtensor.neuron_for_uid(uid, netuid=netuid) + metagraph_dict = neuron_to_dict(metagraph.neurons[uid]) + subtensor_dict = neuron_to_dict(neuron_info_bob) + + # Verify neuron info is the same in both objects + assert ( + metagraph_dict == subtensor_dict + ), "Neuron info of Bob doesn't match b/w metagraph & subtensor" + + # Create pre_dave metagraph for future verifications + metagraph_pre_dave = subtensor.metagraph(netuid=1) + + # Register Dave as a neuron + assert register_neuron( + local_chain, dave_wallet, netuid + ), "Unable to register Dave as a neuron" + + metagraph.sync(subtensor=subtensor) + + # Assert metagraph now includes Dave's neuron + assert ( + len(metagraph.uids) == 2 + ), "Metagraph doesn't have exactly 2 neurons post Dave" + assert ( + metagraph.hotkeys[1] == dave_keypair.ss58_address + ), "Neuron's hotkey in metagraph doesn't match" + assert ( + len(metagraph.coldkeys) == 2 + ), "Metagraph doesn't have exactly 2 coldkeys post Dave" + assert metagraph.n.max() == 2, "Metagraph's max n is not 2 post Dave" + assert metagraph.n.min() == 2, "Metagraph's min n is not 2 post Dave" + assert len(metagraph.addresses) == 2, "Metagraph doesn't have 2 addresses post Dave" + + # Test staking with low balance + assert not add_stake( + local_chain, dave_wallet, bittensor.Balance.from_tao(10_000) + ), "Low balance stake should fail" + + # Add stake by Bob + assert add_stake( + local_chain, bob_wallet, bittensor.Balance.from_tao(10_000) + ), "Failed to add stake for Bob" + + # Assert stake is added after updating metagraph + metagraph.sync(subtensor=subtensor) + assert metagraph.neurons[0].stake == bittensor.Balance.from_tao( + 10_000 + ), "Bob's stake not updated in metagraph" + + # Test the save() and load() mechanism + # We save the metagraph and pre_dave loads it + metagraph.save() + time.sleep(3) + metagraph_pre_dave.load() + + # Ensure data is synced between two metagraphs + assert len(metagraph.uids) == len( + metagraph_pre_dave.uids + ), "UID count mismatch after save and load" + assert ( + metagraph.uids == metagraph_pre_dave.uids + ).all(), "UIDs don't match after save and load" + + assert len(metagraph.axons) == len( + metagraph_pre_dave.axons + ), "Axon count mismatch after save and load" + assert ( + metagraph.axons[1].hotkey == metagraph_pre_dave.axons[1].hotkey + ), "Axon hotkey mismatch after save and load" + assert ( + metagraph.axons == metagraph_pre_dave.axons + ), "Axons don't match after save and load" + + assert len(metagraph.neurons) == len( + metagraph_pre_dave.neurons + ), "Neuron count mismatch after save and load" + assert ( + metagraph.neurons == metagraph_pre_dave.neurons + ), "Neurons don't match after save and load" + + logging.info("✅ Passed test_metagraph") diff --git a/tests/e2e_tests/test_subtensor_functions.py b/tests/e2e_tests/test_subtensor_functions.py new file mode 100644 index 0000000000..32d0f6e14d --- /dev/null +++ b/tests/e2e_tests/test_subtensor_functions.py @@ -0,0 +1,152 @@ +import asyncio +import sys + +import pytest + +import bittensor +from bittensor import logging +from tests.e2e_tests.utils.chain_interactions import ( + register_neuron, + register_subnet, +) +from tests.e2e_tests.utils.e2e_test_utils import ( + setup_wallet, + template_path, + templates_repo, +) + + +@pytest.mark.asyncio +async def test_subtensor_extrinsics(local_chain): + """ + Tests subtensor extrinsics + + Steps: + 1. Validate subnets in the chain before/after registering netuid = 1 + 2. Register Alice's neuron + 3. Verify Alice and Bob's participation in subnets (individually and global) + 4. Verify uids of Alice and Bob gets populated correctly + 5. Start Alice as a validator and verify neuroninfo before/after is different + Raises: + AssertionError: If any of the checks or verifications fail + """ + netuid = 1 + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + + # Subnets 0 and 3 are bootstrapped from the start + assert subtensor.get_subnets() == [0, 3] + assert subtensor.get_total_subnets() == 2 + + # Add wallets for Alice and Bob + alice_keypair, alice_wallet = setup_wallet("//Alice") + bob_keypair, bob_wallet = setup_wallet("//Bob") + + # Register subnet + register_subnet(local_chain, alice_wallet), "Unable to register the subnet" + + # Subnet 1 is added after registration + assert subtensor.get_subnets() == [0, 1, 3] + assert subtensor.get_total_subnets() == 3 + + # Verify subnet 1 created successfully + assert local_chain.query("SubtensorModule", "NetworksAdded", [1]).serialize() + assert subtensor.subnet_exists(netuid) + + # Register Alice to the subnet + assert register_neuron( + local_chain, alice_wallet, netuid + ), "Unable to register Alice as a neuron" + + # Verify Alice is registered to netuid 1 and Bob isn't registered to any + assert subtensor.get_netuids_for_hotkey(hotkey_ss58=alice_keypair.ss58_address) == [ + 1 + ], "Alice is not registered to netuid 1 as expected" + assert ( + subtensor.get_netuids_for_hotkey(hotkey_ss58=bob_keypair.ss58_address) == [] + ), "Bob is unexpectedly registered to some netuid" + + # Verify Alice's hotkey is registered to any subnet (currently netuid = 1) + assert subtensor.is_hotkey_registered_any( + hotkey_ss58=alice_keypair.ss58_address + ), "Alice's hotkey is not registered to any subnet" + assert not subtensor.is_hotkey_registered_any( + hotkey_ss58=bob_keypair.ss58_address + ), "Bob's hotkey is unexpectedly registered to a subnet" + + # Verify netuid = 1 only has Alice registered and not Bob + assert subtensor.is_hotkey_registered_on_subnet( + netuid=netuid, hotkey_ss58=alice_keypair.ss58_address + ), "Alice's hotkey is not registered on netuid 1" + assert not subtensor.is_hotkey_registered_on_subnet( + netuid=netuid, hotkey_ss58=bob_keypair.ss58_address + ), "Bob's hotkey is unexpectedly registered on netuid 1" + + # Verify Alice's UID on netuid 1 is 0 + assert ( + subtensor.get_uid_for_hotkey_on_subnet( + hotkey_ss58=alice_keypair.ss58_address, netuid=netuid + ) + == 0 + ), "UID for Alice's hotkey on netuid 1 is not 0 as expected" + + # Register Bob to the subnet + assert register_neuron( + local_chain, bob_wallet, netuid + ), "Unable to register Alice as a neuron" + + # Verify Bob's UID on netuid 1 is 1 + assert ( + subtensor.get_uid_for_hotkey_on_subnet( + hotkey_ss58=bob_keypair.ss58_address, netuid=netuid + ) + == 1 + ), "UID for Bob's hotkey on netuid 1 is not 1 as expected" + + neuron_info_old = subtensor.get_neuron_for_pubkey_and_subnet( + alice_keypair.ss58_address, netuid=netuid + ) + + # Prepare to run Alice as validator + cmd = " ".join( + [ + f"{sys.executable}", + f'"{template_path}{templates_repo}/neurons/validator.py"', + "--no_prompt", + "--netuid", + str(netuid), + "--subtensor.network", + "local", + "--subtensor.chain_endpoint", + "ws://localhost:9945", + "--wallet.path", + alice_wallet.path, + "--wallet.name", + alice_wallet.name, + "--wallet.hotkey", + "default", + "--logging.trace", + ] + ) + + # Run Alice as validator in the background + await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + logging.info("Neuron Alice is now validating") + + await asyncio.sleep( + 5 + ) # wait for 5 seconds for the metagraph and subtensor to refresh with latest data + subtensor = bittensor.Subtensor(network="ws://localhost:9945") + + # Verify neuron info is updated after running as a validator + neuron_info = subtensor.get_neuron_for_pubkey_and_subnet( + alice_keypair.ss58_address, netuid=netuid + ) + assert ( + neuron_info_old.axon_info != neuron_info.axon_info + ), "Neuron info not updated after running validator" + + logging.info("✅ Passed test_subtensor_extrinsics") diff --git a/tests/e2e_tests/test_transfer.py b/tests/e2e_tests/test_transfer.py new file mode 100644 index 0000000000..b6be1cd6ae --- /dev/null +++ b/tests/e2e_tests/test_transfer.py @@ -0,0 +1,52 @@ +from bittensor import Subtensor, logging +from bittensor.core.subtensor import transfer_extrinsic +from tests.e2e_tests.utils.e2e_test_utils import setup_wallet + + +def test_transfer(local_chain): + """ + Test the transfer mechanism on the chain + + Steps: + 1. Create a wallet for Alice + 2. Calculate existing balance and transfer 2 Tao + 3. Calculate balance after extrinsic call and verify calculations + Raises: + AssertionError: If any of the checks or verifications fail + """ + + logging.info("Testing test_transfer") + + # Set up Alice wallet + keypair, wallet = setup_wallet("//Alice") + + # Account details before transfer + acc_before = local_chain.query("System", "Account", [keypair.ss58_address]) + + # Transfer Tao using extrinsic + subtensor = Subtensor(network="ws://localhost:9945") + transfer_extrinsic( + subtensor=subtensor, + wallet=wallet, + dest="5GpzQgpiAKHMWNSH3RN4GLf96GVTDct9QxYEFAY7LWcVzTbx", + amount=2, + wait_for_finalization=True, + wait_for_inclusion=True, + prompt=False, + ) + + # Account details after transfer + acc_after = local_chain.query("System", "Account", [keypair.ss58_address]) + + # Transfer calculation assertions + expected_transfer = 2_000_000_000 + tolerance = 200_000 # Tx fee tolerance + + actual_difference = ( + acc_before.value["data"]["free"] - acc_after.value["data"]["free"] + ) + assert ( + expected_transfer <= actual_difference <= expected_transfer + tolerance + ), f"Expected transfer with tolerance: {expected_transfer} <= {actual_difference} <= {expected_transfer + tolerance}" + + logging.info("✅ Passed test_transfer") diff --git a/tests/e2e_tests/utils/chain_interactions.py b/tests/e2e_tests/utils/chain_interactions.py new file mode 100644 index 0000000000..aad53812c8 --- /dev/null +++ b/tests/e2e_tests/utils/chain_interactions.py @@ -0,0 +1,186 @@ +""" +This module provides functions interacting with the chain for end-to-end testing; +these are not present in btsdk but are required for e2e tests +""" + +import asyncio +from typing import Union, Optional, TYPE_CHECKING + +from bittensor import logging + +# for typing purposes +if TYPE_CHECKING: + from bittensor import Wallet + from bittensor.core.subtensor import Subtensor + from bittensor.utils.balance import Balance + from substrateinterface import SubstrateInterface + + +def sudo_set_hyperparameter_bool( + substrate: "SubstrateInterface", + wallet: "Wallet", + call_function: str, + value: bool, + netuid: int, +) -> bool: + """ + Sets boolean hyperparameter value through AdminUtils. Mimics setting hyperparams + """ + call = substrate.compose_call( + call_module="AdminUtils", + call_function=call_function, + call_params={"netuid": netuid, "enabled": value}, + ) + extrinsic = substrate.create_signed_extrinsic(call=call, keypair=wallet.coldkey) + response = substrate.submit_extrinsic( + extrinsic, + wait_for_inclusion=True, + wait_for_finalization=True, + ) + response.process_events() + return response.is_success + + +def sudo_set_hyperparameter_values( + substrate: "SubstrateInterface", + wallet: "Wallet", + call_function: str, + call_params: dict, + return_error_message: bool = False, +) -> Union[bool, tuple[bool, Optional[str]]]: + """ + Sets liquid alpha values using AdminUtils. Mimics setting hyperparams + """ + call = substrate.compose_call( + call_module="AdminUtils", + call_function=call_function, + call_params=call_params, + ) + extrinsic = substrate.create_signed_extrinsic(call=call, keypair=wallet.coldkey) + response = substrate.submit_extrinsic( + extrinsic, + wait_for_inclusion=True, + wait_for_finalization=True, + ) + response.process_events() + + if return_error_message: + return response.is_success, response.error_message + + return response.is_success + + +def add_stake( + substrate: "SubstrateInterface", wallet: "Wallet", amount: "Balance" +) -> bool: + """ + Adds stake to a hotkey using SubtensorModule. Mimics command of adding stake + """ + stake_call = substrate.compose_call( + call_module="SubtensorModule", + call_function="add_stake", + call_params={"hotkey": wallet.hotkey.ss58_address, "amount_staked": amount.rao}, + ) + extrinsic = substrate.create_signed_extrinsic( + call=stake_call, keypair=wallet.coldkey + ) + response = substrate.submit_extrinsic( + extrinsic, wait_for_finalization=True, wait_for_inclusion=True + ) + response.process_events() + return response.is_success + + +def register_subnet(substrate: "SubstrateInterface", wallet: "Wallet") -> bool: + """ + Registers a subnet on the chain using wallet. Mimics register subnet command. + """ + register_call = substrate.compose_call( + call_module="SubtensorModule", + call_function="register_network", + call_params={"immunity_period": 0, "reg_allowed": True}, + ) + extrinsic = substrate.create_signed_extrinsic( + call=register_call, keypair=wallet.coldkey + ) + response = substrate.submit_extrinsic( + extrinsic, wait_for_finalization=True, wait_for_inclusion=True + ) + response.process_events() + return response.is_success + + +def register_neuron( + substrate: "SubstrateInterface", wallet: "Wallet", netuid: int +) -> bool: + """ + Registers a neuron on a subnet. Mimics subnet register command. + """ + neuron_register_call = substrate.compose_call( + call_module="SubtensorModule", + call_function="burned_register", + call_params={ + "netuid": netuid, + "hotkey": wallet.hotkey.ss58_address, + }, + ) + extrinsic = substrate.create_signed_extrinsic( + call=neuron_register_call, keypair=wallet.coldkey + ) + response = substrate.submit_extrinsic( + extrinsic, wait_for_finalization=True, wait_for_inclusion=True + ) + response.process_events() + return response.is_success + + +async def wait_epoch(subtensor: "Subtensor", netuid: int = 1): + """ + Waits for the next epoch to start on a specific subnet. + + Queries the tempo value from the Subtensor module and calculates the + interval based on the tempo. Then waits for the next epoch to start + by monitoring the current block number. + + Raises: + Exception: If the tempo cannot be determined from the chain. + """ + q_tempo = [ + v.value + for [k, v] in subtensor.query_map_subtensor("Tempo") + if k.value == netuid + ] + if len(q_tempo) == 0: + raise Exception("could not determine tempo") + tempo = q_tempo[0] + logging.info(f"tempo = {tempo}") + await wait_interval(tempo, subtensor, netuid) + + +async def wait_interval(tempo: int, subtensor: "Subtensor", netuid: int = 1): + """ + Waits until the next tempo interval starts for a specific subnet. + + Calculates the next tempo block start based on the current block number + and the provided tempo, then enters a loop where it periodically checks + the current block number until the next tempo interval starts. + """ + interval = tempo + 1 + current_block = subtensor.get_current_block() + last_epoch = current_block - 1 - (current_block + netuid + 1) % interval + next_tempo_block_start = last_epoch + interval + last_reported = None + + while current_block < next_tempo_block_start: + await asyncio.sleep( + 1 + ) # Wait for 1 second before checking the block number again + current_block = subtensor.get_current_block() + if last_reported is None or current_block - last_reported >= 10: + last_reported = current_block + print( + f"Current Block: {current_block} Next tempo for netuid {netuid} at: {next_tempo_block_start}" + ) + logging.info( + f"Current Block: {current_block} Next tempo for netuid {netuid} at: {next_tempo_block_start}" + ) diff --git a/tests/e2e_tests/utils/e2e_test_utils.py b/tests/e2e_tests/utils/e2e_test_utils.py new file mode 100644 index 0000000000..ba662647a4 --- /dev/null +++ b/tests/e2e_tests/utils/e2e_test_utils.py @@ -0,0 +1,83 @@ +import os +import shutil +import subprocess +import sys + +from substrateinterface import Keypair + +import bittensor + +template_path = os.getcwd() + "/neurons/" +templates_repo = "templates repository" + + +def setup_wallet(uri: str) -> tuple[Keypair, bittensor.Wallet]: + """ + Sets up a wallet using the provided URI. + + This function creates a keypair from the given URI and initializes a wallet + at a temporary path. It sets the coldkey, coldkeypub, and hotkey for the wallet + using the generated keypair. + + Side Effects: + - Creates a wallet in a temporary directory. + - Sets keys in the wallet without encryption and with overwriting enabled. + """ + keypair = Keypair.create_from_uri(uri) + wallet_path = f"/tmp/btcli-e2e-wallet-{uri.strip('/')}" + wallet = bittensor.Wallet(path=wallet_path) + wallet.set_coldkey(keypair=keypair, encrypt=False, overwrite=True) + wallet.set_coldkeypub(keypair=keypair, encrypt=False, overwrite=True) + wallet.set_hotkey(keypair=keypair, encrypt=False, overwrite=True) + return keypair, wallet + + +def clone_or_update_templates(specific_commit=None): + """ + Clones or updates the Bittensor subnet template repository. + + This function clones the Bittensor subnet template repository if it does not + already exist in the specified installation directory. If the repository already + exists, it updates it by pulling the latest changes. Optionally, it can check out + a specific commit if the `specific_commit` variable is set. + """ + install_dir = template_path + repo_mapping = { + templates_repo: "https://github.com/opentensor/bittensor-subnet-template.git", + } + + os.makedirs(install_dir, exist_ok=True) + os.chdir(install_dir) + + for repo, git_link in repo_mapping.items(): + if not os.path.exists(repo): + print(f"\033[94mCloning {repo}...\033[0m") + subprocess.run(["git", "clone", git_link, repo], check=True) + else: + print(f"\033[94mUpdating {repo}...\033[0m") + os.chdir(repo) + subprocess.run(["git", "pull"], check=True) + os.chdir("..") + + # For pulling specific commit versions of repo + if specific_commit: + os.chdir(templates_repo) + print( + f"\033[94mChecking out commit {specific_commit} in {templates_repo}...\033[0m" + ) + subprocess.run(["git", "checkout", specific_commit], check=True) + os.chdir("..") + + return install_dir + templates_repo + "/" + + +def install_templates(install_dir): + subprocess.check_call([sys.executable, "-m", "pip", "install", install_dir]) + + +def uninstall_templates(install_dir): + subprocess.check_call( + [sys.executable, "-m", "pip", "uninstall", "bittensor_subnet_template", "-y"] + ) + # Delete everything in directory + shutil.rmtree(install_dir) diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py new file mode 100644 index 0000000000..f876d249bd --- /dev/null +++ b/tests/helpers/__init__.py @@ -0,0 +1,34 @@ +# The MIT License (MIT) +# Copyright © 2023 Opentensor Technologies Inc + +# 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 +from .helpers import ( # noqa: F401 + CLOSE_IN_VALUE, + MockConsole, + __mock_wallet_factory__, +) +from bittensor_wallet.mock.wallet_mock import ( # noqa: F401 + get_mock_coldkey, + get_mock_hotkey, + get_mock_keypair, + get_mock_wallet, +) + + +def is_running_in_circleci(): + """Checks that tests are running in the app.circleci.com environment.""" + return os.getenv("CIRCLECI") == "true" diff --git a/tests/helpers/helpers.py b/tests/helpers/helpers.py new file mode 100644 index 0000000000..417bd643b3 --- /dev/null +++ b/tests/helpers/helpers.py @@ -0,0 +1,170 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from typing import Union + +from bittensor_wallet.mock.wallet_mock import MockWallet as _MockWallet +from bittensor_wallet.mock.wallet_mock import get_mock_coldkey +from bittensor_wallet.mock.wallet_mock import get_mock_hotkey +from bittensor_wallet.mock.wallet_mock import get_mock_wallet + +from rich.console import Console +from rich.text import Text + +from bittensor.utils.balance import Balance +from bittensor.core.chain_data import AxonInfo, NeuronInfo, PrometheusInfo + + +def __mock_wallet_factory__(*args, **kwargs) -> _MockWallet: + """Returns a mock wallet object.""" + + mock_wallet = get_mock_wallet() + + return mock_wallet + + +class CLOSE_IN_VALUE: + value: Union[float, int, Balance] + tolerance: Union[float, int, Balance] + + def __init__( + self, + value: Union[float, int, Balance], + tolerance: Union[float, int, Balance] = 0.0, + ) -> None: + self.value = value + self.tolerance = tolerance + + def __eq__(self, __o: Union[float, int, Balance]) -> bool: + # True if __o \in [value - tolerance, value + tolerance] + # or if value \in [__o - tolerance, __o + tolerance] + return ( + (self.value - self.tolerance) <= __o <= (self.value + self.tolerance) + ) or ((__o - self.tolerance) <= self.value <= (__o + self.tolerance)) + + +def get_mock_neuron(**kwargs) -> NeuronInfo: + """ + Returns a mock neuron with the given kwargs overriding the default values. + """ + + mock_neuron_d = dict( + { + "netuid": -1, # mock netuid + "axon_info": AxonInfo( + block=0, + version=1, + ip=0, + port=0, + ip_type=0, + protocol=0, + placeholder1=0, + placeholder2=0, + ), + "prometheus_info": PrometheusInfo( + block=0, version=1, ip=0, port=0, ip_type=0 + ), + "validator_permit": True, + "uid": 1, + "hotkey": "some_hotkey", + "coldkey": "some_coldkey", + "active": 0, + "last_update": 0, + "stake": {"some_coldkey": 1e12}, + "total_stake": 1e12, + "rank": 0.0, + "trust": 0.0, + "consensus": 0.0, + "validator_trust": 0.0, + "incentive": 0.0, + "dividends": 0.0, + "emission": 0.0, + "bonds": [], + "weights": [], + "stake_dict": {}, + "pruning_score": 0.0, + "is_null": False, + } + ) + + mock_neuron_d.update(kwargs) # update with kwargs + + if kwargs.get("stake") is None and kwargs.get("coldkey") is not None: + mock_neuron_d["stake"] = {kwargs.get("coldkey"): 1e12} + + if kwargs.get("total_stake") is None: + mock_neuron_d["total_stake"] = sum(mock_neuron_d["stake"].values()) + + mock_neuron = NeuronInfo._neuron_dict_to_namespace(mock_neuron_d) + + return mock_neuron + + +def get_mock_neuron_by_uid(uid: int, **kwargs) -> NeuronInfo: + return get_mock_neuron( + uid=uid, hotkey=get_mock_hotkey(uid), coldkey=get_mock_coldkey(uid), **kwargs + ) + + +class MockStatus: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + def start(self): + pass + + def stop(self): + pass + + def update(self, *args, **kwargs): + MockConsole().print(*args, **kwargs) + + +class MockConsole: + """ + Mocks the console object for status and print. + Captures the last print output as a string. + """ + + captured_print = None + + def status(self, *args, **kwargs): + return MockStatus() + + def print(self, *args, **kwargs): + console = Console( + width=1000, no_color=True, markup=False + ) # set width to 1000 to avoid truncation + console.begin_capture() + console.print(*args, **kwargs) + self.captured_print = console.end_capture() + + def clear(self, *args, **kwargs): + pass + + @staticmethod + def remove_rich_syntax(text: str) -> str: + """ + Removes rich syntax from the given text. + Removes markup and ansi syntax. + """ + output_no_syntax = Text.from_ansi(Text.from_markup(text).plain).plain + + return output_no_syntax diff --git a/tests/integration_tests/__init__.py b/tests/integration_tests/__init__.py new file mode 100644 index 0000000000..640a132503 --- /dev/null +++ b/tests/integration_tests/__init__.py @@ -0,0 +1,16 @@ +# The MIT License (MIT) +# Copyright © 2024 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. diff --git a/tests/integration_tests/test_metagraph_integration.py b/tests/integration_tests/test_metagraph_integration.py new file mode 100644 index 0000000000..34bf4f590e --- /dev/null +++ b/tests/integration_tests/test_metagraph_integration.py @@ -0,0 +1,110 @@ +# The MIT License (MIT) +# Copyright © 2024 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 bittensor +import torch +import os +from bittensor.utils.mock import MockSubtensor +from bittensor.core.metagraph import METAGRAPH_STATE_DICT_NDARRAY_KEYS, get_save_dir + +_subtensor_mock: MockSubtensor = MockSubtensor() + + +def setUpModule(): + _subtensor_mock.reset() + _subtensor_mock.create_subnet(netuid=3) + _subtensor_mock.set_difficulty(netuid=3, difficulty=0) # Set diff 0 + + +class TestMetagraph: + def setup_method(self): + self.sub = MockSubtensor() + self.metagraph = bittensor.Metagraph(netuid=3, network="mock", sync=False) + + def test_print_empty(self): + print(self.metagraph) + + def test_lite_sync(self): + self.metagraph.sync(lite=True, subtensor=self.sub) + + def test_full_sync(self): + self.metagraph.sync(lite=False, subtensor=self.sub) + + def test_sync_block_0(self): + self.metagraph.sync(lite=True, block=0, subtensor=self.sub) + + def test_load_sync_save(self): + self.metagraph.sync(lite=True, subtensor=self.sub) + self.metagraph.save() + self.metagraph.load() + self.metagraph.save() + + def test_load_sync_save_from_torch(self): + self.metagraph.sync(lite=True, subtensor=self.sub) + + def deprecated_save_torch(metagraph): + save_directory = get_save_dir(metagraph.network, metagraph.netuid) + os.makedirs(save_directory, exist_ok=True) + graph_filename = save_directory + f"/block-{metagraph.block.item()}.pt" + state_dict = metagraph.state_dict() + for key in METAGRAPH_STATE_DICT_NDARRAY_KEYS: + state_dict[key] = torch.nn.Parameter( + torch.tensor(state_dict[key]), requires_grad=False + ) + torch.save(state_dict, graph_filename) + + deprecated_save_torch(self.metagraph) + self.metagraph.load() + + def test_state_dict(self): + self.metagraph.load() + state = self.metagraph.state_dict() + assert "version" in state + assert "n" in state + assert "block" in state + assert "stake" in state + assert "total_stake" in state + assert "ranks" in state + assert "trust" in state + assert "consensus" in state + assert "validator_trust" in state + assert "incentive" in state + assert "emission" in state + assert "dividends" in state + assert "active" in state + assert "last_update" in state + assert "validator_permit" in state + assert "weights" in state + assert "bonds" in state + assert "uids" in state + + def test_properties(self): + metagraph = self.metagraph + metagraph.hotkeys + metagraph.coldkeys + metagraph.addresses + metagraph.validator_trust + metagraph.S + metagraph.R + metagraph.I + metagraph.E + metagraph.C + metagraph.T + metagraph.Tv + metagraph.D + metagraph.B + metagraph.W diff --git a/tests/integration_tests/test_subtensor_integration.py b/tests/integration_tests/test_subtensor_integration.py new file mode 100644 index 0000000000..8539839ccc --- /dev/null +++ b/tests/integration_tests/test_subtensor_integration.py @@ -0,0 +1,250 @@ +# The MIT License (MIT) +# Copyright © 2024 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 unittest +from unittest.mock import MagicMock, patch + +from substrateinterface import Keypair + +import bittensor +from bittensor.core import settings +from bittensor.utils.balance import Balance +from bittensor.utils.mock import MockSubtensor +from tests.helpers import ( + get_mock_coldkey, + MockConsole, + get_mock_keypair, + get_mock_wallet, +) +from bittensor.core.extrinsics import transfer + + +class TestSubtensor(unittest.TestCase): + _mock_console_patcher = None + _mock_subtensor: MockSubtensor + subtensor: MockSubtensor + + def setUp(self): + self.wallet = get_mock_wallet( + hotkey=get_mock_keypair(0, self.id()), + coldkey=get_mock_keypair(1, self.id()), + ) + self.balance = Balance.from_tao(1000) + self.mock_neuron = MagicMock() # NOTE: this might need more sophistication + self.subtensor = MockSubtensor() # own instance per test + + @classmethod + def setUpClass(cls) -> None: + # mock rich console status + mock_console = MockConsole() + cls._mock_console_patcher = patch( + "bittensor.core.settings.bt_console", mock_console + ) + cls._mock_console_patcher.start() + # Keeps the same mock network for all tests. This stops the network from being re-setup for each test. + cls._mock_subtensor = MockSubtensor() + cls._do_setup_subnet() + + @classmethod + def _do_setup_subnet(cls): + # reset the mock subtensor + cls._mock_subtensor.reset() + # Setup the mock subnet 3 + cls._mock_subtensor.create_subnet(netuid=3) + + @classmethod + def tearDownClass(cls) -> None: + cls._mock_console_patcher.stop() + + def test_network_overrides(self): + """Tests that the network overrides the chain_endpoint.""" + # Argument importance: chain_endpoint (arg) > network (arg) > config.subtensor.chain_endpoint > config.subtensor.network + config0 = bittensor.Subtensor.config() + config0.subtensor.network = "finney" + config0.subtensor.chain_endpoint = "wss://finney.subtensor.io" # Should not match bittensor.core.settings.FINNEY_ENTRYPOINT + assert config0.subtensor.chain_endpoint != settings.FINNEY_ENTRYPOINT + + config1 = bittensor.Subtensor.config() + config1.subtensor.network = "local" + config1.subtensor.chain_endpoint = None + + # Mock network calls + with patch("substrateinterface.SubstrateInterface.connect_websocket"): + with patch("substrateinterface.SubstrateInterface.reload_type_registry"): + print(bittensor.Subtensor, type(bittensor.Subtensor)) + # Choose network arg over config + sub1 = bittensor.Subtensor(config=config1, network="local") + self.assertEqual( + sub1.chain_endpoint, + settings.LOCAL_ENTRYPOINT, + msg="Explicit network arg should override config.network", + ) + + # Choose network config over chain_endpoint config + sub2 = bittensor.Subtensor(config=config0) + self.assertNotEqual( + sub2.chain_endpoint, + settings.FINNEY_ENTRYPOINT, # Here we expect the endpoint corresponding to the network "finney" + msg="config.network should override config.chain_endpoint", + ) + + sub3 = bittensor.Subtensor(config=config1) + # Should pick local instead of finney (default) + assert sub3.network == "local" + assert sub3.chain_endpoint == settings.LOCAL_ENTRYPOINT + + def test_get_current_block(self): + block = self.subtensor.get_current_block() + assert type(block) is int + + def test_do_block_step(self): + self.subtensor.do_block_step() + block = self.subtensor.get_current_block() + assert type(block) is int + + def test_do_block_step_query_previous_block(self): + self.subtensor.do_block_step() + block = self.subtensor.get_current_block() + self.subtensor.query_subtensor("NetworksAdded", block) + + def test_transfer(self): + fake_coldkey = get_mock_coldkey(1) + + transfer.do_transfer = MagicMock(return_value=(True, "0x", None)) + self.subtensor.get_neuron_for_pubkey_and_subnet = MagicMock( + return_value=self.mock_neuron + ) + self.subtensor.get_balance = MagicMock(return_value=self.balance) + success = self.subtensor.transfer( + self.wallet, + fake_coldkey, + amount=200, + ) + self.assertTrue(success, msg="Transfer should succeed") + + def test_transfer_inclusion(self): + fake_coldkey = get_mock_coldkey(1) + transfer.do_transfer = MagicMock(return_value=(True, "0x", None)) + self.subtensor.get_neuron_for_pubkey_and_subnet = MagicMock( + return_value=self.mock_neuron + ) + self.subtensor.get_balance = MagicMock(return_value=self.balance) + + success = self.subtensor.transfer( + self.wallet, fake_coldkey, amount=200, wait_for_inclusion=True + ) + self.assertTrue(success, msg="Transfer should succeed") + + def test_transfer_failed(self): + fake_coldkey = get_mock_coldkey(1) + transfer.do_transfer = MagicMock( + return_value=(False, None, "Mock failure message") + ) + + fail = self.subtensor.transfer( + self.wallet, fake_coldkey, amount=200, wait_for_inclusion=True + ) + self.assertFalse(fail, msg="Transfer should fail") + + def test_transfer_invalid_dest(self): + fake_coldkey = get_mock_coldkey(1) + + fail = self.subtensor.transfer( + self.wallet, + fake_coldkey[:-1], # invalid dest + amount=200, + wait_for_inclusion=True, + ) + self.assertFalse(fail, msg="Transfer should fail because of invalid dest") + + def test_transfer_dest_as_bytes(self): + fake_coldkey = get_mock_coldkey(1) + with patch( + "bittensor.core.extrinsics.transfer.do_transfer", + return_value=(True, "0x", None), + ): + self.subtensor.get_neuron_for_pubkey_and_subnet = MagicMock( + return_value=self.mock_neuron + ) + self.subtensor.get_balance = MagicMock(return_value=self.balance) + + dest_as_bytes: bytes = Keypair(fake_coldkey).public_key + success = self.subtensor.transfer( + self.wallet, + dest_as_bytes, # invalid dest + amount=200, + wait_for_inclusion=True, + ) + self.assertTrue(success, msg="Transfer should succeed") + + def test_set_weights(self): + chain_weights = [0] + + self.subtensor.set_weights = MagicMock(return_value=True) + self.subtensor.do_set_weights = MagicMock(return_value=(True, None)) + + success = self.subtensor.set_weights( + wallet=self.wallet, + netuid=3, + uids=[1], + weights=chain_weights, + ) + assert success is True + + def test_set_weights_inclusion(self): + chain_weights = [0] + self.subtensor.do_set_weights = MagicMock(return_value=(True, None)) + self.subtensor.set_weights = MagicMock(return_value=True) + + success = self.subtensor.set_weights( + wallet=self.wallet, + netuid=1, + uids=[1], + weights=chain_weights, + wait_for_inclusion=True, + ) + assert success is True + + def test_set_weights_failed(self): + chain_weights = [0] + self.subtensor.do_set_weights = MagicMock( + return_value=(False, "Mock failure message") + ) + self.subtensor.set_weights = MagicMock(return_value=False) + + fail = self.subtensor.set_weights( + wallet=self.wallet, + netuid=3, + uids=[1], + weights=chain_weights, + wait_for_inclusion=True, + ) + assert fail is False + + def test_get_balance(self): + fake_coldkey = get_mock_coldkey(0) + balance = self.subtensor.get_balance(address=fake_coldkey) + assert type(balance) is bittensor.utils.balance.Balance + + def test_defaults_to_finney(self): + sub = bittensor.Subtensor() + assert sub.network == "finney" + assert sub.chain_endpoint == settings.FINNEY_ENTRYPOINT + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pytest.ini b/tests/pytest.ini new file mode 100644 index 0000000000..17ba4b865d --- /dev/null +++ b/tests/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +filterwarnings = + ignore::DeprecationWarning:pkg_resources.*: \ No newline at end of file diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py new file mode 100644 index 0000000000..a5503f8961 --- /dev/null +++ b/tests/unit_tests/conftest.py @@ -0,0 +1,13 @@ +import pytest +from aioresponses import aioresponses + + +@pytest.fixture +def force_legacy_torch_compatible_api(monkeypatch): + monkeypatch.setenv("USE_TORCH", "1") + + +@pytest.fixture +def mock_aio_response(): + with aioresponses() as m: + yield m diff --git a/tests/unit_tests/extrinsics/test_commit_weights.py b/tests/unit_tests/extrinsics/test_commit_weights.py new file mode 100644 index 0000000000..35a1d4d426 --- /dev/null +++ b/tests/unit_tests/extrinsics/test_commit_weights.py @@ -0,0 +1,133 @@ +import pytest + +from bittensor.core import subtensor as subtensor_module +from bittensor.core.settings import version_as_int +from bittensor.core.subtensor import Subtensor +from bittensor.core.extrinsics.commit_weights import ( + do_commit_weights, + do_reveal_weights, +) + + +@pytest.fixture +def subtensor(mocker): + fake_substrate = mocker.MagicMock() + fake_substrate.websocket.sock.getsockopt.return_value = 0 + mocker.patch.object( + subtensor_module, "SubstrateInterface", return_value=fake_substrate + ) + return Subtensor() + + +def test_do_commit_weights(subtensor, mocker): + """Successful _do_commit_weights call.""" + # Preps + fake_wallet = mocker.MagicMock() + netuid = 1 + commit_hash = "fake_commit_hash" + wait_for_inclusion = True + wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = None + + mocked_format_error_message = mocker.MagicMock() + subtensor_module.format_error_message = mocked_format_error_message + + # Call + result = do_commit_weights( + self=subtensor, + wallet=fake_wallet, + netuid=netuid, + commit_hash=commit_hash, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Assertions + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="commit_weights", + call_params={ + "netuid": netuid, + "commit_hash": commit_hash, + }, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, keypair=fake_wallet.hotkey + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + + assert result == ( + False, + subtensor.substrate.submit_extrinsic.return_value.error_message, + ) + + +def test_do_reveal_weights(subtensor, mocker): + """Verifies that the `_do_reveal_weights` method interacts with the right substrate methods.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_wallet.hotkey = "hotkey" + + netuid = 1 + uids = [1, 2, 3, 4] + values = [1, 2, 3, 4] + salt = [4, 2, 2, 1] + wait_for_inclusion = True + wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = None + + mocked_format_error_message = mocker.MagicMock() + subtensor_module.format_error_message = mocked_format_error_message + + # Call + result = do_reveal_weights( + self=subtensor, + wallet=fake_wallet, + netuid=netuid, + uids=uids, + values=values, + salt=salt, + version_key=version_as_int, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="reveal_weights", + call_params={ + "netuid": netuid, + "uids": uids, + "values": values, + "salt": salt, + "version_key": version_as_int, + }, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, keypair=fake_wallet.hotkey + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + + assert result == ( + False, + subtensor.substrate.submit_extrinsic.return_value.error_message, + ) diff --git a/tests/unit_tests/extrinsics/test_init.py b/tests/unit_tests/extrinsics/test_init.py new file mode 100644 index 0000000000..8a2480a9b9 --- /dev/null +++ b/tests/unit_tests/extrinsics/test_init.py @@ -0,0 +1,114 @@ +"""Tests for bittensor/extrinsics/__ini__ module.""" + +from bittensor.utils import format_error_message + + +def test_format_error_message_with_right_error_message(): + """Verify that error message from extrinsic response parses correctly.""" + # Prep + fake_error_message = { + "type": "SomeType", + "name": "SomeErrorName", + "docs": ["Some error description."], + } + + # Call + result = format_error_message(fake_error_message) + + # Assertions + + assert "SomeType" in result + assert "SomeErrorName" in result + assert "Some error description." in result + + +def test_format_error_message_with_empty_error_message(): + """Verify that empty error message from extrinsic response parses correctly.""" + # Prep + fake_error_message = {} + + # Call + result = format_error_message(fake_error_message) + + # Assertions + + assert "UnknownType" in result + assert "UnknownError" in result + assert "Unknown Description" in result + + +def test_format_error_message_with_wrong_type_error_message(): + """Verify that error message from extrinsic response with wrong type parses correctly.""" + # Prep + fake_error_message = None + + # Call + result = format_error_message(fake_error_message) + + # Assertions + + assert "UnknownType" in result + assert "UnknownError" in result + assert "Unknown Description" in result + + +def test_format_error_message_with_custom_error_message_with_index(mocker): + """Tests error formatter if subtensor error is custom error with index.""" + # Preps + fake_custom_error = { + "code": 1010, + "message": "SomeErrorName", + "data": "Custom error: 1", + } + fake_subtensor_error = { + "docs": ["Some description"], + "fields": [], + "index": 1, + "name": "SomeErrorName", + } + + fake_substrate = mocker.MagicMock() + fake_substrate.metadata.get_metadata_pallet().errors.__getitem__().value.get = ( + mocker.Mock( + side_effect=[fake_custom_error["message"], fake_subtensor_error["docs"]] + ) + ) + + mocker.patch( + "substrateinterface.base.SubstrateInterface", return_value=fake_substrate + ) + + # Call + result = format_error_message(fake_custom_error, fake_substrate) + + # Assertions + assert ( + result + == f"Subtensor returned `SubstrateRequestException({fake_subtensor_error['name']})` error. This means: `Some description`." + ) + + +def test_format_error_message_with_custom_error_message_without_index(mocker): + """Tests error formatter if subtensor error is custom error without index.""" + # Preps + fake_custom_error = { + "code": 1010, + "message": "SomeErrorType", + "data": "Custom error description", + } + fake_substrate = mocker.MagicMock() + fake_substrate.metadata.get_metadata_pallet().errors.__getitem__().value.get.return_value = fake_custom_error[ + "message" + ] + mocker.patch( + "substrateinterface.base.SubstrateInterface", return_value=fake_substrate + ) + + # Call + result = format_error_message(fake_custom_error, fake_substrate) + + # Assertions + assert ( + result + == f"Subtensor returned `SubstrateRequestException({fake_custom_error['message']})` error. This means: `{fake_custom_error['data']}`." + ) diff --git a/tests/unit_tests/extrinsics/test_prometheus.py b/tests/unit_tests/extrinsics/test_prometheus.py new file mode 100644 index 0000000000..dbcfed1e47 --- /dev/null +++ b/tests/unit_tests/extrinsics/test_prometheus.py @@ -0,0 +1,167 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from unittest.mock import MagicMock, patch + +import pytest +from bittensor_wallet import Wallet + +from bittensor.core.extrinsics.prometheus import ( + prometheus_extrinsic, +) +from bittensor.core.subtensor import Subtensor +from bittensor.core.settings import version_as_int + + +# Mocking the bittensor and networking modules +@pytest.fixture +def mock_bittensor(): + with patch("bittensor.core.subtensor.Subtensor") as mock: + yield mock + + +@pytest.fixture +def mock_wallet(): + with patch("bittensor_wallet.Wallet") as mock: + yield mock + + +@pytest.fixture +def mock_net(): + with patch("bittensor.utils.networking") as mock: + yield mock + + +@pytest.mark.parametrize( + "ip, port, netuid, wait_for_inclusion, wait_for_finalization, expected_result, test_id", + [ + (None, 9221, 0, False, True, True, "happy-path-default-ip"), + ("192.168.0.1", 9221, 0, False, True, True, "happy-path-custom-ip"), + (None, 9221, 0, True, False, True, "happy-path-wait-for-inclusion"), + (None, 9221, 0, False, False, True, "happy-path-no-waiting"), + ], +) +def test_prometheus_extrinsic_happy_path( + mock_bittensor, + mock_wallet, + mock_net, + ip, + port, + netuid, + wait_for_inclusion, + wait_for_finalization, + expected_result, + test_id, +): + # Arrange + subtensor = MagicMock(spec=Subtensor) + subtensor.network = "test_network" + subtensor.substrate = MagicMock() + wallet = MagicMock(spec=Wallet) + mock_net.get_external_ip.return_value = "192.168.0.1" + mock_net.ip_to_int.return_value = 3232235521 # IP in integer form + mock_net.ip_version.return_value = 4 + neuron = MagicMock() + neuron.is_null = False + neuron.prometheus_info.version = version_as_int + neuron.prometheus_info.ip = 3232235521 + neuron.prometheus_info.port = port + neuron.prometheus_info.ip_type = 4 + subtensor.get_neuron_for_pubkey_and_subnet.return_value = neuron + subtensor._do_serve_prometheus.return_value = (True, None) + + # Act + result = prometheus_extrinsic( + subtensor=subtensor, + wallet=wallet, + ip=ip, + port=port, + netuid=netuid, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Assert + assert result == expected_result, f"Test ID: {test_id}" + + +# Edge cases +@pytest.mark.parametrize( + "ip, port, netuid, test_id", + [ + ("0.0.0.0", 0, 0, "edge-case-min-values"), + ("255.255.255.255", 65535, 2147483647, "edge-case-max-values"), + ], +) +def test_prometheus_extrinsic_edge_cases( + mock_bittensor, mock_wallet, mock_net, ip, port, netuid, test_id +): + # Arrange + subtensor = MagicMock(spec=Subtensor) + subtensor.network = "test_network" + subtensor.substrate = MagicMock() + wallet = MagicMock(spec=Wallet) + mock_net.get_external_ip.return_value = ip + mock_net.ip_to_int.return_value = 3232235521 # IP in integer form + mock_net.ip_version.return_value = 4 + neuron = MagicMock() + neuron.is_null = True + subtensor.get_neuron_for_pubkey_and_subnet.return_value = neuron + subtensor._do_serve_prometheus.return_value = (True, None) + + # Act + result = prometheus_extrinsic( + subtensor=subtensor, + wallet=wallet, + ip=ip, + port=port, + netuid=netuid, + wait_for_inclusion=False, + wait_for_finalization=True, + ) + + # Assert + assert result is True, f"Test ID: {test_id}" + + +# Error cases +def test_prometheus_extrinsic_error_cases(mock_bittensor, mock_wallet, mocker): + # Arrange + subtensor = MagicMock(spec=Subtensor) + subtensor.network = "test_network" + subtensor.substrate = MagicMock() + subtensor.substrate.websocket.sock.getsockopt.return_value = 0 + wallet = MagicMock(spec=Wallet) + neuron = MagicMock() + neuron.is_null = True + subtensor.get_neuron_for_pubkey_and_subnet.return_value = neuron + subtensor._do_serve_prometheus.return_value = (True,) + + with mocker.patch( + "bittensor.utils.networking.get_external_ip", side_effect=RuntimeError + ): + # Act & Assert + with pytest.raises(RuntimeError): + prometheus_extrinsic( + subtensor=subtensor, + wallet=wallet, + ip=None, + port=9221, + netuid=1, + wait_for_inclusion=False, + wait_for_finalization=True, + ) diff --git a/tests/unit_tests/extrinsics/test_serving.py b/tests/unit_tests/extrinsics/test_serving.py new file mode 100644 index 0000000000..a57e32d01c --- /dev/null +++ b/tests/unit_tests/extrinsics/test_serving.py @@ -0,0 +1,401 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from unittest.mock import MagicMock, patch + +import pytest +from bittensor_wallet import Wallet + +from bittensor.core.axon import Axon +from bittensor.core.subtensor import Subtensor +from bittensor.core.extrinsics import serving + + +@pytest.fixture +def mock_subtensor(mocker): + mock_subtensor = mocker.MagicMock(spec=Subtensor) + mock_subtensor.network = "test_network" + mock_subtensor.substrate = mocker.MagicMock() + return mock_subtensor + + +@pytest.fixture +def mock_wallet(mocker): + wallet = mocker.MagicMock(spec=Wallet) + wallet.hotkey.ss58_address = "hotkey_address" + wallet.coldkeypub.ss58_address = "coldkey_address" + return wallet + + +@pytest.fixture +def mock_axon(mock_wallet, mocker): + axon = mocker.MagicMock(spec=Axon) + axon.wallet = mock_wallet() + axon.external_port = 9221 + return axon + + +@pytest.mark.parametrize( + "ip,port,protocol,netuid,placeholder1,placeholder2,wait_for_inclusion,wait_for_finalization,prompt,expected,test_id,", + [ + ( + "192.168.1.1", + 9221, + 1, + 0, + 0, + 0, + False, + True, + False, + True, + "happy-path-no-wait", + ), + ( + "192.168.1.2", + 9222, + 2, + 1, + 1, + 1, + True, + False, + False, + True, + "happy-path-wait-for-inclusion", + ), + ( + "192.168.1.3", + 9223, + 3, + 2, + 2, + 2, + False, + True, + True, + True, + "happy-path-wait-for-finalization-and-prompt", + ), + ], + ids=[ + "happy-path-no-wait", + "happy-path-wait-for-inclusion", + "happy-path-wait-for-finalization-and-prompt", + ], +) +def test_serve_extrinsic_happy_path( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + expected, + test_id, + mocker, +): + # Arrange + serving.do_serve_axon = mocker.MagicMock(return_value=(True, "")) + with patch( + "bittensor.core.extrinsics.serving.Confirm.ask", + return_value=True, + ): + # Act + result = serving.serve_extrinsic( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + ) + + # Assert + assert result == expected, f"Test ID: {test_id}" + + +# Various edge cases +@pytest.mark.parametrize( + "ip,port,protocol,netuid,placeholder1,placeholder2,wait_for_inclusion,wait_for_finalization,prompt,expected,test_id,", + [ + ( + "192.168.1.4", + 9224, + 4, + 3, + 3, + 3, + True, + True, + False, + True, + "edge_case_max_values", + ), + ], + ids=["edge-case-max-values"], +) +def test_serve_extrinsic_edge_cases( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + expected, + test_id, + mocker, +): + # Arrange + serving.do_serve_axon = mocker.MagicMock(return_value=(True, "")) + with patch( + "bittensor.core.extrinsics.serving.Confirm.ask", + return_value=True, + ): + # Act + result = serving.serve_extrinsic( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + ) + + # Assert + assert result == expected, f"Test ID: {test_id}" + + +# Various error cases +@pytest.mark.parametrize( + "ip,port,protocol,netuid,placeholder1,placeholder2,wait_for_inclusion,wait_for_finalization,prompt,expected_error_message,test_id,", + [ + ( + "192.168.1.5", + 9225, + 5, + 4, + 4, + 4, + True, + True, + False, + False, + "error-case-failed-serve", + ), + ], + ids=["error-case-failed-serve"], +) +def test_serve_extrinsic_error_cases( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + expected_error_message, + test_id, + mocker, +): + # Arrange + serving.do_serve_axon = mocker.MagicMock(return_value=(False, "Error serving axon")) + with patch( + "bittensor.core.extrinsics.serving.Confirm.ask", + return_value=True, + ): + # Act + result = serving.serve_extrinsic( + mock_subtensor, + mock_wallet, + ip, + port, + protocol, + netuid, + placeholder1, + placeholder2, + wait_for_inclusion, + wait_for_finalization, + prompt, + ) + + # Assert + assert result == expected_error_message, f"Test ID: {test_id}" + + +@pytest.mark.parametrize( + "netuid, wait_for_inclusion, wait_for_finalization, prompt, external_ip, external_ip_success, serve_success, expected_result, test_id", + [ + # Happy path test + (1, False, True, False, "192.168.1.1", True, True, True, "happy-ext-ip"), + (1, False, True, True, None, True, True, True, "happy-net-external-ip"), + # Edge cases + (1, True, True, False, "192.168.1.1", True, True, True, "edge-case-wait"), + # Error cases + (1, False, True, False, None, False, True, False, "error-fetching-external-ip"), + ( + 1, + False, + True, + False, + "192.168.1.1", + True, + False, + False, + "error-serving-axon", + ), + ], + ids=[ + "happy-axon-external-ip", + "happy-net-external-ip", + "edge-case-wait", + "error-fetching-external-ip", + "error-serving-axon", + ], +) +def test_serve_axon_extrinsic( + mock_subtensor, + mock_axon, + netuid, + wait_for_inclusion, + wait_for_finalization, + prompt, + external_ip, + external_ip_success, + serve_success, + expected_result, + test_id, + mocker, +): + mock_axon.external_ip = external_ip + # Arrange + with patch( + "bittensor.utils.networking.get_external_ip", + side_effect=Exception("Failed to fetch IP") + if not external_ip_success + else MagicMock(return_value="192.168.1.1"), + ): + serving.do_serve_axon = mocker.MagicMock(return_value=(serve_success, "")) + # Act + if not external_ip_success: + with pytest.raises(RuntimeError): + serving.serve_axon_extrinsic( + mock_subtensor, + netuid, + mock_axon, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + else: + result = serving.serve_axon_extrinsic( + mock_subtensor, + netuid, + mock_axon, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Assert + assert result == expected_result, f"Test ID: {test_id}" + + +@pytest.mark.parametrize( + "wait_for_inclusion, wait_for_finalization, net_uid, type_u, data, response_success, expected_result, test_id", + [ + ( + True, + True, + 1, + "Sha256", + b"mock_bytes_data", + True, + True, + "happy-path-wait", + ), + ( + False, + False, + 1, + "Sha256", + b"mock_bytes_data", + True, + True, + "happy-path-no-wait", + ), + ], + ids=["happy-path-wait", "happy-path-no-wait"], +) +def test_publish_metadata( + mock_subtensor, + mock_wallet, + wait_for_inclusion, + wait_for_finalization, + net_uid, + type_u, + data, + response_success, + expected_result, + test_id, +): + # Arrange + with patch.object(mock_subtensor.substrate, "compose_call"), patch.object( + mock_subtensor.substrate, "create_signed_extrinsic" + ), patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock( + is_success=response_success, + process_events=MagicMock(), + error_message="error", + ), + ): + # Act + result = serving.publish_metadata( + self=mock_subtensor, + wallet=mock_wallet, + netuid=net_uid, + data_type=type_u, + data=data, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + # Assert + assert result == expected_result, f"Test ID: {test_id}" diff --git a/tests/unit_tests/extrinsics/test_set_weights.py b/tests/unit_tests/extrinsics/test_set_weights.py new file mode 100644 index 0000000000..9c32fc9bdf --- /dev/null +++ b/tests/unit_tests/extrinsics/test_set_weights.py @@ -0,0 +1,278 @@ +from unittest.mock import MagicMock, patch + +import pytest +import torch +from bittensor_wallet import Wallet + +from bittensor.core import subtensor as subtensor_module +from bittensor.core.extrinsics.set_weights import ( + do_set_weights, + set_weights_extrinsic, +) +from bittensor.core.settings import version_as_int +from bittensor.core.subtensor import Subtensor + + +@pytest.fixture +def mock_subtensor(): + mock = MagicMock(spec=Subtensor) + mock.network = "mock_network" + mock.substrate = MagicMock() + return mock + + +@pytest.fixture +def mock_wallet(): + mock = MagicMock(spec=Wallet) + return mock + + +@pytest.mark.parametrize( + "uids, weights, version_key, wait_for_inclusion, wait_for_finalization, prompt, user_accepts, expected_success, expected_message", + [ + ( + [1, 2], + [0.5, 0.5], + 0, + True, + False, + True, + True, + True, + "Successfully set weights and Finalized.", + ), + ( + [1, 2], + [0.5, 0.4], + 0, + False, + False, + False, + True, + True, + "Not waiting for finalization or inclusion.", + ), + ( + [1, 2], + [0.5, 0.5], + 0, + True, + False, + True, + True, + False, + "Subtensor returned `UnknownError(UnknownType)` error. This means: `Unknown Description`.", + ), + ([1, 2], [0.5, 0.5], 0, True, True, True, False, False, "Prompt refused."), + ], + ids=[ + "happy-flow", + "not-waiting-finalization-inclusion", + "error-flow", + "prompt-refused", + ], +) +def test_set_weights_extrinsic( + mock_subtensor, + mock_wallet, + uids, + weights, + version_key, + wait_for_inclusion, + wait_for_finalization, + prompt, + user_accepts, + expected_success, + expected_message, +): + uids_tensor = torch.tensor(uids, dtype=torch.int64) + weights_tensor = torch.tensor(weights, dtype=torch.float32) + with patch( + "bittensor.utils.weight_utils.convert_weights_and_uids_for_emit", + return_value=(uids_tensor, weights_tensor), + ), patch("rich.prompt.Confirm.ask", return_value=user_accepts), patch( + "bittensor.core.extrinsics.set_weights.do_set_weights", + return_value=(expected_success, "Mock error message"), + ) as mock_do_set_weights: + result, message = set_weights_extrinsic( + subtensor=mock_subtensor, + wallet=mock_wallet, + netuid=123, + uids=uids, + weights=weights, + version_key=version_key, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + ) + + assert result == expected_success, f"Test {expected_message} failed." + assert message == expected_message, f"Test {expected_message} failed." + if user_accepts is not False: + mock_do_set_weights.assert_called_once_with( + self=mock_subtensor, + wallet=mock_wallet, + netuid=123, + uids=uids_tensor, + vals=weights_tensor, + version_key=version_key, + wait_for_finalization=wait_for_finalization, + wait_for_inclusion=wait_for_inclusion, + ) + + +def test_do_set_weights_is_success(mock_subtensor, mocker): + """Successful _do_set_weights call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_uids = [1, 2, 3] + fake_vals = [4, 5, 6] + fake_netuid = 1 + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + mock_subtensor.substrate.submit_extrinsic.return_value.is_success = True + + # Call + result = do_set_weights( + self=mock_subtensor, + wallet=fake_wallet, + uids=fake_uids, + vals=fake_vals, + netuid=fake_netuid, + version_key=version_as_int, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + mock_subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="set_weights", + call_params={ + "dests": fake_uids, + "weights": fake_vals, + "netuid": fake_netuid, + "version_key": version_as_int, + }, + ) + + mock_subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=mock_subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + era={"period": 5}, + ) + + mock_subtensor.substrate.submit_extrinsic.assert_called_once_with( + mock_subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + mock_subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == (True, "Successfully set weights.") + + +def test_do_set_weights_is_not_success(mock_subtensor, mocker): + """Unsuccessful _do_set_weights call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_uids = [1, 2, 3] + fake_vals = [4, 5, 6] + fake_netuid = 1 + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + mock_subtensor.substrate.submit_extrinsic.return_value.is_success = False + mocked_format_error_message = mocker.MagicMock() + subtensor_module.format_error_message = mocked_format_error_message + + # Call + result = do_set_weights( + self=mock_subtensor, + wallet=fake_wallet, + uids=fake_uids, + vals=fake_vals, + netuid=fake_netuid, + version_key=version_as_int, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + mock_subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="set_weights", + call_params={ + "dests": fake_uids, + "weights": fake_vals, + "netuid": fake_netuid, + "version_key": version_as_int, + }, + ) + + mock_subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=mock_subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + era={"period": 5}, + ) + + mock_subtensor.substrate.submit_extrinsic.assert_called_once_with( + mock_subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + mock_subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == ( + False, + mock_subtensor.substrate.submit_extrinsic.return_value.error_message, + ) + + +def test_do_set_weights_no_waits(mock_subtensor, mocker): + """Successful _do_set_weights call without wait flags for fake_wait_for_inclusion and fake_wait_for_finalization.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_uids = [1, 2, 3] + fake_vals = [4, 5, 6] + fake_netuid = 1 + fake_wait_for_inclusion = False + fake_wait_for_finalization = False + + # Call + result = do_set_weights( + self=mock_subtensor, + wallet=fake_wallet, + uids=fake_uids, + vals=fake_vals, + netuid=fake_netuid, + version_key=version_as_int, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + mock_subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="set_weights", + call_params={ + "dests": fake_uids, + "weights": fake_vals, + "netuid": fake_netuid, + "version_key": version_as_int, + }, + ) + + mock_subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=mock_subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + era={"period": 5}, + ) + + mock_subtensor.substrate.submit_extrinsic.assert_called_once_with( + mock_subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + assert result == (True, "Not waiting for finalization or inclusion.") diff --git a/tests/unit_tests/extrinsics/test_transfer.py b/tests/unit_tests/extrinsics/test_transfer.py new file mode 100644 index 0000000000..af59d5769b --- /dev/null +++ b/tests/unit_tests/extrinsics/test_transfer.py @@ -0,0 +1,142 @@ +import pytest + +from bittensor.core import subtensor as subtensor_module +from bittensor.core.extrinsics.transfer import do_transfer +from bittensor.core.subtensor import Subtensor +from bittensor.utils.balance import Balance + + +@pytest.fixture +def subtensor(mocker): + fake_substrate = mocker.MagicMock() + fake_substrate.websocket.sock.getsockopt.return_value = 0 + mocker.patch.object( + subtensor_module, "SubstrateInterface", return_value=fake_substrate + ) + return Subtensor() + + +def test_do_transfer_is_success_true(subtensor, mocker): + """Successful do_transfer call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_dest = "SS58PUBLICKEY" + fake_transfer_balance = Balance(1) + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = True + + # Call + result = do_transfer( + subtensor, + fake_wallet, + fake_dest, + fake_transfer_balance, + fake_wait_for_inclusion, + fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": fake_dest, "value": fake_transfer_balance.rao}, + ) + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, keypair=fake_wallet.coldkey + ) + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == ( + True, + subtensor.substrate.submit_extrinsic.return_value.block_hash, + None, + ) + + +def test_do_transfer_is_success_false(subtensor, mocker): + """Successful do_transfer call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_dest = "SS58PUBLICKEY" + fake_transfer_balance = Balance(1) + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = False + + mocked_format_error_message = mocker.MagicMock() + subtensor_module.format_error_message = mocked_format_error_message + + # Call + result = do_transfer( + subtensor, + fake_wallet, + fake_dest, + fake_transfer_balance, + fake_wait_for_inclusion, + fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": fake_dest, "value": fake_transfer_balance.rao}, + ) + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, keypair=fake_wallet.coldkey + ) + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + + assert result == ( + False, + None, + subtensor.substrate.submit_extrinsic.return_value.error_message, + ) + + +def test_do_transfer_no_waits(subtensor, mocker): + """Successful do_transfer call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_dest = "SS58PUBLICKEY" + fake_transfer_balance = Balance(1) + fake_wait_for_inclusion = False + fake_wait_for_finalization = False + + # Call + result = do_transfer( + subtensor, + fake_wallet, + fake_dest, + fake_transfer_balance, + fake_wait_for_inclusion, + fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": fake_dest, "value": fake_transfer_balance.rao}, + ) + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, keypair=fake_wallet.coldkey + ) + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + assert result == (True, None, None) diff --git a/tests/unit_tests/factories/__init__.py b/tests/unit_tests/factories/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit_tests/factories/neuron_factory.py b/tests/unit_tests/factories/neuron_factory.py new file mode 100644 index 0000000000..f99a084acd --- /dev/null +++ b/tests/unit_tests/factories/neuron_factory.py @@ -0,0 +1,63 @@ +import factory + +from bittensor.core.chain_data import AxonInfo, NeuronInfoLite, PrometheusInfo +from bittensor.utils.balance import Balance + + +class BalanceFactory(factory.Factory): + class Meta: + model = Balance + + balance = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + + +class PrometheusInfoFactory(factory.Factory): + class Meta: + model = PrometheusInfo + + block = factory.Faker("random_int", min=0, max=100) + version = factory.Faker("random_int", min=0, max=100) + ip = factory.Faker("ipv4") + port = factory.Faker("random_int", min=0, max=100) + ip_type = factory.Faker("random_int", min=0, max=100) + + +class AxonInfoFactory(factory.Factory): + class Meta: + model = AxonInfo + + version = factory.Faker("random_int", min=0, max=100) + ip = factory.Faker("ipv4") + port = factory.Faker("random_int", min=0, max=100) + ip_type = factory.Faker("random_int", min=0, max=100) + hotkey = factory.Faker("uuid4") + coldkey = factory.Faker("uuid4") + + +class NeuronInfoLiteFactory(factory.Factory): + class Meta: + model = NeuronInfoLite + + hotkey = factory.Faker("uuid4") + coldkey = factory.Faker("uuid4") + uid = factory.Sequence(lambda n: n) + netuid = factory.Sequence(lambda n: n) + active = factory.Faker("random_int", min=0, max=1) + stake = factory.SubFactory(BalanceFactory) + stake_dict = factory.Dict({"balance": 10}) + total_stake = factory.SubFactory(BalanceFactory) + rank = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + emission = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + incentive = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + consensus = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + trust = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + validator_trust = factory.Faker( + "pyfloat", left_digits=3, right_digits=6, positive=True + ) + dividends = factory.Faker("pyfloat", left_digits=3, right_digits=6, positive=True) + last_update = factory.Faker("unix_time") + validator_permit = factory.Faker("boolean") + prometheus_info = factory.SubFactory(PrometheusInfoFactory) + axon_info = factory.SubFactory(AxonInfoFactory) + pruning_score = factory.Faker("random_int", min=0, max=100) + is_null = factory.Faker("boolean") diff --git a/tests/unit_tests/test_axon.py b/tests/unit_tests/test_axon.py new file mode 100644 index 0000000000..689d217379 --- /dev/null +++ b/tests/unit_tests/test_axon.py @@ -0,0 +1,781 @@ +# The MIT License (MIT) +# Copyright © 2024 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 re +import time +from dataclasses import dataclass +from typing import Any, Optional, Tuple +from unittest import IsolatedAsyncioTestCase +from unittest.mock import AsyncMock, MagicMock, patch + +import fastapi +import netaddr +import pydantic +import pytest +from fastapi.testclient import TestClient +from starlette.requests import Request + +from bittensor.core.axon import AxonMiddleware, Axon +from bittensor.core.errors import RunException +from bittensor.core.settings import version_as_int +from bittensor.core.stream import StreamingSynapse +from bittensor.core.synapse import Synapse +from bittensor.core.threadpool import PriorityThreadPoolExecutor +from bittensor.utils.axon_utils import ( + allowed_nonce_window_ns, + calculate_diff_seconds, + ALLOWED_DELTA, + NANOSECONDS_IN_SECOND, +) + + +def test_attach_initial(): + # Create a mock AxonServer instance + server = Axon() + + # Define the Synapse type + class TestSynapse(Synapse): + pass + + # Define the functions with the correct signatures + def forward_fn(synapse: TestSynapse) -> Any: + pass + + def blacklist_fn(synapse: TestSynapse) -> Tuple[bool, str]: + return True, "" + + def priority_fn(synapse: TestSynapse) -> float: + return 1.0 + + def verify_fn(synapse: TestSynapse) -> None: + pass + + # Test attaching with correct signatures + server.attach(forward_fn, blacklist_fn, priority_fn, verify_fn) + + # Define functions with incorrect signatures + def wrong_blacklist_fn(synapse: TestSynapse) -> int: + return 1 + + def wrong_priority_fn(synapse: TestSynapse) -> int: + return 1 + + def wrong_verify_fn(synapse: TestSynapse) -> bool: + return True + + # Test attaching with incorrect signatures + with pytest.raises(AssertionError): + server.attach(forward_fn, wrong_blacklist_fn, priority_fn, verify_fn) + + with pytest.raises(AssertionError): + server.attach(forward_fn, blacklist_fn, wrong_priority_fn, verify_fn) + + with pytest.raises(AssertionError): + server.attach(forward_fn, blacklist_fn, priority_fn, wrong_verify_fn) + + +def test_attach(): + # Create a mock AxonServer instance + server = Axon() + + # Define the Synapse type + class FakeSynapse: + pass + + # Define a class that inherits from Synapse + class InheritedSynapse(Synapse): + pass + + # Define a function with the correct signature + def forward_fn(synapse: InheritedSynapse) -> Any: + pass + + # Test attaching with correct signature and inherited class + server.attach(forward_fn) + + # Define a class that does not inherit from Synapse + class NonInheritedSynapse: + pass + + # Define a function with an argument of a class not inheriting from Synapse + def wrong_forward_fn(synapse: NonInheritedSynapse) -> Any: + pass + + # Test attaching with incorrect class inheritance + with pytest.raises(AssertionError): + server.attach(wrong_forward_fn) + + +def test_log_and_handle_error(): + from bittensor.core.axon import log_and_handle_error + + synapse = SynapseMock() + + synapse = log_and_handle_error(synapse, Exception("Error"), 500, 100) + assert synapse.axon.status_code == 500 + assert re.match(r"Internal Server Error #[\da-f\-]+", synapse.axon.status_message) + assert synapse.axon.process_time is not None + + +def test_create_error_response(): + from bittensor.core.axon import create_error_response + + synapse = SynapseMock() + synapse.axon.status_code = 500 + synapse.axon.status_message = "Error" + + response = create_error_response(synapse) + assert response.status_code == 500 + assert response.body == b'{"message":"Error"}' + + +# Fixtures +@pytest.fixture +def middleware(): + # Mock AxonMiddleware instance with empty axon object + axon = AxonMock() + return AxonMiddleware(None, axon) + + +@pytest.fixture +def mock_request(): + request = AsyncMock(spec=Request) + request.body = AsyncMock(return_value=b'{"field1": "value1", "field2": "value2"}') + request.url.path = "/test_endpoint" + request.headers = {"computed_body_hash": "correct_hash"} + return request + + +@pytest.fixture +def axon_instance(): + axon = Axon() + axon.required_hash_fields = {"test_endpoint": ["field1", "field2"]} + axon.forward_class_types = { + "test_endpoint": MagicMock(return_value=MagicMock(body_hash="correct_hash")) + } + return axon + + +# Mocks +@dataclass +class MockWallet: + hotkey: Any + coldkey: Any = None + coldkeypub: Any = None + + +class MockHotkey: + def __init__(self, ss58_address): + self.ss58_address = ss58_address + + def sign(self, *args, **kwargs): + return f"Signed: {args!r} {kwargs!r}".encode() + + +class MockInfo: + def to_string(self): + return "MockInfoString" + + +class AxonMock: + def __init__(self): + self.status_code = None + self.forward_class_types = {} + self.blacklist_fns = {} + self.priority_fns = {} + self.forward_fns = {} + self.verify_fns = {} + self.thread_pool = PriorityThreadPoolExecutor(max_workers=1) + + +class SynapseMock(Synapse): + pass + + +def verify_fn_pass(synapse): + pass + + +def verify_fn_fail(synapse): + raise Exception("Verification failed") + + +def blacklist_fn_pass(synapse): + return False, "" + + +def blacklist_fn_fail(synapse): + return True, "" + + +def priority_fn_pass(synapse) -> float: + return 0.0 + + +def priority_fn_timeout(synapse) -> float: + return 2.0 + + +@pytest.mark.asyncio +async def test_verify_pass(middleware): + synapse = SynapseMock() + middleware.axon.verify_fns = {"SynapseMock": verify_fn_pass} + await middleware.verify(synapse) + assert synapse.axon.status_code != 401 + + +@pytest.mark.asyncio +async def test_verify_fail(middleware): + synapse = SynapseMock() + middleware.axon.verify_fns = {"SynapseMock": verify_fn_fail} + with pytest.raises(Exception): + await middleware.verify(synapse) + assert synapse.axon.status_code == 401 + + +@pytest.mark.asyncio +async def test_blacklist_pass(middleware): + synapse = SynapseMock() + middleware.axon.blacklist_fns = {"SynapseMock": blacklist_fn_pass} + await middleware.blacklist(synapse) + assert synapse.axon.status_code != 403 + + +@pytest.mark.asyncio +async def test_blacklist_fail(middleware): + synapse = SynapseMock() + middleware.axon.blacklist_fns = {"SynapseMock": blacklist_fn_fail} + with pytest.raises(Exception): + await middleware.blacklist(synapse) + assert synapse.axon.status_code == 403 + + +@pytest.mark.asyncio +async def test_priority_pass(middleware): + synapse = SynapseMock() + middleware.axon.priority_fns = {"SynapseMock": priority_fn_pass} + await middleware.priority(synapse) + assert synapse.axon.status_code != 408 + + +@pytest.mark.parametrize( + "body, expected", + [ + ( + b'{"field1": "value1", "field2": "value2"}', + {"field1": "value1", "field2": "value2"}, + ), + ( + b'{"field1": "different_value", "field2": "another_value"}', + {"field1": "different_value", "field2": "another_value"}, + ), + ], +) +@pytest.mark.asyncio +async def test_verify_body_integrity_happy_path( + mock_request, axon_instance, body, expected +): + # Arrange + mock_request.body.return_value = body + + # Act + result = await axon_instance.verify_body_integrity(mock_request) + + # Assert + assert result == expected, "The parsed body should match the expected dictionary." + + +@pytest.mark.parametrize( + "body, expected_exception_message", + [ + (b"", "Expecting value: line 1 column 1 (char 0)"), # Empty body + (b"not_json", "Expecting value: line 1 column 1 (char 0)"), # Non-JSON body + ], + ids=["empty_body", "non_json_body"], +) +@pytest.mark.asyncio +async def test_verify_body_integrity_edge_cases( + mock_request, axon_instance, body, expected_exception_message +): + # Arrange + mock_request.body.return_value = body + + # Act & Assert + with pytest.raises(Exception) as exc_info: + await axon_instance.verify_body_integrity(mock_request) + assert expected_exception_message in str( + exc_info.value + ), "Expected specific exception message." + + +@pytest.mark.parametrize( + "computed_hash, expected_error", + [ + ("incorrect_hash", ValueError), + ], +) +@pytest.mark.asyncio +async def test_verify_body_integrity_error_cases( + mock_request, axon_instance, computed_hash, expected_error +): + # Arrange + mock_request.headers["computed_body_hash"] = computed_hash + + # Act & Assert + with pytest.raises(expected_error) as exc_info: + await axon_instance.verify_body_integrity(mock_request) + assert "Hash mismatch" in str(exc_info.value), "Expected a hash mismatch error." + + +@pytest.mark.parametrize( + "info_return, expected_output, test_id", + [ + (MockInfo(), "MockInfoString", "happy_path_basic"), + (MockInfo(), "MockInfoString", "edge_case_empty_string"), + ], +) +def test_to_string(info_return, expected_output, test_id): + # Arrange + axon = Axon() + with patch.object(axon, "info", return_value=info_return): + # Act + output = axon.to_string() + + # Assert + assert output == expected_output, f"Test ID: {test_id}" + + +@pytest.mark.parametrize( + "ip, port, expected_ip_type, test_id", + [ + # Happy path + ( + "127.0.0.1", + 8080, + 4, + "valid_ipv4", + ), + ( + "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + 3030, + 6, + "valid_ipv6", + ), + ], +) +def test_valid_ipv4_and_ipv6_address(ip, port, expected_ip_type, test_id): + # Arrange + axon = Axon() + axon.ip = ip + axon.external_ip = ip + axon.port = port + + # Act + ip_type = axon.info().ip_type + + # Assert + assert ip_type == expected_ip_type, f"Test ID: {test_id}" + + +@pytest.mark.parametrize( + "ip, port, expected_exception", + [ + ( + "This Is not a valid address", + 65534, + netaddr.core.AddrFormatError, + ), + ], + ids=["failed to detect a valid IP " "address from %r"], +) +def test_invalid_ip_address(ip, port, expected_exception): + # Assert + with pytest.raises(expected_exception): + Axon(ip=ip, external_ip=ip, port=port).info() + + +@pytest.mark.parametrize( + "ip, port, ss58_address, started, forward_fns, expected_str, test_id", + [ + # Happy path + ( + "127.0.0.1", + 8080, + "5G9RtsTbiYJYQYJzUfTCs...", + True, + {"fn1": None}, + "Axon(127.0.0.1, 8080, 5G9RtsTbiYJYQYJzUfTCs..., started, ['fn1'])", + "happy_path_started_with_forward_fn", + ), + ( + "192.168.1.1", + 3030, + "5HqUkGuo62b5...", + False, + {}, + "Axon(192.168.1.1, 3030, 5HqUkGuo62b5..., stopped, [])", + "happy_path_stopped_no_forward_fn", + ), + # Edge cases + ("", 0, "", False, {}, "Axon(, 0, , stopped, [])", "edge_empty_values"), + ( + "255.255.255.255", + 65535, + "5G9RtsTbiYJYQYJzUfTCs...", + True, + {"fn1": None, "fn2": None}, + "Axon(255.255.255.255, 65535, 5G9RtsTbiYJYQYJzUfTCs..., started, ['fn1', 'fn2'])", + "edge_max_values", + ), + ], +) +def test_axon_str_representation( + ip, port, ss58_address, started, forward_fns, expected_str, test_id +): + # Arrange + hotkey = MockHotkey(ss58_address) + wallet = MockWallet(hotkey) + axon = Axon() + axon.ip = ip + axon.port = port + axon.wallet = wallet + axon.started = started + axon.forward_fns = forward_fns + + # Act + result_dunder_str = axon.__str__() + result_dunder_repr = axon.__repr__() + + # Assert + assert result_dunder_str == expected_str, f"Test ID: {test_id}" + assert result_dunder_repr == expected_str, f"Test ID: {test_id}" + + +class TestAxonMiddleware(IsolatedAsyncioTestCase): + def setUp(self): + # Create a mock app + self.mock_app = MagicMock() + # Create a mock axon + self.mock_axon = MagicMock() + self.mock_axon.uuid = "1234" + self.mock_axon.forward_class_types = { + "request_name": Synapse, + } + self.mock_axon.wallet.hotkey.sign.return_value = bytes.fromhex("aabbccdd") + # Create an instance of AxonMiddleware + self.axon_middleware = AxonMiddleware(self.mock_app, self.mock_axon) + return self.axon_middleware + + @pytest.mark.asyncio + async def test_preprocess(self): + # Mock the request + request = MagicMock(spec=Request) + request.url.path = "/request_name" + request.client.port = "5000" + request.client.host = "192.168.0.1" + request.headers = {} + + synapse = await self.axon_middleware.preprocess(request) + + # Check if the preprocess function fills the axon information into the synapse + assert synapse.axon.version == str(version_as_int) + assert synapse.axon.uuid == "1234" + assert synapse.axon.nonce is not None + assert synapse.axon.status_message is None + assert synapse.axon.status_code == 100 + assert synapse.axon.signature == "0xaabbccdd" + + # Check if the preprocess function fills the dendrite information into the synapse + assert synapse.dendrite.port == "5000" + assert synapse.dendrite.ip == "192.168.0.1" + + # Check if the preprocess function sets the request name correctly + assert synapse.name == "request_name" + + +class SynapseHTTPClient(TestClient): + def post_synapse(self, synapse: Synapse): + return self.post( + f"/{synapse.__class__.__name__}", + json=synapse.model_dump(), + headers={"computed_body_hash": synapse.body_hash}, + ) + + +@pytest.mark.asyncio +class TestAxonHTTPAPIResponses: + @pytest.fixture + def axon(self): + return Axon( + ip="192.0.2.1", + external_ip="192.0.2.1", + wallet=MockWallet(MockHotkey("A"), MockHotkey("B"), MockHotkey("PUB")), + ) + + @pytest.fixture + def no_verify_axon(self, axon): + axon.default_verify = self.no_verify_fn + return axon + + @pytest.fixture + def http_client(self, axon): + return SynapseHTTPClient(axon.app) + + async def no_verify_fn(self, synapse): + return + + class NonDeterministicHeaders(pydantic.BaseModel): + """ + Helper class to verify headers. + + Size headers are non-determistic as for example, header_size depends on non-deterministic + processing-time value. + """ + + bt_header_axon_process_time: float = pydantic.Field(gt=0, lt=30) + timeout: float = pydantic.Field(gt=0, lt=30) + header_size: int = pydantic.Field(None, gt=10, lt=400) + total_size: int = pydantic.Field(gt=100, lt=10000) + content_length: Optional[int] = pydantic.Field( + None, alias="content-length", gt=100, lt=10000 + ) + + def assert_headers(self, response, expected_headers): + expected_headers = { + "bt_header_axon_status_code": "200", + "bt_header_axon_status_message": "Success", + **expected_headers, + } + headers = dict(response.headers) + non_deterministic_headers_names = { + field.alias or field_name + for field_name, field in self.NonDeterministicHeaders.model_fields.items() + } + non_deterministic_headers = { + field: headers.pop(field, None) for field in non_deterministic_headers_names + } + assert headers == expected_headers + self.NonDeterministicHeaders.model_validate(non_deterministic_headers) + + async def test_unknown_path(self, http_client): + response = http_client.get("/no_such_path") + assert (response.status_code, response.json()) == ( + 404, + { + "message": "Synapse name 'no_such_path' not found. Available synapses ['Synapse']" + }, + ) + + async def test_ping__no_dendrite(self, http_client): + response = http_client.post_synapse(Synapse()) + assert (response.status_code, response.json()) == ( + 401, + { + "message": "Not Verified with error: No SS58 formatted address or public key provided" + }, + ) + + async def test_ping__without_verification(self, http_client, axon): + axon.verify_fns["Synapse"] = self.no_verify_fn + request_synapse = Synapse() + response = http_client.post_synapse(request_synapse) + assert response.status_code == 200 + response_synapse = Synapse(**response.json()) + assert response_synapse.axon.status_code == 200 + self.assert_headers( + response, + { + "computed_body_hash": "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", + "content-type": "application/json", + "name": "Synapse", + }, + ) + + @pytest.fixture + def custom_synapse_cls(self): + class CustomSynapse(Synapse): + pass + + return CustomSynapse + + @pytest.fixture + def streaming_synapse_cls(self): + class CustomStreamingSynapse(StreamingSynapse): + async def process_streaming_response(self, response): + pass + + def extract_response_json(self, response) -> dict: + return {} + + return CustomStreamingSynapse + + async def test_synapse__explicitly_set_status_code( + self, http_client, axon, custom_synapse_cls, no_verify_axon + ): + error_message = "Essential resource for CustomSynapse not found" + + async def forward_fn(synapse: custom_synapse_cls): + synapse.axon.status_code = 404 + synapse.axon.status_message = error_message + return synapse + + axon.attach(forward_fn) + + response = http_client.post_synapse(custom_synapse_cls()) + assert response.status_code == 404 + response_synapse = custom_synapse_cls(**response.json()) + assert ( + response_synapse.axon.status_code, + response_synapse.axon.status_message, + ) == (404, error_message) + + async def test_synapse__exception_with_set_status_code( + self, http_client, axon, custom_synapse_cls, no_verify_axon + ): + error_message = "Conflicting request" + + async def forward_fn(synapse: custom_synapse_cls): + synapse.axon.status_code = 409 + raise RunException(message=error_message, synapse=synapse) + + axon.attach(forward_fn) + + response = http_client.post_synapse(custom_synapse_cls()) + assert response.status_code == 409 + assert response.json() == {"message": error_message} + + async def test_synapse__internal_error( + self, http_client, axon, custom_synapse_cls, no_verify_axon + ): + async def forward_fn(synapse: custom_synapse_cls): + raise ValueError("error with potentially sensitive information") + + axon.attach(forward_fn) + + response = http_client.post_synapse(custom_synapse_cls()) + assert response.status_code == 500 + response_data = response.json() + assert sorted(response_data.keys()) == ["message"] + assert re.match(r"Internal Server Error #[\da-f\-]+", response_data["message"]) + + +def test_allowed_nonce_window_ns(): + mock_synapse = SynapseMock() + current_time = time.time_ns() + allowed_window_ns = allowed_nonce_window_ns(current_time, mock_synapse.timeout) + expected_window_ns = ( + current_time - ALLOWED_DELTA - (mock_synapse.timeout * NANOSECONDS_IN_SECOND) + ) + assert ( + allowed_window_ns < current_time + ), "Allowed window should be less than the current time" + assert ( + allowed_window_ns == expected_window_ns + ), f"Expected {expected_window_ns} but got {allowed_window_ns}" + + +@pytest.mark.parametrize("nonce_offset_seconds", [1, 3, 5, 10]) +def test_nonce_diff_seconds(nonce_offset_seconds): + mock_synapse = SynapseMock() + current_time_ns = time.time_ns() + synapse_nonce = current_time_ns - (nonce_offset_seconds * NANOSECONDS_IN_SECOND) + diff_seconds, allowed_delta_seconds = calculate_diff_seconds( + current_time_ns, mock_synapse.timeout, synapse_nonce + ) + + expected_diff_seconds = nonce_offset_seconds # Because we subtracted nonce_offset_seconds from current_time_ns + expected_allowed_delta_seconds = ( + ALLOWED_DELTA + (mock_synapse.timeout * NANOSECONDS_IN_SECOND) + ) / NANOSECONDS_IN_SECOND + + assert ( + diff_seconds == expected_diff_seconds + ), f"Expected {expected_diff_seconds} but got {diff_seconds}" + assert ( + allowed_delta_seconds == expected_allowed_delta_seconds + ), f"Expected {expected_allowed_delta_seconds} but got {allowed_delta_seconds}" + + +# Mimicking axon default_verify nonce verification +# True: Nonce is fresh, False: Nonce is old +def is_nonce_within_allowed_window(synapse_nonce, allowed_window_ns): + return not (synapse_nonce <= allowed_window_ns) + + +# Test assuming synapse timeout is the default 12 seconds +@pytest.mark.parametrize( + "nonce_offset_seconds, expected_result", + [(1, True), (3, True), (5, True), (15, True), (18, False), (19, False)], +) +def test_nonce_within_allowed_window(nonce_offset_seconds, expected_result): + mock_synapse = SynapseMock() + current_time_ns = time.time_ns() + synapse_nonce = current_time_ns - (nonce_offset_seconds * NANOSECONDS_IN_SECOND) + allowed_window_ns = allowed_nonce_window_ns(current_time_ns, mock_synapse.timeout) + + result = is_nonce_within_allowed_window(synapse_nonce, allowed_window_ns) + + assert result == expected_result, f"Expected {expected_result} but got {result}" + + @pytest.mark.parametrize( + "forward_fn_return_annotation", + [ + None, + fastapi.Response, + StreamingSynapse, + ], + ) + async def test_streaming_synapse( + self, + http_client, + axon, + streaming_synapse_cls, + no_verify_axon, + forward_fn_return_annotation, + ): + tokens = [f"data{i}\n" for i in range(10)] + + async def streamer(send): + for token in tokens: + await send( + { + "type": "http.response.body", + "body": token.encode(), + "more_body": True, + } + ) + await send({"type": "http.response.body", "body": b"", "more_body": False}) + + async def forward_fn(synapse: streaming_synapse_cls): + return synapse.create_streaming_response(token_streamer=streamer) + + if forward_fn_return_annotation is not None: + forward_fn.__annotations__["return"] = forward_fn_return_annotation + + axon.attach(forward_fn) + + response = http_client.post_synapse(streaming_synapse_cls()) + assert (response.status_code, response.text) == (200, "".join(tokens)) + self.assert_headers( + response, + { + "content-type": "text/event-stream", + "name": "CustomStreamingSynapse", + "computed_body_hash": "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", + }, + ) diff --git a/tests/unit_tests/test_chain_data.py b/tests/unit_tests/test_chain_data.py new file mode 100644 index 0000000000..353f697d46 --- /dev/null +++ b/tests/unit_tests/test_chain_data.py @@ -0,0 +1,479 @@ +# The MIT License (MIT) +# Copyright © 2024 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 pytest +import torch + +from bittensor.core.chain_data import AxonInfo, DelegateInfo +from bittensor.core.chain_data.utils import ChainDataType + +RAOPERTAO = 10**18 + + +@pytest.mark.parametrize( + "ip, expected, test_case", + [ + ("0.0.0.0", False, "ID_is_serving_false"), + ("127.0.0.1", True, "ID_is_serving_true"), + ], +) +def test_is_serving(ip, expected, test_case): + # Arrange + axon_info = AxonInfo( + version=1, ip=ip, port=8080, ip_type=4, hotkey="", coldkey="cold" + ) + + # Act + result = axon_info.is_serving + + # Assert + assert result == expected, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "ip_type, ip, port, expected, test_case", + [ + (4, "127.0.0.1", 8080, "/ipv4/127.0.0.1:8080", "ID_ip_str_ipv4"), + (6, "::1", 8080, "/ipv6/::1:8080", "ID_ip_str_ipv6"), + ], +) +def test_ip_str(ip_type, ip, port, expected, test_case): + # Arrange + axon_info = AxonInfo( + version=1, ip=ip, port=port, ip_type=ip_type, hotkey="hot", coldkey="cold" + ) + + # Act + result = axon_info.ip_str() + + # Assert + assert result == expected, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "other, expected, test_case", + [ + (None, False, "ID_eq_none"), + ( + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + True, + "ID_eq_equal", + ), + ( + AxonInfo( + version=2, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + False, + "ID_eq_diff_version", + ), + ], +) +def test_eq(other, expected, test_case): + # Arrange + axon_info = AxonInfo( + version=1, ip="127.0.0.1", port=8080, ip_type=4, hotkey="hot", coldkey="cold" + ) + + # Act + result = axon_info == other + + # Assert + assert result == expected, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "axon_info, expected, test_case", + [ + ( + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + '{"version": 1, "ip": "127.0.0.1", "port": 8080, "ip_type": 4, "hotkey": "hot", "coldkey": "cold", "protocol": 4, "placeholder1": 0, "placeholder2": 0}', + "ID_to_string", + ), + ], +) +def test_to_string(axon_info, expected, test_case): + # Act + result = axon_info.to_string() + + # Assert + assert result == expected, f"Test case: {test_case}" + + +# Test AxonInfo.from_string method +@pytest.mark.parametrize( + "string, expected, test_case", + [ + ( + '{"version": 1, "ip": "127.0.0.1", "port": 8080, "ip_type": 4, "hotkey": "hot", "coldkey": "cold"}', + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_from_string_valid", + ), + ("invalid_json", AxonInfo(0, "", 0, 0, "", ""), "ID_from_string_invalid_json"), + ], +) +def test_from_string(string, expected, test_case): + # Act + result = AxonInfo.from_string(string) + + # Assert + assert result == expected, f"Test case: {test_case}" + + +# Test AxonInfo.from_neuron_info method +@pytest.mark.parametrize( + "neuron_info, expected, test_case", + [ + ( + { + "axon_info": { + "version": 1, + "ip": 2130706433, + "port": 8080, + "ip_type": 4, + }, + "hotkey": "hot", + "coldkey": "cold", + }, + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_from_neuron_info", + ), + ], +) +def test_from_neuron_info(neuron_info, expected, test_case): + # Act + result = AxonInfo.from_neuron_info(neuron_info) + + # Assert + assert result == expected, f"Test case: {test_case}" + + +# Test AxonInfo.to_parameter_dict method +@pytest.mark.parametrize( + "axon_info, test_case", + [ + ( + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_to_parameter_dict", + ), + ], +) +def test_to_parameter_dict(axon_info, test_case): + # Act + result = axon_info.to_parameter_dict() + + # Assert + assert isinstance(result, dict) + for key, value in axon_info.__dict__.items(): + assert key in result + assert result[key] == value, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "axon_info, test_case", + [ + ( + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_to_parameter_dict", + ), + ], +) +def test_to_parameter_dict_torch( + axon_info, + test_case, + force_legacy_torch_compatible_api, +): + result = axon_info.to_parameter_dict() + + # Assert + assert isinstance(result, torch.nn.ParameterDict) + for key, value in axon_info.__dict__.items(): + assert key in result + assert result[key] == value, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "parameter_dict, expected, test_case", + [ + ( + { + "version": 1, + "ip": "127.0.0.1", + "port": 8080, + "ip_type": 4, + "hotkey": "hot", + "coldkey": "cold", + }, + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_from_parameter_dict", + ), + ], +) +def test_from_parameter_dict(parameter_dict, expected, test_case): + # Act + result = AxonInfo.from_parameter_dict(parameter_dict) + + # Assert + assert result == expected, f"Test case: {test_case}" + + +@pytest.mark.parametrize( + "parameter_dict, expected, test_case", + [ + ( + torch.nn.ParameterDict( + { + "version": 1, + "ip": "127.0.0.1", + "port": 8080, + "ip_type": 4, + "hotkey": "hot", + "coldkey": "cold", + } + ), + AxonInfo( + version=1, + ip="127.0.0.1", + port=8080, + ip_type=4, + hotkey="hot", + coldkey="cold", + ), + "ID_from_parameter_dict", + ), + ], +) +def test_from_parameter_dict_torch( + parameter_dict, expected, test_case, force_legacy_torch_compatible_api +): + # Act + result = AxonInfo.from_parameter_dict(parameter_dict) + + # Assert + assert result == expected, f"Test case: {test_case}" + + +def create_neuron_info_decoded( + hotkey, + coldkey, + stake, + weights, + bonds, + rank, + emission, + incentive, + consensus, + trust, + validator_trust, + dividends, + uid, + netuid, + active, + last_update, + validator_permit, + pruning_score, + prometheus_info, + axon_info, +): + return { + "hotkey": hotkey, + "coldkey": coldkey, + "stake": stake, + "weights": weights, + "bonds": bonds, + "rank": rank, + "emission": emission, + "incentive": incentive, + "consensus": consensus, + "trust": trust, + "validator_trust": validator_trust, + "dividends": dividends, + "uid": uid, + "netuid": netuid, + "active": active, + "last_update": last_update, + "validator_permit": validator_permit, + "pruning_score": pruning_score, + "prometheus_info": prometheus_info, + "axon_info": axon_info, + } + + +@pytest.fixture +def mock_from_scale_encoding(mocker): + return mocker.patch("bittensor.core.chain_data.delegate_info.from_scale_encoding") + + +@pytest.fixture +def mock_fix_decoded_values(mocker): + return mocker.patch( + "bittensor.core.chain_data.DelegateInfo.fix_decoded_values", + side_effect=lambda x: x, + ) + + +@pytest.mark.parametrize( + "test_id, vec_u8, expected", + [ + ( + "happy-path-1", + [1, 2, 3], + [ + DelegateInfo( + hotkey_ss58="hotkey", + total_stake=1000, + nominators=[ + "nominator1", + "nominator2", + ], + owner_ss58="owner", + take=10.1, + validator_permits=[1, 2, 3], + registrations=[4, 5, 6], + return_per_1000=100, + total_daily_return=1000, + ) + ], + ), + ( + "happy-path-2", + [4, 5, 6], + [ + DelegateInfo( + hotkey_ss58="hotkey", + total_stake=1000, + nominators=[ + "nominator1", + "nominator2", + ], + owner_ss58="owner", + take=2.1, + validator_permits=[1, 2, 3], + registrations=[4, 5, 6], + return_per_1000=100, + total_daily_return=1000, + ) + ], + ), + ], +) +def test_list_from_vec_u8_happy_path( + mock_from_scale_encoding, mock_fix_decoded_values, test_id, vec_u8, expected +): + # Arrange + mock_from_scale_encoding.return_value = expected + + # Act + result = DelegateInfo.list_from_vec_u8(vec_u8) + + # Assert + mock_from_scale_encoding.assert_called_once_with( + vec_u8, ChainDataType.DelegateInfo, is_vec=True + ) + assert result == expected, f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, vec_u8, expected", + [ + ("edge_empty_list", [], []), + ], +) +def test_list_from_vec_u8_edge_cases( + mock_from_scale_encoding, mock_fix_decoded_values, test_id, vec_u8, expected +): + # Arrange + mock_from_scale_encoding.return_value = None + + # Act + result = DelegateInfo.list_from_vec_u8(vec_u8) + + # Assert + mock_from_scale_encoding.assert_called_once_with( + vec_u8, ChainDataType.DelegateInfo, is_vec=True + ) + assert result == expected, f"Failed {test_id}" + + +@pytest.mark.parametrize( + "vec_u8, expected_exception", + [ + ("not_a_list", TypeError), + ], +) +def test_list_from_vec_u8_error_cases( + vec_u8, + expected_exception, +): + # No Arrange section needed as input values are provided via test parameters + + # Act & Assert + with pytest.raises(expected_exception): + _ = DelegateInfo.list_from_vec_u8(vec_u8) diff --git a/tests/unit_tests/test_dendrite.py b/tests/unit_tests/test_dendrite.py new file mode 100644 index 0000000000..3150aaf648 --- /dev/null +++ b/tests/unit_tests/test_dendrite.py @@ -0,0 +1,416 @@ +# The MIT License (MIT) +# Copyright © 2022 Yuma Rao +# Copyright © 2022-2023 Opentensor Foundation +# Copyright © 2023 Opentensor Technologies Inc + +# 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 asyncio +import typing +from unittest.mock import MagicMock, Mock + +import aiohttp +import pytest + +from bittensor.core.axon import Axon +from bittensor.core.dendrite import ( + DENDRITE_ERROR_MAPPING, + DENDRITE_DEFAULT_ERROR, + Dendrite, +) +from bittensor.core.synapse import TerminalInfo +from tests.helpers import get_mock_wallet +from bittensor.core.synapse import Synapse +from bittensor.core.chain_data import AxonInfo + + +class SynapseDummy(Synapse): + input: int + output: typing.Optional[int] = None + + +def dummy(synapse: SynapseDummy) -> SynapseDummy: + synapse.output = synapse.input + 1 + return synapse + + +@pytest.fixture +def setup_dendrite(): + # Assuming bittensor.Wallet() returns a wallet object + user_wallet = get_mock_wallet() + dendrite_obj = Dendrite(user_wallet) + return dendrite_obj + + +@pytest.fixture +def dendrite_obj(setup_dendrite): + return setup_dendrite + + +@pytest.fixture +def axon_info(): + return AxonInfo( + version=1, + ip="127.0.0.1", + port=666, + ip_type=4, + hotkey="hot", + coldkey="cold", + ) + + +@pytest.fixture(scope="session") +def setup_axon(): + axon = Axon() + axon.attach(forward_fn=dummy) + axon.start() + yield axon + del axon + + +def test_init(setup_dendrite): + dendrite_obj = setup_dendrite + assert isinstance(dendrite_obj, Dendrite) + assert dendrite_obj.keypair == setup_dendrite.keypair + + +def test_str(dendrite_obj): + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" + assert str(dendrite_obj) == expected_string + + +def test_repr(dendrite_obj): + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" + assert repr(dendrite_obj) == expected_string + + +def test_close(dendrite_obj, setup_axon): + axon = setup_axon + # Query the axon to open a session + dendrite_obj.query(axon, SynapseDummy(input=1)) + # Session should be automatically closed after query + assert dendrite_obj._session is None + + +@pytest.mark.asyncio +async def test_aclose(dendrite_obj, setup_axon): + axon = setup_axon + # Use context manager to open an async session + async with dendrite_obj: + await dendrite_obj([axon], SynapseDummy(input=1), deserialize=False) + # Close should automatically be called on the session after context manager scope + assert dendrite_obj._session is None + + +class AsyncMock(Mock): + def __call__(self, *args, **kwargs): + sup = super(AsyncMock, self) + + async def coro(): + return sup.__call__(*args, **kwargs) + + return coro() + + def __await__(self): + return self().__await__() + + +def test_dendrite_create_wallet(): + d = Dendrite(get_mock_wallet()) + d = Dendrite(get_mock_wallet().hotkey) + d = Dendrite(get_mock_wallet().coldkeypub) + assert d.__str__() == d.__repr__() + + +@pytest.mark.asyncio +async def test_forward_many(): + n = 10 + d = Dendrite(wallet=get_mock_wallet()) + d.call = AsyncMock() + axons = [MagicMock() for _ in range(n)] + + resps = await d(axons) + assert len(resps) == n + resp = await d(axons[0]) + assert len([resp]) == 1 + + resps = await d.forward(axons) + assert len(resps) == n + resp = await d.forward(axons[0]) + assert len([resp]) == 1 + + +def test_pre_process_synapse(): + d = Dendrite(wallet=get_mock_wallet()) + s = Synapse() + synapse = d.preprocess_synapse_for_request( + target_axon_info=Axon(wallet=get_mock_wallet()).info(), + synapse=s, + timeout=12, + ) + assert synapse.timeout == 12 + assert synapse.dendrite + assert synapse.axon + assert synapse.dendrite.ip + assert synapse.dendrite.version + assert synapse.dendrite.nonce + assert synapse.dendrite.uuid + assert synapse.dendrite.hotkey + assert synapse.axon.ip + assert synapse.axon.port + assert synapse.axon.hotkey + assert synapse.dendrite.signature + + +# Helper functions for casting, assuming they exist and work correctly. +def cast_int(value: typing.Any) -> int: + return int(value) + + +def cast_float(value: typing.Any) -> float: + return float(value) + + +# Happy path tests +@pytest.mark.parametrize( + "status_code, status_message, process_time, ip, port, version, nonce, uuid, hotkey, signature, expected", + [ + ( + 200, + "Success", + 0.1, + "198.123.23.1", + 9282, + 111, + 111111, + "5ecbd69c-1cec-11ee-b0dc-e29ce36fec1a", + "5EnjDGNqqWnuL2HCAdxeEtN2oqtXZw6BMBe936Kfy2PFz1J1", + "0x0813029319030129u4120u10841824y0182u091u230912u", + True, + ), + # Add more test cases with different combinations of realistic values + ], + ids=["basic-success"], +) +def test_terminal_info_happy_path( + status_code, + status_message, + process_time, + ip, + port, + version, + nonce, + uuid, + hotkey, + signature, + expected, +): + # Act + terminal_info = TerminalInfo( + status_code=status_code, + status_message=status_message, + process_time=process_time, + ip=ip, + port=port, + version=version, + nonce=nonce, + uuid=uuid, + hotkey=hotkey, + signature=signature, + ) + + # Assert + assert isinstance(terminal_info, TerminalInfo) == expected + assert terminal_info.status_code == status_code + assert terminal_info.status_message == status_message + assert terminal_info.process_time == process_time + assert terminal_info.ip == ip + assert terminal_info.port == port + assert terminal_info.version == version + assert terminal_info.nonce == nonce + assert terminal_info.uuid == uuid + assert terminal_info.hotkey == hotkey + assert terminal_info.signature == signature + + +# Edge cases +@pytest.mark.parametrize( + "status_code, process_time, port, version, nonce, expected_exception", + [ + ("not-an-int", 0.1, 9282, 111, 111111, ValueError), # status_code not an int + (200, "not-a-float", 9282, 111, 111111, ValueError), # process_time not a float + (200, 0.1, "not-an-int", 111, 111111, ValueError), # port not an int + # Add more edge cases as needed + ], + ids=["status_code-not-int", "process_time-not-float", "port-not-int"], +) +def test_terminal_info_edge_cases( + status_code, process_time, port, version, nonce, expected_exception +): + # Act & Assert + with pytest.raises(expected_exception): + TerminalInfo( + status_code=status_code, + process_time=process_time, + port=port, + version=version, + nonce=nonce, + ) + + +# Error case +@pytest.mark.parametrize( + "status_code, process_time, port, ip, version, nonce, expected_exception", + [ + (None, 0.1, 9282, 111, TerminalInfo(), 111111, TypeError), + ], + ids=[ + "int() argument must be a string, a bytes-like object or a real number, not 'TerminalInfo'" + ], +) +def test_terminal_info_error_cases( + status_code, process_time, port, ip, version, nonce, expected_exception +): + # Act & Assert + with pytest.raises(expected_exception): + TerminalInfo( + status_code=status_code, + process_time=process_time, + port=port, + ip=ip, + version=version, + nonce=nonce, + ) + + +@pytest.mark.asyncio +async def test_dendrite__call__success_response( + axon_info, dendrite_obj, mock_aio_response +): + input_synapse = SynapseDummy(input=1) + expected_synapse = SynapseDummy( + **( + input_synapse.model_dump() + | dict( + output=2, + axon=TerminalInfo( + status_code=200, + status_message="Success", + process_time=0.1, + ), + ) + ) + ) + mock_aio_response.post( + f"http://127.0.0.1:666/SynapseDummy", + body=expected_synapse.json(), + ) + synapse = await dendrite_obj.call(axon_info, synapse=input_synapse) + + assert synapse.input == 1 + assert synapse.output == 2 + assert synapse.dendrite.status_code == 200 + assert synapse.dendrite.status_message == "Success" + assert synapse.dendrite.process_time >= 0 + + +@pytest.mark.asyncio +async def test_dendrite__call__handles_http_error_response( + axon_info, dendrite_obj, mock_aio_response +): + status_code = 414 + message = "Custom Error" + + mock_aio_response.post( + "http://127.0.0.1:666/SynapseDummy", + status=status_code, + payload={"message": message}, + ) + synapse = await dendrite_obj.call(axon_info, synapse=SynapseDummy(input=1)) + + assert synapse.axon.status_code == synapse.dendrite.status_code == status_code + assert synapse.axon.status_message == synapse.dendrite.status_message == message + + +@pytest.mark.parametrize( + "exception, expected_status_code, expected_message, synapse_timeout, synapse_ip, synapse_port, request_name", + [ + ( + aiohttp.ClientConnectorError(Mock(), Mock()), + DENDRITE_ERROR_MAPPING[aiohttp.ClientConnectorError][0], + f"{DENDRITE_ERROR_MAPPING[aiohttp.ClientConnectorError][1]} at 127.0.0.1:8080/test_request", + None, + "127.0.0.1", + "8080", + "test_request_client_connector_error", + ), + ( + asyncio.TimeoutError(), + DENDRITE_ERROR_MAPPING[asyncio.TimeoutError][0], + f"{DENDRITE_ERROR_MAPPING[asyncio.TimeoutError][1]} after 5 seconds", + 5, + None, + None, + "test_request_timeout", + ), + ( + aiohttp.ClientResponseError(Mock(), Mock(), status=404), + "404", + f"{DENDRITE_ERROR_MAPPING[aiohttp.ClientResponseError][1]}: 404, message=''", + None, + None, + None, + "test_request_client_response_error", + ), + ( + Exception("Unknown error"), + DENDRITE_DEFAULT_ERROR[0], + f"{DENDRITE_DEFAULT_ERROR[1]}: Unknown error", + None, + None, + None, + "test_request_unknown_error", + ), + ], + ids=[ + "ClientConnectorError", + "TimeoutError", + "ClientResponseError", + "GenericException", + ], +) +def test_process_error_message( + exception, + expected_status_code, + expected_message, + synapse_timeout, + synapse_ip, + synapse_port, + request_name, +): + # Arrange + dendrite = Dendrite() + synapse = Mock() + + synapse.timeout = synapse_timeout + synapse.axon.ip = synapse_ip + synapse.axon.port = synapse_port + + # Act + result = dendrite.process_error_message(synapse, request_name, exception) + + # Assert + assert result.dendrite.status_code == expected_status_code + assert expected_message in result.dendrite.status_message diff --git a/tests/unit_tests/test_deprecated.py b/tests/unit_tests/test_deprecated.py new file mode 100644 index 0000000000..c4b906a0ca --- /dev/null +++ b/tests/unit_tests/test_deprecated.py @@ -0,0 +1,51 @@ +# The MIT License (MIT) +# Copyright © 2024 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 sys + + +def test_mock_import(): + """ + Tests that `bittensor.mock` can be imported and is the same as `bittensor.utils.mock`. + """ + import bittensor.mock as redirected_mock + import bittensor.utils.mock as real_mock + + assert "bittensor.mock" in sys.modules + assert redirected_mock is real_mock + + +def test_extrinsics_import(): + """Tests that `bittensor.extrinsics` can be imported and is the same as `bittensor.utils.deprecated.extrinsics`.""" + import bittensor.extrinsics as redirected_extrinsics + import bittensor.core.extrinsics as real_extrinsics + + assert "bittensor.extrinsics" in sys.modules + assert redirected_extrinsics is real_extrinsics + + +def test_object_aliases_are_correctly_mapped(): + """Ensures all object aliases correctly map to their respective classes in Bittensor package.""" + import bittensor + + assert issubclass(bittensor.axon, bittensor.Axon) + assert issubclass(bittensor.config, bittensor.Config) + assert issubclass(bittensor.dendrite, bittensor.Dendrite) + assert issubclass(bittensor.keyfile, bittensor.Keyfile) + assert issubclass(bittensor.metagraph, bittensor.Metagraph) + assert issubclass(bittensor.wallet, bittensor.Wallet) + assert issubclass(bittensor.synapse, bittensor.Synapse) diff --git a/tests/unit_tests/test_logging.py b/tests/unit_tests/test_logging.py new file mode 100644 index 0000000000..2aa43d1e70 --- /dev/null +++ b/tests/unit_tests/test_logging.py @@ -0,0 +1,199 @@ +import logging as stdlogging +import multiprocessing +from unittest.mock import MagicMock, patch + +import pytest + +from bittensor.utils.btlogging import LoggingMachine +from bittensor.utils.btlogging.defines import ( + DEFAULT_LOG_FILE_NAME, + BITTENSOR_LOGGER_NAME, +) +from bittensor.utils.btlogging.loggingmachine import LoggingConfig, _concat_message + + +@pytest.fixture(autouse=True, scope="session") +def disable_stdout_streaming(): + # Backup original handlers + original_handlers = stdlogging.root.handlers[:] + + # Remove all handlers that stream to stdout + stdlogging.root.handlers = [ + h + for h in stdlogging.root.handlers + if not isinstance(h, stdlogging.StreamHandler) + ] + + yield # Yield control to the test or fixture setup + + # Restore original handlers after the test + stdlogging.root.handlers = original_handlers + + +@pytest.fixture +def mock_config(tmp_path): + # Using pytest's tmp_path fixture to generate a temporary directory + log_dir = tmp_path / "logs" + log_dir.mkdir() # Create the temporary directory + log_file_path = log_dir / DEFAULT_LOG_FILE_NAME + + mock_config = LoggingConfig( + debug=False, trace=False, record_log=True, logging_dir=str(log_dir) + ) + + yield mock_config, log_file_path + # Cleanup: No need to explicitly delete the log file or directory, tmp_path does it automatically + + +@pytest.fixture +def logging_machine(mock_config): + config, _ = mock_config + logging_machine = LoggingMachine(config=config) + return logging_machine + + +def test_initialization(logging_machine, mock_config): + """ + Test initialization of LoggingMachine. + """ + config, log_file_path = mock_config # Unpack to get the log_file_path + + assert logging_machine.get_queue() is not None + assert isinstance(logging_machine.get_queue(), multiprocessing.queues.Queue) + assert logging_machine.get_config() == config + + # Ensure that handlers are set up correctly + assert any( + isinstance(handler, stdlogging.StreamHandler) + for handler in logging_machine._handlers + ) + if config.record_log and config.logging_dir: + assert any( + isinstance(handler, stdlogging.FileHandler) + for handler in logging_machine._handlers + ) + assert log_file_path.exists() # Check if log file is created + + +def test_state_transitions(logging_machine, mock_config): + """ + Test state transitions and the associated logging level changes. + """ + config, log_file_path = mock_config + with patch( + "bittensor.utils.btlogging.loggingmachine.all_loggers" + ) as mocked_all_loggers: + # mock the main bittensor logger, identified by its `name` field + mocked_bt_logger = MagicMock() + mocked_bt_logger.name = BITTENSOR_LOGGER_NAME + # third party loggers are treated differently and silenced under default + # logging settings + mocked_third_party_logger = MagicMock() + logging_machine._logger = mocked_bt_logger + mocked_all_loggers.return_value = [mocked_third_party_logger, mocked_bt_logger] + + # Enable/Disable Debug + # from default + assert logging_machine.current_state_value == "Default" + logging_machine.enable_debug() + assert logging_machine.current_state_value == "Debug" + # check log levels + mocked_bt_logger.setLevel.assert_called_with(stdlogging.DEBUG) + mocked_third_party_logger.setLevel.assert_called_with(stdlogging.DEBUG) + + logging_machine.disable_debug() + + # Enable/Disable Trace + assert logging_machine.current_state_value == "Default" + logging_machine.enable_trace() + assert logging_machine.current_state_value == "Trace" + # check log levels + mocked_bt_logger.setLevel.assert_called_with(stdlogging.TRACE) + mocked_third_party_logger.setLevel.assert_called_with(stdlogging.TRACE) + logging_machine.disable_trace() + assert logging_machine.current_state_value == "Default" + + # Enable Default + logging_machine.enable_debug() + assert logging_machine.current_state_value == "Debug" + logging_machine.enable_default() + assert logging_machine.current_state_value == "Default" + # main logger set to INFO + mocked_bt_logger.setLevel.assert_called_with(stdlogging.WARNING) + # 3rd party loggers should be disabled by setting to CRITICAL + mocked_third_party_logger.setLevel.assert_called_with(stdlogging.CRITICAL) + + # Disable Logging + # from default + logging_machine.disable_logging() + assert logging_machine.current_state_value == "Disabled" + mocked_bt_logger.setLevel.assert_called_with(stdlogging.CRITICAL) + mocked_third_party_logger.setLevel.assert_called_with(stdlogging.CRITICAL) + + +def test_enable_file_logging_with_new_config(tmp_path): + """ + Test enabling file logging by setting a new config. + """ + log_dir = tmp_path / "logs" + log_dir.mkdir() # Create the temporary directory + log_file_path = log_dir / DEFAULT_LOG_FILE_NAME + + # check no file handler is created + config = LoggingConfig(debug=False, trace=False, record_log=True, logging_dir=None) + lm = LoggingMachine(config) + assert not any( + isinstance(handler, stdlogging.FileHandler) for handler in lm._handlers + ) + + # check file handler now exists + new_config = LoggingConfig( + debug=False, trace=False, record_log=True, logging_dir=str(log_dir) + ) + lm.set_config(new_config) + assert any(isinstance(handler, stdlogging.FileHandler) for handler in lm._handlers) + + +def test_all_log_levels_output(logging_machine, caplog): + """ + Test that all log levels are captured. + """ + logging_machine.set_trace() + + logging_machine.trace("Test trace") + logging_machine.debug("Test debug") + logging_machine.info("Test info") + logging_machine.success("Test success") + logging_machine.warning("Test warning") + logging_machine.error("Test error") + logging_machine.critical("Test critical") + + assert "Test trace" in caplog.text + assert "Test debug" in caplog.text + assert "Test info" in caplog.text + assert "Test success" in caplog.text + assert "Test warning" in caplog.text + assert "Test error" in caplog.text + assert "Test critical" in caplog.text + + +@pytest.mark.parametrize( + "msg, prefix, suffix, expected_result", + [ + ("msg", "", "", "msg"), + ("msg", None, None, "msg"), + ("msg", "prefix", None, "prefix - msg"), + ("msg", None, "suffix", "msg - suffix"), + ("msg", "prefix", "suffix", "prefix - msg - suffix"), + ], + ids=[ + "message, no prefix (str), no suffix (str)", + "message, no prefix (None), no suffix (None)", + "message and prefix only", + "message and suffix only", + "message, prefix, and suffix", + ], +) +def test_concat(msg, prefix, suffix, expected_result): + """Test different options of message concatenation with prefix and suffix.""" + assert _concat_message(msg, prefix, suffix) == expected_result diff --git a/tests/unit_tests/test_metagraph.py b/tests/unit_tests/test_metagraph.py new file mode 100644 index 0000000000..e4dca70a1d --- /dev/null +++ b/tests/unit_tests/test_metagraph.py @@ -0,0 +1,176 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from unittest.mock import MagicMock +from unittest.mock import Mock + +import numpy as np +import pytest + +from bittensor.core import settings +from bittensor.core.metagraph import Metagraph + + +@pytest.fixture +def mock_environment(): + # Create a Mock for subtensor + subtensor = Mock() + + # Create a list of Mock Neurons + neurons = [ + Mock( + uid=i, + trust=i + 0.5, + consensus=i + 0.1, + incentive=i + 0.2, + dividends=i + 0.3, + rank=i + 0.4, + emission=i + 0.5, + active=i, + last_update=i, + validator_permit=i % 2 == 0, + validator_trust=i + 0.6, + total_stake=Mock(tao=i + 0.7), + stake=i + 0.8, + axon_info=f"axon_info_{i}", + weights=[(j, j + 0.1) for j in range(5)], + bonds=[(j, j + 0.2) for j in range(5)], + ) + for i in range(10) + ] + + return subtensor, neurons + + +def test_set_metagraph_attributes(mock_environment): + subtensor, neurons = mock_environment + metagraph = Metagraph(1, sync=False) + metagraph.neurons = neurons + metagraph._set_metagraph_attributes(block=5, subtensor=subtensor) + + # Check the attributes are set as expected + assert metagraph.n.item() == len(neurons) + assert metagraph.block.item() == 5 + assert ( + np.array_equal( + metagraph.uids, + np.array([neuron.uid for neuron in neurons], dtype=np.int64), + ) + is True + ) + + assert ( + np.array_equal( + metagraph.trust, + np.array([neuron.trust for neuron in neurons], dtype=np.float32), + ) + is True + ) + + assert ( + np.array_equal( + metagraph.consensus, + np.array([neuron.consensus for neuron in neurons], dtype=np.float32), + ) + is True + ) + # Similarly for other attributes... + + # Test the axons + assert metagraph.axons == [n.axon_info for n in neurons] + + +def test_process_weights_or_bonds(mock_environment): + _, neurons = mock_environment + metagraph = Metagraph(1, sync=False) + metagraph.neurons = neurons + + # Test weights processing + weights = metagraph._process_weights_or_bonds( + data=[neuron.weights for neuron in neurons], attribute="weights" + ) + assert weights.shape[0] == len( + neurons + ) # Number of rows should be equal to number of neurons + assert weights.shape[1] == len( + neurons + ) # Number of columns should be equal to number of neurons + # TODO: Add more checks to ensure the weights have been processed correctly + + # Test bonds processing + bonds = metagraph._process_weights_or_bonds( + data=[neuron.bonds for neuron in neurons], attribute="bonds" + ) + assert bonds.shape[0] == len( + neurons + ) # Number of rows should be equal to number of neurons + assert bonds.shape[1] == len( + neurons + ) # Number of columns should be equal to number of neurons + + # TODO: Add more checks to ensure the bonds have been processed correctly + + +# Mocking the bittensor.Subtensor class for testing purposes +@pytest.fixture +def mock_subtensor(): + subtensor = MagicMock() + subtensor.chain_endpoint = settings.FINNEY_ENTRYPOINT + subtensor.network = "finney" + subtensor.get_current_block.return_value = 601 + return subtensor + + +# Mocking the metagraph instance for testing purposes +@pytest.fixture +def metagraph_instance(): + metagraph = Metagraph(netuid=1337, sync=False) + metagraph._assign_neurons = MagicMock() + metagraph._set_metagraph_attributes = MagicMock() + metagraph._set_weights_and_bonds = MagicMock() + return metagraph + + +@pytest.fixture +def loguru_sink(): + class LogSink: + def __init__(self): + self.messages = [] + + def write(self, message): + # Assuming `message` is an object, you might need to adjust how you extract the text + self.messages.append(str(message)) + + def __contains__(self, item): + return any(item in message for message in self.messages) + + return LogSink() + + +@pytest.mark.parametrize( + "block, test_id", + [ + (300, "warning_case_block_greater_than_300"), + ], +) +def test_sync_warning_cases(block, test_id, metagraph_instance, mock_subtensor, caplog): + metagraph_instance.sync(block=block, lite=True, subtensor=mock_subtensor) + + expected_message = "Attempting to sync longer than 300 blocks ago on a non-archive node. Please use the 'archive' network for subtensor and retry." + assert ( + expected_message in caplog.text + ), f"Test ID: {test_id} - Expected warning message not found in Loguru sink." diff --git a/tests/unit_tests/test_subnets.py b/tests/unit_tests/test_subnets.py new file mode 100644 index 0000000000..9cec02e935 --- /dev/null +++ b/tests/unit_tests/test_subnets.py @@ -0,0 +1,82 @@ +import pytest +from mpmath.ctx_mp_python import return_mpc + +from bittensor.utils import subnets + + +class MySubnetsAPI(subnets.SubnetsAPI): + """Example of user class inherited from SubnetsAPI.""" + + def prepare_synapse(self, *args, **kwargs): + """Prepare the synapse-specific payload.""" + + def process_responses(self, responses): + """Process the responses from the network.""" + return responses + + +def test_instance_creation(mocker): + """Test the creation of a MySubnetsAPI instance.""" + # Prep + mocked_dendrite = mocker.patch.object(subnets, "Dendrite") + fake_wallet = mocker.MagicMock() + + # Call + instance = MySubnetsAPI(fake_wallet) + + # Asserts + assert isinstance(instance, subnets.SubnetsAPI) + mocked_dendrite.assert_called_once_with(wallet=fake_wallet) + assert instance.dendrite == mocked_dendrite.return_value + assert instance.wallet == fake_wallet + + +@pytest.mark.asyncio +async def test_query_api(mocker): + """Test querying the MySubnetsAPI instance asynchronously.""" + # Prep + mocked_async_dendrite = mocker.AsyncMock() + mocked_dendrite = mocker.patch.object( + subnets, "Dendrite", return_value=mocked_async_dendrite + ) + + fake_wallet = mocker.MagicMock() + fake_axon = mocker.MagicMock() + + mocked_synapse = mocker.MagicMock() + mocked_synapse.return_value.name = "test synapse" + mocked_prepare_synapse = mocker.patch.object( + MySubnetsAPI, "prepare_synapse", return_value=mocked_synapse + ) + + # Call + instance = MySubnetsAPI(fake_wallet) + result = await instance.query_api(fake_axon, **{"key": "val"}) + + # Asserts + mocked_prepare_synapse.assert_called_once_with(key="val") + mocked_dendrite.assert_called_once_with(wallet=fake_wallet) + assert result == mocked_async_dendrite.return_value + + +@pytest.mark.asyncio +async def test_test_instance_call(mocker): + """Test the MySubnetsAPI instance call with asynchronous handling.""" + # Prep + mocked_async_dendrite = mocker.AsyncMock() + mocked_dendrite = mocker.patch.object( + subnets, "Dendrite", return_value=mocked_async_dendrite + ) + mocked_query_api = mocker.patch.object( + MySubnetsAPI, "query_api", new=mocker.AsyncMock() + ) + fake_wallet = mocker.MagicMock() + fake_axon = mocker.MagicMock() + + # Call + instance = MySubnetsAPI(fake_wallet) + await instance(fake_axon) + + # Asserts + mocked_dendrite.assert_called_once_with(wallet=fake_wallet) + mocked_query_api.assert_called_once_with(fake_axon) diff --git a/tests/unit_tests/test_subtensor.py b/tests/unit_tests/test_subtensor.py new file mode 100644 index 0000000000..d0783d20ff --- /dev/null +++ b/tests/unit_tests/test_subtensor.py @@ -0,0 +1,2053 @@ +# The MIT License (MIT) +# Copyright © 2024 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 argparse +import unittest.mock as mock +from unittest.mock import MagicMock + +import pytest +from bittensor_wallet import Wallet + +from bittensor.core import subtensor as subtensor_module, settings +from bittensor.core.axon import Axon +from bittensor.core.chain_data import SubnetHyperparameters +from bittensor.core.settings import version_as_int +from bittensor.core.subtensor import Subtensor, logging +from bittensor.utils import u16_normalized_float, u64_normalized_float +from bittensor.utils.balance import Balance + +U16_MAX = 65535 +U64_MAX = 18446744073709551615 + + +def test_serve_axon_with_external_ip_set(): + internal_ip: str = "192.0.2.146" + external_ip: str = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" + + mock_serve_axon = MagicMock(return_value=True) + + mock_subtensor = MagicMock(spec=Subtensor, serve_axon=mock_serve_axon) + + mock_wallet = MagicMock( + spec=Wallet, + coldkey=MagicMock(), + coldkeypub=MagicMock( + # mock ss58 address + ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm" + ), + hotkey=MagicMock( + ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg" + ), + ) + + mock_config = Axon.config() + mock_axon_with_external_ip_set = Axon( + wallet=mock_wallet, + ip=internal_ip, + external_ip=external_ip, + config=mock_config, + ) + + mock_subtensor.serve_axon( + netuid=-1, + axon=mock_axon_with_external_ip_set, + ) + + mock_serve_axon.assert_called_once() + + # verify that the axon is served to the network with the external ip + _, kwargs = mock_serve_axon.call_args + axon_info = kwargs["axon"].info() + assert axon_info.ip == external_ip + + +def test_serve_axon_with_external_port_set(): + external_ip: str = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" + + internal_port: int = 1234 + external_port: int = 5678 + + mock_serve = MagicMock(return_value=True) + + mock_serve_axon = MagicMock(return_value=True) + + mock_subtensor = MagicMock( + spec=Subtensor, + serve=mock_serve, + serve_axon=mock_serve_axon, + ) + + mock_wallet = MagicMock( + spec=Wallet, + coldkey=MagicMock(), + coldkeypub=MagicMock( + # mock ss58 address + ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm" + ), + hotkey=MagicMock( + ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg" + ), + ) + + mock_config = Axon.config() + + mock_axon_with_external_port_set = Axon( + wallet=mock_wallet, + port=internal_port, + external_port=external_port, + config=mock_config, + ) + + with mock.patch( + "bittensor.utils.networking.get_external_ip", return_value=external_ip + ): + # mock the get_external_ip function to return the external ip + mock_subtensor.serve_axon( + netuid=-1, + axon=mock_axon_with_external_port_set, + ) + + mock_serve_axon.assert_called_once() + # verify that the axon is served to the network with the external port + _, kwargs = mock_serve_axon.call_args + axon_info = kwargs["axon"].info() + assert axon_info.port == external_port + + +class ExitEarly(Exception): + """Mock exception to exit early from the called code""" + + pass + + +@pytest.mark.parametrize( + "test_id, expected_output", + [ + # Happy path test + ( + "happy_path_default", + "Create and return a new object. See help(type) for accurate signature.", + ), + ], +) +def test_help(test_id, expected_output, capsys): + # Act + Subtensor.help() + + # Assert + captured = capsys.readouterr() + assert expected_output in captured.out, f"Test case {test_id} failed" + + +@pytest.fixture +def parser(): + return argparse.ArgumentParser() + + +# Mocking argparse.ArgumentParser.add_argument method to simulate ArgumentError +def test_argument_error_handling(monkeypatch, parser): + def mock_add_argument(*args, **kwargs): + raise argparse.ArgumentError(None, "message") + + monkeypatch.setattr(argparse.ArgumentParser, "add_argument", mock_add_argument) + # No exception should be raised + Subtensor.add_args(parser) + + +@pytest.mark.parametrize( + "network, expected_network, expected_endpoint", + [ + # Happy path tests + ("finney", "finney", settings.FINNEY_ENTRYPOINT), + ("local", "local", settings.LOCAL_ENTRYPOINT), + ("test", "test", settings.FINNEY_TEST_ENTRYPOINT), + ("archive", "archive", settings.ARCHIVE_ENTRYPOINT), + # Endpoint override tests + ( + settings.FINNEY_ENTRYPOINT, + "finney", + settings.FINNEY_ENTRYPOINT, + ), + ( + "entrypoint-finney.opentensor.ai", + "finney", + settings.FINNEY_ENTRYPOINT, + ), + ( + settings.FINNEY_TEST_ENTRYPOINT, + "test", + settings.FINNEY_TEST_ENTRYPOINT, + ), + ( + "test.finney.opentensor.ai", + "test", + settings.FINNEY_TEST_ENTRYPOINT, + ), + ( + settings.ARCHIVE_ENTRYPOINT, + "archive", + settings.ARCHIVE_ENTRYPOINT, + ), + ( + "archive.chain.opentensor.ai", + "archive", + settings.ARCHIVE_ENTRYPOINT, + ), + ("127.0.0.1", "local", "127.0.0.1"), + ("localhost", "local", "localhost"), + # Edge cases + (None, None, None), + ("unknown", "unknown", "unknown"), + ], +) +def test_determine_chain_endpoint_and_network( + network, expected_network, expected_endpoint +): + # Act + result_network, result_endpoint = Subtensor.determine_chain_endpoint_and_network( + network + ) + + # Assert + assert result_network == expected_network + assert result_endpoint == expected_endpoint + + +@pytest.fixture +def subtensor(mocker): + fake_substrate = mocker.MagicMock() + fake_substrate.websocket.sock.getsockopt.return_value = 0 + mocker.patch.object( + subtensor_module, "SubstrateInterface", return_value=fake_substrate + ) + return Subtensor() + + +@pytest.fixture +def mock_logger(): + with mock.patch.object(logging, "warning") as mock_warning: + yield mock_warning + + +def test_hyperparameter_subnet_does_not_exist(subtensor, mocker): + """Tests when the subnet does not exist.""" + subtensor.subnet_exists = mocker.MagicMock(return_value=False) + assert subtensor._get_hyperparameter("Difficulty", 1, None) is None + subtensor.subnet_exists.assert_called_once_with(1, None) + + +def test_hyperparameter_result_is_none(subtensor, mocker): + """Tests when query_subtensor returns None.""" + subtensor.subnet_exists = mocker.MagicMock(return_value=True) + subtensor.query_subtensor = mocker.MagicMock(return_value=None) + assert subtensor._get_hyperparameter("Difficulty", 1, None) is None + subtensor.subnet_exists.assert_called_once_with(1, None) + subtensor.query_subtensor.assert_called_once_with("Difficulty", None, [1]) + + +def test_hyperparameter_result_has_no_value(subtensor, mocker): + """Test when the result has no 'value' attribute.""" + subtensor.subnet_exists = mocker.MagicMock(return_value=True) + subtensor.query_subtensor = mocker.MagicMock(return_value=None) + assert subtensor._get_hyperparameter("Difficulty", 1, None) is None + subtensor.subnet_exists.assert_called_once_with(1, None) + subtensor.query_subtensor.assert_called_once_with("Difficulty", None, [1]) + + +def test_hyperparameter_success_int(subtensor, mocker): + """Test when query_subtensor returns an integer value.""" + subtensor.subnet_exists = mocker.MagicMock(return_value=True) + subtensor.query_subtensor = mocker.MagicMock( + return_value=mocker.MagicMock(value=100) + ) + assert subtensor._get_hyperparameter("Difficulty", 1, None) == 100 + subtensor.subnet_exists.assert_called_once_with(1, None) + subtensor.query_subtensor.assert_called_once_with("Difficulty", None, [1]) + + +def test_hyperparameter_success_float(subtensor, mocker): + """Test when query_subtensor returns a float value.""" + subtensor.subnet_exists = mocker.MagicMock(return_value=True) + subtensor.query_subtensor = mocker.MagicMock( + return_value=mocker.MagicMock(value=0.5) + ) + assert subtensor._get_hyperparameter("Difficulty", 1, None) == 0.5 + subtensor.subnet_exists.assert_called_once_with(1, None) + subtensor.query_subtensor.assert_called_once_with("Difficulty", None, [1]) + + +def test_blocks_since_last_update_success_calls(subtensor, mocker): + """Tests the weights_rate_limit method to ensure it correctly fetches the LastUpdate hyperparameter.""" + # Prep + uid = 7 + mocked_current_block = 2 + mocked_result = {uid: 1} + subtensor._get_hyperparameter = mocker.MagicMock(return_value=mocked_result) + subtensor.get_current_block = mocker.MagicMock(return_value=mocked_current_block) + + # Call + result = subtensor.blocks_since_last_update(netuid=7, uid=uid) + + # Assertions + subtensor.get_current_block.assert_called_once() + subtensor._get_hyperparameter.assert_called_once_with( + param_name="LastUpdate", netuid=7 + ) + assert result == 1 + # if we change the methods logic in the future we have to be make sure the returned type is correct + assert isinstance(result, int) + + +def test_weights_rate_limit_success_calls(subtensor, mocker): + """Tests the weights_rate_limit method to ensure it correctly fetches the WeightsSetRateLimit hyperparameter.""" + # Prep + subtensor._get_hyperparameter = mocker.MagicMock(return_value=5) + + # Call + result = subtensor.weights_rate_limit(netuid=7) + + # Assertions + subtensor._get_hyperparameter.assert_called_once_with( + param_name="WeightsSetRateLimit", netuid=7 + ) + # if we change the methods logic in the future we have to be make sure the returned type is correct + assert isinstance(result, int) + + +@pytest.fixture +def sample_hyperparameters(): + return MagicMock(spec=SubnetHyperparameters) + + +def normalize_hyperparameters( + subnet: "SubnetHyperparameters", +) -> list[tuple[str, str, str]]: + """ + Normalizes the hyperparameters of a subnet. + + Args: + subnet: The subnet hyperparameters object. + + Returns: + A list of tuples containing the parameter name, value, and normalized value. + """ + param_mappings = { + "adjustment_alpha": u64_normalized_float, + "min_difficulty": u64_normalized_float, + "max_difficulty": u64_normalized_float, + "difficulty": u64_normalized_float, + "bonds_moving_avg": u64_normalized_float, + "max_weight_limit": u16_normalized_float, + "kappa": u16_normalized_float, + "alpha_high": u16_normalized_float, + "alpha_low": u16_normalized_float, + "min_burn": Balance.from_rao, + "max_burn": Balance.from_rao, + } + + normalized_values: list[tuple[str, str, str]] = [] + subnet_dict = subnet.__dict__ + + for param, value in subnet_dict.items(): + try: + if param in param_mappings: + norm_value = param_mappings[param](value) + if isinstance(norm_value, float): + norm_value = f"{norm_value:.{10}g}" + else: + norm_value = value + except Exception as e: + logging.warning(f"Error normalizing parameter '{param}': {e}") + norm_value = "-" + + normalized_values.append((param, str(value), str(norm_value))) + + return normalized_values + + +def get_normalized_value(normalized_data, param_name): + return next( + ( + norm_value + for p_name, _, norm_value in normalized_data + if p_name == param_name + ), + None, + ) + + +@pytest.mark.parametrize( + "param_name, max_value, mid_value, zero_value, is_balance", + [ + ("adjustment_alpha", U64_MAX, U64_MAX / 2, 0, False), + ("max_weight_limit", U16_MAX, U16_MAX / 2, 0, False), + ("difficulty", U64_MAX, U64_MAX / 2, 0, False), + ("min_difficulty", U64_MAX, U64_MAX / 2, 0, False), + ("max_difficulty", U64_MAX, U64_MAX / 2, 0, False), + ("bonds_moving_avg", U64_MAX, U64_MAX / 2, 0, False), + ("min_burn", 10000000000, 5000000000, 0, True), # These are in rao + ("max_burn", 20000000000, 10000000000, 0, True), + ], + ids=[ + "adjustment-alpha", + "max_weight_limit", + "difficulty", + "min_difficulty", + "max_difficulty", + "bonds_moving_avg", + "min_burn", + "max_burn", + ], +) +def test_hyperparameter_normalization( + sample_hyperparameters, param_name, max_value, mid_value, zero_value, is_balance +): + setattr(sample_hyperparameters, param_name, mid_value) + normalized = normalize_hyperparameters(sample_hyperparameters) + norm_value = get_normalized_value(normalized, param_name) + + # Mid-value test + if is_balance: + numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL)) + expected_tao = mid_value / 1e9 + assert ( + numeric_value == expected_tao + ), f"Mismatch in tao value for {param_name} at mid value" + else: + assert float(norm_value) == 0.5, f"Failed mid-point test for {param_name}" + + # Max-value test + setattr(sample_hyperparameters, param_name, max_value) + normalized = normalize_hyperparameters(sample_hyperparameters) + norm_value = get_normalized_value(normalized, param_name) + + if is_balance: + numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL)) + expected_tao = max_value / 1e9 + assert ( + numeric_value == expected_tao + ), f"Mismatch in tao value for {param_name} at max value" + else: + assert float(norm_value) == 1.0, f"Failed max value test for {param_name}" + + # Zero-value test + setattr(sample_hyperparameters, param_name, zero_value) + normalized = normalize_hyperparameters(sample_hyperparameters) + norm_value = get_normalized_value(normalized, param_name) + + if is_balance: + numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL)) + expected_tao = zero_value / 1e9 + assert ( + numeric_value == expected_tao + ), f"Mismatch in tao value for {param_name} at zero value" + else: + assert float(norm_value) == 0.0, f"Failed zero value test for {param_name}" + + +########################### +# Account functions tests # +########################### + + +# get_prometheus_info tests +def test_get_prometheus_info_success(mocker, subtensor): + """Test get_prometheus_info returns correct data when information is found.""" + # Prep + netuid = 1 + hotkey_ss58 = "test_hotkey" + block = 123 + mock_result = mocker.MagicMock( + value={ + "ip": 3232235777, # 192.168.1.1 + "ip_type": 4, + "port": 9090, + "version": "1.0", + "block": 1000, + } + ) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_prometheus_info(netuid, hotkey_ss58, block) + + # Asserts + assert result is not None + assert result.ip == "192.168.1.1" + assert result.ip_type == 4 + assert result.port == 9090 + assert result.version == "1.0" + assert result.block == 1000 + subtensor.query_subtensor.assert_called_once_with( + "Prometheus", block, [netuid, hotkey_ss58] + ) + + +def test_get_prometheus_info_no_data(mocker, subtensor): + """Test get_prometheus_info returns None when no information is found.""" + # Prep + netuid = 1 + hotkey_ss58 = "test_hotkey" + block = 123 + mocker.patch.object(subtensor, "query_subtensor", return_value=None) + + # Call + result = subtensor.get_prometheus_info(netuid, hotkey_ss58, block) + + # Asserts + assert result is None + subtensor.query_subtensor.assert_called_once_with( + "Prometheus", block, [netuid, hotkey_ss58] + ) + + +def test_get_prometheus_info_no_value_attribute(mocker, subtensor): + """Test get_prometheus_info returns None when result has no value attribute.""" + # Prep + netuid = 1 + hotkey_ss58 = "test_hotkey" + block = 123 + mock_result = mocker.MagicMock() + del mock_result.value + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_prometheus_info(netuid, hotkey_ss58, block) + + # Asserts + assert result is None + subtensor.query_subtensor.assert_called_once_with( + "Prometheus", block, [netuid, hotkey_ss58] + ) + + +def test_get_prometheus_info_no_block(mocker, subtensor): + """Test get_prometheus_info with no block specified.""" + # Prep + netuid = 1 + hotkey_ss58 = "test_hotkey" + mock_result = MagicMock( + value={ + "ip": "192.168.1.1", + "ip_type": 4, + "port": 9090, + "version": "1.0", + "block": 1000, + } + ) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_prometheus_info(netuid, hotkey_ss58) + + # Asserts + assert result is not None + assert result.ip == "192.168.1.1" + assert result.ip_type == 4 + assert result.port == 9090 + assert result.version == "1.0" + assert result.block == 1000 + subtensor.query_subtensor.assert_called_once_with( + "Prometheus", None, [netuid, hotkey_ss58] + ) + + +########################### +# Global Parameters tests # +########################### + + +# `block` property test +def test_block_property(mocker, subtensor): + """Test block property returns the correct block number.""" + expected_block = 123 + mocker.patch.object(subtensor, "get_current_block", return_value=expected_block) + + result = subtensor.block + + assert result == expected_block + subtensor.get_current_block.assert_called_once() + + +# `subnet_exists` tests +def test_subnet_exists_success(mocker, subtensor): + """Test subnet_exists returns True when subnet exists.""" + # Prep + netuid = 1 + block = 123 + mock_result = mocker.MagicMock(value=True) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.subnet_exists(netuid, block) + + # Asserts + assert result is True + subtensor.query_subtensor.assert_called_once_with("NetworksAdded", block, [netuid]) + + +def test_subnet_exists_no_data(mocker, subtensor): + """Test subnet_exists returns False when no subnet information is found.""" + # Prep + netuid = 1 + block = 123 + mocker.patch.object(subtensor, "query_subtensor", return_value=None) + + # Call + result = subtensor.subnet_exists(netuid, block) + + # Asserts + assert result is False + subtensor.query_subtensor.assert_called_once_with("NetworksAdded", block, [netuid]) + + +def test_subnet_exists_no_value_attribute(mocker, subtensor): + """Test subnet_exists returns False when result has no value attribute.""" + # Prep + netuid = 1 + block = 123 + mock_result = mocker.MagicMock() + del mock_result.value + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.subnet_exists(netuid, block) + + # Asserts + assert result is False + subtensor.query_subtensor.assert_called_once_with("NetworksAdded", block, [netuid]) + + +def test_subnet_exists_no_block(mocker, subtensor): + """Test subnet_exists with no block specified.""" + # Prep + netuid = 1 + mock_result = mocker.MagicMock(value=True) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.subnet_exists(netuid) + + # Asserts + assert result is True + subtensor.query_subtensor.assert_called_once_with("NetworksAdded", None, [netuid]) + + +# `get_total_subnets` tests +def test_get_total_subnets_success(mocker, subtensor): + """Test get_total_subnets returns correct data when total subnet information is found.""" + # Prep + block = 123 + total_subnets_value = 10 + mock_result = mocker.MagicMock(value=total_subnets_value) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_total_subnets(block) + + # Asserts + assert result is not None + assert result == total_subnets_value + subtensor.query_subtensor.assert_called_once_with("TotalNetworks", block) + + +def test_get_total_subnets_no_data(mocker, subtensor): + """Test get_total_subnets returns None when no total subnet information is found.""" + # Prep + block = 123 + mocker.patch.object(subtensor, "query_subtensor", return_value=None) + + # Call + result = subtensor.get_total_subnets(block) + + # Asserts + assert result is None + subtensor.query_subtensor.assert_called_once_with("TotalNetworks", block) + + +def test_get_total_subnets_no_value_attribute(mocker, subtensor): + """Test get_total_subnets returns None when result has no value attribute.""" + # Prep + block = 123 + mock_result = mocker.MagicMock() + del mock_result.value # Simulating a missing value attribute + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_total_subnets(block) + + # Asserts + assert result is None + subtensor.query_subtensor.assert_called_once_with("TotalNetworks", block) + + +def test_get_total_subnets_no_block(mocker, subtensor): + """Test get_total_subnets with no block specified.""" + # Prep + total_subnets_value = 10 + mock_result = mocker.MagicMock(value=total_subnets_value) + mocker.patch.object(subtensor, "query_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_total_subnets() + + # Asserts + assert result is not None + assert result == total_subnets_value + subtensor.query_subtensor.assert_called_once_with("TotalNetworks", None) + + +# `get_subnets` tests +def test_get_subnets_success(mocker, subtensor): + """Test get_subnets returns correct list when subnet information is found.""" + # Prep + block = 123 + mock_netuid1 = mocker.MagicMock(value=1) + mock_netuid2 = mocker.MagicMock(value=2) + mock_result = mocker.MagicMock() + mock_result.records = [(mock_netuid1, True), (mock_netuid2, True)] + mocker.patch.object(subtensor, "query_map_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_subnets(block) + + # Asserts + assert result == [1, 2] + subtensor.query_map_subtensor.assert_called_once_with("NetworksAdded", block) + + +def test_get_subnets_no_data(mocker, subtensor): + """Test get_subnets returns empty list when no subnet information is found.""" + # Prep + block = 123 + mock_result = mocker.MagicMock() + mock_result.records = [] + mocker.patch.object(subtensor, "query_map_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_subnets(block) + + # Asserts + assert result == [] + subtensor.query_map_subtensor.assert_called_once_with("NetworksAdded", block) + + +def test_get_subnets_no_records_attribute(mocker, subtensor): + """Test get_subnets returns empty list when result has no records attribute.""" + # Prep + block = 123 + mock_result = mocker.MagicMock() + del mock_result.records # Simulating a missing records attribute + mocker.patch.object(subtensor, "query_map_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_subnets(block) + + # Asserts + assert result == [] + subtensor.query_map_subtensor.assert_called_once_with("NetworksAdded", block) + + +def test_get_subnets_no_block_specified(mocker, subtensor): + """Test get_subnets with no block specified.""" + # Prep + mock_netuid1 = mocker.MagicMock(value=1) + mock_netuid2 = mocker.MagicMock(value=2) + mock_result = mocker.MagicMock() + mock_result.records = [(mock_netuid1, True), (mock_netuid2, True)] + mocker.patch.object(subtensor, "query_map_subtensor", return_value=mock_result) + + # Call + result = subtensor.get_subnets() + + # Asserts + assert result == [1, 2] + subtensor.query_map_subtensor.assert_called_once_with("NetworksAdded", None) + + +# `get_subnet_hyperparameters` tests +def test_get_subnet_hyperparameters_success(mocker, subtensor): + """Test get_subnet_hyperparameters returns correct data when hyperparameters are found.""" + # Prep + netuid = 1 + block = 123 + hex_bytes_result = "0x010203" + bytes_result = bytes.fromhex(hex_bytes_result[2:]) + mocker.patch.object(subtensor, "query_runtime_api", return_value=hex_bytes_result) + mocker.patch.object( + subtensor_module.SubnetHyperparameters, + "from_vec_u8", + return_value=["from_vec_u8"], + ) + + # Call + result = subtensor.get_subnet_hyperparameters(netuid, block) + + # Asserts + subtensor.query_runtime_api.assert_called_once_with( + runtime_api="SubnetInfoRuntimeApi", + method="get_subnet_hyperparams", + params=[netuid], + block=block, + ) + subtensor_module.SubnetHyperparameters.from_vec_u8.assert_called_once_with( + bytes_result + ) + + +def test_get_subnet_hyperparameters_hex_without_prefix(subtensor, mocker): + """Test get_subnet_hyperparameters correctly processes hex string without '0x' prefix.""" + # Prep + netuid = 1 + block = 123 + hex_bytes_result = "010203" + bytes_result = bytes.fromhex(hex_bytes_result) + mocker.patch.object(subtensor, "query_runtime_api", return_value=hex_bytes_result) + mocker.patch.object(subtensor_module.SubnetHyperparameters, "from_vec_u8") + + # Call + result = subtensor.get_subnet_hyperparameters(netuid, block) + + # Asserts + subtensor.query_runtime_api.assert_called_once_with( + runtime_api="SubnetInfoRuntimeApi", + method="get_subnet_hyperparams", + params=[netuid], + block=block, + ) + subtensor_module.SubnetHyperparameters.from_vec_u8.assert_called_once_with( + bytes_result + ) + + +def test_get_subnet_hyperparameters_no_data(mocker, subtensor): + """Test get_subnet_hyperparameters returns empty list when no data is found.""" + # Prep + netuid = 1 + block = 123 + mocker.patch.object(subtensor, "query_runtime_api", return_value=None) + mocker.patch.object(subtensor_module.SubnetHyperparameters, "from_vec_u8") + + # Call + result = subtensor.get_subnet_hyperparameters(netuid, block) + + # Asserts + assert result == [] + subtensor.query_runtime_api.assert_called_once_with( + runtime_api="SubnetInfoRuntimeApi", + method="get_subnet_hyperparams", + params=[netuid], + block=block, + ) + subtensor_module.SubnetHyperparameters.from_vec_u8.assert_not_called() + + +def test_query_subtensor(subtensor, mocker): + """Tests query_subtensor call.""" + # Prep + fake_name = "module_name" + + # Call + result = subtensor.query_subtensor(fake_name) + + # Asserts + subtensor.substrate.query.assert_called_once_with( + module="SubtensorModule", + storage_function=fake_name, + params=None, + block_hash=None, + ) + assert result == subtensor.substrate.query.return_value + + +def test_query_runtime_api(subtensor, mocker): + """Tests query_runtime_api call.""" + # Prep + fake_runtime_api = "NeuronInfoRuntimeApi" + fake_method = "get_neuron_lite" + + mocked_state_call = mocker.MagicMock() + subtensor.state_call = mocked_state_call + + mocked_runtime_configuration = mocker.patch.object( + subtensor_module, "RuntimeConfiguration" + ) + mocked_scalecodec = mocker.patch.object(subtensor_module.scalecodec, "ScaleBytes") + + # Call + result = subtensor.query_runtime_api(fake_runtime_api, fake_method, None) + + # Asserts + subtensor.state_call.assert_called_once_with( + method=f"{fake_runtime_api}_{fake_method}", data="0x", block=None + ) + mocked_scalecodec.assert_called_once_with( + subtensor.state_call.return_value.__getitem__.return_value + ) + mocked_runtime_configuration.assert_called_once() + mocked_runtime_configuration.return_value.update_type_registry.assert_called() + mocked_runtime_configuration.return_value.create_scale_object.assert_called() + assert ( + result + == mocked_runtime_configuration.return_value.create_scale_object.return_value.decode.return_value + ) + + +def test_query_map_subtensor(subtensor, mocker): + """Tests query_map_subtensor call.""" + # Prep + fake_name = "module_name" + + # Call + result = subtensor.query_map_subtensor(fake_name) + + # Asserts + subtensor.substrate.query_map.assert_called_once_with( + module="SubtensorModule", + storage_function=fake_name, + params=None, + block_hash=None, + ) + assert result == subtensor.substrate.query_map.return_value + + +def test_state_call(subtensor, mocker): + """Tests state_call call.""" + # Prep + fake_method = "method" + fake_data = "data" + + # Call + result = subtensor.state_call(fake_method, fake_data) + + # Asserts + subtensor.substrate.rpc_request.assert_called_once_with( + method="state_call", + params=[fake_method, fake_data], + ) + assert result == subtensor.substrate.rpc_request.return_value + + +def test_query_map(subtensor, mocker): + """Tests query_map call.""" + # Prep + fake_module_name = "module_name" + fake_name = "constant_name" + + # Call + result = subtensor.query_map(fake_module_name, fake_name) + + # Asserts + subtensor.substrate.query_map.assert_called_once_with( + module=fake_module_name, + storage_function=fake_name, + params=None, + block_hash=None, + ) + assert result == subtensor.substrate.query_map.return_value + + +def test_query_constant(subtensor, mocker): + """Tests query_constant call.""" + # Prep + fake_module_name = "module_name" + fake_constant_name = "constant_name" + + # Call + result = subtensor.query_constant(fake_module_name, fake_constant_name) + + # Asserts + subtensor.substrate.get_constant.assert_called_once_with( + module_name=fake_module_name, + constant_name=fake_constant_name, + block_hash=None, + ) + assert result == subtensor.substrate.get_constant.return_value + + +def test_query_module(subtensor): + # Prep + fake_module = "module" + fake_name = "function_name" + + # Call + result = subtensor.query_module(fake_module, fake_name) + + # Asserts + subtensor.substrate.query.assert_called_once_with( + module=fake_module, + storage_function=fake_name, + params=None, + block_hash=None, + ) + assert result == subtensor.substrate.query.return_value + + +def test_metagraph(subtensor, mocker): + """Tests subtensor.metagraph call.""" + # Prep + fake_netuid = 1 + fake_lite = True + mocked_metagraph = mocker.patch.object(subtensor_module, "Metagraph") + + # Call + result = subtensor.metagraph(fake_netuid, fake_lite) + + # Asserts + mocked_metagraph.assert_called_once_with( + network=subtensor.network, netuid=fake_netuid, lite=fake_lite, sync=False + ) + mocked_metagraph.return_value.sync.assert_called_once_with( + block=None, lite=fake_lite, subtensor=subtensor + ) + assert result == mocked_metagraph.return_value + + +def test_get_netuids_for_hotkey(subtensor, mocker): + """Tests get_netuids_for_hotkey call.""" + # Prep + fake_hotkey_ss58 = "hotkey_ss58" + fake_block = 123 + + mocked_query_map_subtensor = mocker.MagicMock() + subtensor.query_map_subtensor = mocked_query_map_subtensor + + # Call + result = subtensor.get_netuids_for_hotkey(fake_hotkey_ss58, fake_block) + + # Asserts + mocked_query_map_subtensor.assert_called_once_with( + "IsNetworkMember", fake_block, [fake_hotkey_ss58] + ) + assert result == [] + + +def test_get_current_block(subtensor): + """Tests get_current_block call.""" + # Call + result = subtensor.get_current_block() + + # Asserts + subtensor.substrate.get_block_number.assert_called_once_with(None) + assert result == subtensor.substrate.get_block_number.return_value + + +def test_is_hotkey_registered_any(subtensor, mocker): + """Tests is_hotkey_registered_any call""" + # Prep + fake_hotkey_ss58 = "hotkey_ss58" + fake_block = 123 + return_value = [1, 2] + + mocked_get_netuids_for_hotkey = mocker.MagicMock(return_value=return_value) + subtensor.get_netuids_for_hotkey = mocked_get_netuids_for_hotkey + + # Call + result = subtensor.is_hotkey_registered_any(fake_hotkey_ss58, fake_block) + + # Asserts + mocked_get_netuids_for_hotkey.assert_called_once_with(fake_hotkey_ss58, fake_block) + assert result is (len(return_value) > 0) + + +def test_is_hotkey_registered_on_subnet(subtensor, mocker): + """Tests is_hotkey_registered_on_subnet call.""" + # Prep + fake_hotkey_ss58 = "hotkey_ss58" + fake_netuid = 1 + fake_block = 123 + + mocked_get_uid_for_hotkey_on_subnet = mocker.MagicMock() + subtensor.get_uid_for_hotkey_on_subnet = mocked_get_uid_for_hotkey_on_subnet + + # Call + result = subtensor.is_hotkey_registered_on_subnet( + fake_hotkey_ss58, fake_netuid, fake_block + ) + + # Asserts + mocked_get_uid_for_hotkey_on_subnet.assert_called_once_with( + fake_hotkey_ss58, fake_netuid, fake_block + ) + assert result is (mocked_get_uid_for_hotkey_on_subnet.return_value is not None) + + +def test_is_hotkey_registered_without_netuid(subtensor, mocker): + """Tests is_hotkey_registered call with no netuid specified.""" + # Prep + fake_hotkey_ss58 = "hotkey_ss58" + + mocked_is_hotkey_registered_any = mocker.MagicMock() + subtensor.is_hotkey_registered_any = mocked_is_hotkey_registered_any + + # Call + + result = subtensor.is_hotkey_registered(fake_hotkey_ss58) + + # Asserts + mocked_is_hotkey_registered_any.assert_called_once_with(fake_hotkey_ss58, None) + assert result == mocked_is_hotkey_registered_any.return_value + + +def test_is_hotkey_registered_with_netuid(subtensor, mocker): + """Tests is_hotkey_registered call with netuid specified.""" + # Prep + fake_hotkey_ss58 = "hotkey_ss58" + fake_netuid = 123 + + mocked_is_hotkey_registered_on_subnet = mocker.MagicMock() + subtensor.is_hotkey_registered_on_subnet = mocked_is_hotkey_registered_on_subnet + + # Call + + result = subtensor.is_hotkey_registered(fake_hotkey_ss58, fake_netuid) + + # Asserts + mocked_is_hotkey_registered_on_subnet.assert_called_once_with( + fake_hotkey_ss58, fake_netuid, None + ) + assert result == mocked_is_hotkey_registered_on_subnet.return_value + + +def test_set_weights(subtensor, mocker): + """Successful set_weights call.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_netuid = 1 + fake_uids = [2, 4] + fake_weights = [0.4, 0.6] + fake_wait_for_inclusion = False + fake_wait_for_finalization = False + fake_prompt = False + fake_max_retries = 5 + + expected_result = (True, None) + + mocked_get_uid_for_hotkey_on_subnet = mocker.MagicMock() + subtensor.get_uid_for_hotkey_on_subnet = mocked_get_uid_for_hotkey_on_subnet + + mocked_blocks_since_last_update = mocker.MagicMock(return_value=2) + subtensor.blocks_since_last_update = mocked_blocks_since_last_update + + mocked_weights_rate_limit = mocker.MagicMock(return_value=1) + subtensor.weights_rate_limit = mocked_weights_rate_limit + + mocked_set_weights_extrinsic = mocker.patch.object( + subtensor_module, "set_weights_extrinsic", return_value=expected_result + ) + + # Call + result = subtensor.set_weights( + wallet=fake_wallet, + netuid=fake_netuid, + uids=fake_uids, + weights=fake_weights, + version_key=settings.version_as_int, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + prompt=fake_prompt, + max_retries=fake_max_retries, + ) + + # Asserts + mocked_get_uid_for_hotkey_on_subnet.assert_called_once_with( + fake_wallet.hotkey.ss58_address, fake_netuid + ) + mocked_blocks_since_last_update.assert_called_with( + fake_netuid, mocked_get_uid_for_hotkey_on_subnet.return_value + ) + mocked_weights_rate_limit.assert_called_with(fake_netuid) + mocked_set_weights_extrinsic.assert_called_with( + subtensor=subtensor, + wallet=fake_wallet, + netuid=fake_netuid, + uids=fake_uids, + weights=fake_weights, + version_key=settings.version_as_int, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + prompt=fake_prompt, + ) + assert result == expected_result + + +def test_serve_axon(subtensor, mocker): + """Tests successful serve_axon call.""" + # Prep + fake_netuid = 123 + fake_axon = mocker.MagicMock() + fake_wait_for_inclusion = False + fake_wait_for_finalization = True + + mocked_serve_axon_extrinsic = mocker.patch.object( + subtensor_module, "serve_axon_extrinsic" + ) + + # Call + result = subtensor.serve_axon( + fake_netuid, fake_axon, fake_wait_for_inclusion, fake_wait_for_finalization + ) + + # Asserts + mocked_serve_axon_extrinsic.assert_called_once_with( + subtensor, + fake_netuid, + fake_axon, + fake_wait_for_inclusion, + fake_wait_for_finalization, + ) + assert result == mocked_serve_axon_extrinsic.return_value + + +def test_get_block_hash(subtensor, mocker): + """Tests successful get_block_hash call.""" + # Prep + fake_block_id = 123 + + # Call + result = subtensor.get_block_hash(fake_block_id) + + # Asserts + subtensor.substrate.get_block_hash.assert_called_once_with(block_id=fake_block_id) + assert result == subtensor.substrate.get_block_hash.return_value + + +def test_commit(subtensor, mocker): + """Test successful commit call.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_netuid = 1 + fake_data = "some data to network" + mocked_publish_metadata = mocker.patch.object(subtensor_module, "publish_metadata") + + # Call + result = subtensor.commit(fake_wallet, fake_netuid, fake_data) + + # Asserts + mocked_publish_metadata.assert_called_once_with( + subtensor, fake_wallet, fake_netuid, f"Raw{len(fake_data)}", fake_data.encode() + ) + assert result is None + + +def test_subnetwork_n(subtensor, mocker): + """Test successful subnetwork_n call.""" + # Prep + fake_netuid = 1 + fake_block = 123 + fake_result = 2 + + mocked_get_hyperparameter = mocker.MagicMock() + mocked_get_hyperparameter.return_value = fake_result + subtensor._get_hyperparameter = mocked_get_hyperparameter + + # Call + result = subtensor.subnetwork_n(fake_netuid, fake_block) + + # Asserts + mocked_get_hyperparameter.assert_called_once_with( + param_name="SubnetworkN", netuid=fake_netuid, block=fake_block + ) + assert result == mocked_get_hyperparameter.return_value + + +def test_transfer(subtensor, mocker): + """Tests successful transfer call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_dest = "SS58PUBLICKEY" + fake_amount = 1.1 + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + fake_prompt = False + mocked_transfer_extrinsic = mocker.patch.object( + subtensor_module, "transfer_extrinsic" + ) + + # Call + result = subtensor.transfer( + fake_wallet, + fake_dest, + fake_amount, + fake_wait_for_inclusion, + fake_wait_for_finalization, + fake_prompt, + ) + + # Asserts + mocked_transfer_extrinsic.assert_called_once_with( + subtensor=subtensor, + wallet=fake_wallet, + dest=fake_dest, + amount=fake_amount, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + prompt=fake_prompt, + ) + assert result == mocked_transfer_extrinsic.return_value + + +def test_get_neuron_for_pubkey_and_subnet(subtensor, mocker): + """Successful call to get_neuron_for_pubkey_and_subnet.""" + # Prep + fake_hotkey_ss58 = "fake_hotkey" + fake_netuid = 1 + fake_block = 123 + + mocked_neuron_for_uid = mocker.MagicMock() + subtensor.neuron_for_uid = mocked_neuron_for_uid + + mocked_get_uid_for_hotkey_on_subnet = mocker.MagicMock() + subtensor.get_uid_for_hotkey_on_subnet = mocked_get_uid_for_hotkey_on_subnet + + # Call + result = subtensor.get_neuron_for_pubkey_and_subnet( + hotkey_ss58=fake_hotkey_ss58, + netuid=fake_netuid, + block=fake_block, + ) + + # Asserts + mocked_neuron_for_uid.assert_called_once_with( + mocked_get_uid_for_hotkey_on_subnet.return_value, + fake_netuid, + block=fake_block, + ) + assert result == mocked_neuron_for_uid.return_value + + +def test_neuron_for_uid_none(subtensor, mocker): + """Test neuron_for_uid successful call.""" + # Prep + fake_uid = None + fake_netuid = 2 + fake_block = 123 + mocked_neuron_info = mocker.patch.object( + subtensor_module.NeuronInfo, "get_null_neuron" + ) + + # Call + result = subtensor.neuron_for_uid( + uid=fake_uid, netuid=fake_netuid, block=fake_block + ) + + # Asserts + mocked_neuron_info.assert_called_once() + assert result == mocked_neuron_info.return_value + + +def test_neuron_for_uid_response_none(subtensor, mocker): + """Test neuron_for_uid successful call.""" + # Prep + fake_uid = 1 + fake_netuid = 2 + fake_block = 123 + mocked_neuron_info = mocker.patch.object( + subtensor_module.NeuronInfo, "get_null_neuron" + ) + + subtensor.substrate.rpc_request.return_value.get.return_value = None + + # Call + result = subtensor.neuron_for_uid( + uid=fake_uid, netuid=fake_netuid, block=fake_block + ) + + # Asserts + subtensor.substrate.get_block_hash.assert_called_once_with(fake_block) + subtensor.substrate.rpc_request.assert_called_once_with( + method="neuronInfo_getNeuron", + params=[fake_netuid, fake_uid, subtensor.substrate.get_block_hash.return_value], + ) + + mocked_neuron_info.assert_called_once() + assert result == mocked_neuron_info.return_value + + +def test_neuron_for_uid_success(subtensor, mocker): + """Test neuron_for_uid successful call.""" + # Prep + fake_uid = 1 + fake_netuid = 2 + fake_block = 123 + mocked_neuron_from_vec_u8 = mocker.patch.object( + subtensor_module.NeuronInfo, "from_vec_u8" + ) + + # Call + result = subtensor.neuron_for_uid( + uid=fake_uid, netuid=fake_netuid, block=fake_block + ) + + # Asserts + subtensor.substrate.get_block_hash.assert_called_once_with(fake_block) + subtensor.substrate.rpc_request.assert_called_once_with( + method="neuronInfo_getNeuron", + params=[fake_netuid, fake_uid, subtensor.substrate.get_block_hash.return_value], + ) + + mocked_neuron_from_vec_u8.assert_called_once_with( + subtensor.substrate.rpc_request.return_value.get.return_value + ) + assert result == mocked_neuron_from_vec_u8.return_value + + +def test_do_serve_prometheus_is_success(subtensor, mocker): + """Successful do_serve_prometheus call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = True + + # Call + result = subtensor._do_serve_prometheus( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_prometheus", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == (True, None) + + +def test_do_serve_prometheus_is_not_success(subtensor, mocker): + """Unsuccessful do_serve_axon call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = None + + # Call + result = subtensor._do_serve_prometheus( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_prometheus", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == ( + False, + subtensor.substrate.submit_extrinsic.return_value.error_message, + ) + + +def test_do_serve_prometheus_no_waits(subtensor, mocker): + """Unsuccessful do_serve_axon call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = False + fake_wait_for_finalization = False + + # Call + result = subtensor._do_serve_prometheus( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_prometheus", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + assert result == (True, None) + + +def test_serve_prometheus(subtensor, mocker): + """Test serve_prometheus function successful call.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_port = 1234 + fake_netuid = 1 + wait_for_inclusion = True + wait_for_finalization = False + + mocked_prometheus_extrinsic = mocker.patch.object( + subtensor_module, "prometheus_extrinsic" + ) + + # Call + result = subtensor.serve_prometheus( + fake_wallet, + fake_port, + fake_netuid, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + # Asserts + mocked_prometheus_extrinsic.assert_called_once_with( + subtensor, + wallet=fake_wallet, + port=fake_port, + netuid=fake_netuid, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + ) + + assert result == mocked_prometheus_extrinsic.return_value + + +def test_do_serve_axon_is_success(subtensor, mocker): + """Successful do_serve_axon call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = True + + # Call + result = subtensor._do_serve_axon( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_axon", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == (True, None) + + +def test_do_serve_axon_is_not_success(subtensor, mocker): + """Unsuccessful do_serve_axon call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = True + fake_wait_for_finalization = True + + subtensor.substrate.submit_extrinsic.return_value.is_success = None + + # Call + result = subtensor._do_serve_axon( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_axon", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + subtensor.substrate.submit_extrinsic.return_value.process_events.assert_called_once() + assert result == ( + False, + subtensor.substrate.submit_extrinsic.return_value.error_message, + ) + + +def test_do_serve_axon_no_waits(subtensor, mocker): + """Unsuccessful do_serve_axon call.""" + # Prep + fake_wallet = mocker.MagicMock() + fake_call_params = mocker.MagicMock() + fake_wait_for_inclusion = False + fake_wait_for_finalization = False + + # Call + result = subtensor._do_serve_axon( + wallet=fake_wallet, + call_params=fake_call_params, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="SubtensorModule", + call_function="serve_axon", + call_params=fake_call_params, + ) + + subtensor.substrate.create_signed_extrinsic.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.hotkey, + ) + + subtensor.substrate.submit_extrinsic.assert_called_once_with( + subtensor.substrate.create_signed_extrinsic.return_value, + wait_for_inclusion=fake_wait_for_inclusion, + wait_for_finalization=fake_wait_for_finalization, + ) + assert result == (True, None) + + +def test_immunity_period(subtensor, mocker): + """Successful immunity_period call.""" + # Preps + fake_netuid = 1 + fake_block = 123 + fare_result = 101 + + mocked_get_hyperparameter = mocker.MagicMock() + mocked_get_hyperparameter.return_value = fare_result + subtensor._get_hyperparameter = mocked_get_hyperparameter + + # Call + result = subtensor.immunity_period(netuid=fake_netuid, block=fake_block) + + # Assertions + mocked_get_hyperparameter.assert_called_once_with( + param_name="ImmunityPeriod", + netuid=fake_netuid, + block=fake_block, + ) + assert result == mocked_get_hyperparameter.return_value + + +def test_get_uid_for_hotkey_on_subnet(subtensor, mocker): + """Successful get_uid_for_hotkey_on_subnet call.""" + # Prep + fake_hotkey_ss58 = "fake_hotkey_ss58" + fake_netuid = 1 + fake_block = 123 + mocked_query_subtensor = mocker.MagicMock() + subtensor.query_subtensor = mocked_query_subtensor + + # Call + result = subtensor.get_uid_for_hotkey_on_subnet( + hotkey_ss58=fake_hotkey_ss58, netuid=fake_netuid, block=fake_block + ) + + # Assertions + mocked_query_subtensor.assert_called_once_with( + "Uids", fake_block, [fake_netuid, fake_hotkey_ss58] + ) + + assert result == mocked_query_subtensor.return_value.value + + +def test_tempo(subtensor, mocker): + """Successful tempo call.""" + # Preps + fake_netuid = 1 + fake_block = 123 + fare_result = 101 + + mocked_get_hyperparameter = mocker.MagicMock() + mocked_get_hyperparameter.return_value = fare_result + subtensor._get_hyperparameter = mocked_get_hyperparameter + + # Call + result = subtensor.tempo(netuid=fake_netuid, block=fake_block) + + # Assertions + mocked_get_hyperparameter.assert_called_once_with( + param_name="Tempo", + netuid=fake_netuid, + block=fake_block, + ) + assert result == mocked_get_hyperparameter.return_value + + +def test_get_commitment(subtensor, mocker): + """Successful get_commitment call.""" + # Preps + fake_netuid = 1 + fake_uid = 2 + fake_block = 3 + fake_hotkey = "hotkey" + fake_hex_data = "0x010203" + expected_result = bytes.fromhex(fake_hex_data[2:]).decode() + + mocked_metagraph = mocker.MagicMock() + subtensor.metagraph = mocked_metagraph + mocked_metagraph.return_value.hotkeys = {fake_uid: fake_hotkey} + + mocked_get_metadata = mocker.patch.object(subtensor_module, "get_metadata") + mocked_get_metadata.return_value = { + "info": {"fields": [{fake_hex_data: fake_hex_data}]} + } + + # Call + result = subtensor.get_commitment( + netuid=fake_netuid, uid=fake_uid, block=fake_block + ) + + # Assertions + mocked_metagraph.assert_called_once_with(fake_netuid) + assert result == expected_result + + +def test_min_allowed_weights(subtensor, mocker): + """Successful min_allowed_weights call.""" + fake_netuid = 1 + fake_block = 123 + return_value = 10 + + mocked_get_hyperparameter = mocker.MagicMock(return_value=return_value) + subtensor._get_hyperparameter = mocked_get_hyperparameter + + # Call + result = subtensor.min_allowed_weights(netuid=fake_netuid, block=fake_block) + + # Assertion + mocked_get_hyperparameter.assert_called_once_with( + param_name="MinAllowedWeights", block=fake_block, netuid=fake_netuid + ) + assert result == return_value + + +def test_max_weight_limit(subtensor, mocker): + """Successful max_weight_limit call.""" + fake_netuid = 1 + fake_block = 123 + return_value = 100 + + mocked_get_hyperparameter = mocker.MagicMock(return_value=return_value) + subtensor._get_hyperparameter = mocked_get_hyperparameter + + mocked_u16_normalized_float = mocker.MagicMock() + subtensor_module.u16_normalized_float = mocked_u16_normalized_float + + # Call + result = subtensor.max_weight_limit(netuid=fake_netuid, block=fake_block) + + # Assertion + mocked_get_hyperparameter.assert_called_once_with( + param_name="MaxWeightsLimit", block=fake_block, netuid=fake_netuid + ) + assert result == mocked_u16_normalized_float.return_value + + +def test_get_transfer_fee(subtensor, mocker): + """Successful get_transfer_fee call.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_dest = "SS58ADDRESS" + value = 1 + + fake_payment_info = {"partialFee": int(2e10)} + subtensor.substrate.get_payment_info.return_value = fake_payment_info + + # Call + result = subtensor.get_transfer_fee(wallet=fake_wallet, dest=fake_dest, value=value) + + # Asserts + subtensor.substrate.compose_call.assert_called_once_with( + call_module="Balances", + call_function="transfer_allow_death", + call_params={"dest": fake_dest, "value": value}, + ) + + subtensor.substrate.get_payment_info.assert_called_once_with( + call=subtensor.substrate.compose_call.return_value, + keypair=fake_wallet.coldkeypub, + ) + + assert result == 2e10 + + +def test_get_transfer_fee_incorrect_value(subtensor, mocker): + """Successful get_transfer_fee call.""" + # Preps + fake_wallet = mocker.MagicMock() + fake_dest = mocker.MagicMock() + value = "no_int_no_float_no_Balance" + + mocked_substrate = mocker.MagicMock() + subtensor.substrate = mocked_substrate + spy_balance_from_rao = mocker.spy(Balance, "from_rao") + + # Call + result = subtensor.get_transfer_fee(wallet=fake_wallet, dest=fake_dest, value=value) + + # Asserts + spy_balance_from_rao.assert_called_once_with(2e7) + + assert result == Balance.from_rao(int(2e7)) + + +def test_get_existential_deposit(subtensor, mocker): + """Successful get_existential_deposit call.""" + # Prep + block = 123 + + mocked_query_constant = mocker.MagicMock() + value = 10 + mocked_query_constant.return_value.value = value + subtensor.query_constant = mocked_query_constant + + # Call + result = subtensor.get_existential_deposit(block=block) + + # Assertions + mocked_query_constant.assert_called_once_with( + module_name="Balances", constant_name="ExistentialDeposit", block=block + ) + + assert isinstance(result, Balance) + assert result == Balance.from_rao(value) + + +def test_commit_weights(subtensor, mocker): + """Successful commit_weights call.""" + # Preps + fake_wallet = mocker.MagicMock() + netuid = 1 + salt = [1, 3] + uids = [2, 4] + weights = [0.4, 0.6] + wait_for_inclusion = False + wait_for_finalization = False + prompt = False + max_retries = 5 + + expected_result = (True, None) + mocked_generate_weight_hash = mocker.patch.object( + subtensor_module, "generate_weight_hash", return_value=expected_result + ) + mocked_commit_weights_extrinsic = mocker.patch.object( + subtensor_module, "commit_weights_extrinsic", return_value=expected_result + ) + + # Call + result = subtensor.commit_weights( + wallet=fake_wallet, + netuid=netuid, + salt=salt, + uids=uids, + weights=weights, + version_key=settings.version_as_int, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + max_retries=max_retries, + ) + + # Asserts + mocked_generate_weight_hash.assert_called_once_with( + address=fake_wallet.hotkey.ss58_address, + netuid=netuid, + uids=list(uids), + values=list(weights), + salt=list(salt), + version_key=settings.version_as_int, + ) + + mocked_commit_weights_extrinsic.assert_called_once_with( + subtensor=subtensor, + wallet=fake_wallet, + netuid=netuid, + commit_hash=mocked_generate_weight_hash.return_value, + wait_for_inclusion=wait_for_inclusion, + wait_for_finalization=wait_for_finalization, + prompt=prompt, + ) + assert result == expected_result + + +def test_reveal_weights(subtensor, mocker): + """Successful test_reveal_weights call.""" + # Preps + fake_wallet = mocker.MagicMock() + netuid = 1 + uids = [1, 2, 3, 4] + weights = [0.1, 0.2, 0.3, 0.4] + salt = [4, 2, 2, 1] + expected_result = (True, None) + mocked_extrinsic = mocker.patch.object( + subtensor_module, "reveal_weights_extrinsic", return_value=expected_result + ) + + # Call + result = subtensor.reveal_weights( + wallet=fake_wallet, + netuid=netuid, + uids=uids, + weights=weights, + salt=salt, + wait_for_inclusion=False, + wait_for_finalization=False, + prompt=False, + ) + + # Assertions + assert result == (True, None) + mocked_extrinsic.assert_called_once_with( + subtensor=subtensor, + wallet=fake_wallet, + netuid=netuid, + uids=uids, + version_key=version_as_int, + weights=weights, + salt=salt, + wait_for_inclusion=False, + wait_for_finalization=False, + prompt=False, + ) + + +def test_reveal_weights_false(subtensor, mocker): + """Failed test_reveal_weights call.""" + # Preps + fake_wallet = mocker.MagicMock() + netuid = 1 + uids = [1, 2, 3, 4] + weights = [0.1, 0.2, 0.3, 0.4] + salt = [4, 2, 2, 1] + + expected_result = ( + False, + "No attempt made. Perhaps it is too soon to reveal weights!", + ) + mocked_extrinsic = mocker.patch.object(subtensor_module, "reveal_weights_extrinsic") + + # Call + result = subtensor.reveal_weights( + wallet=fake_wallet, + netuid=netuid, + uids=uids, + weights=weights, + salt=salt, + wait_for_inclusion=False, + wait_for_finalization=False, + prompt=False, + ) + + # Assertion + assert result == expected_result + assert mocked_extrinsic.call_count == 5 + + +def test_connect_without_substrate(mocker): + """Ensure re-connection is called when using an alive substrate.""" + # Prep + fake_substrate = mocker.MagicMock() + fake_substrate.websocket.sock.getsockopt.return_value = 1 + mocker.patch.object( + subtensor_module, "SubstrateInterface", return_value=fake_substrate + ) + fake_subtensor = Subtensor() + spy_get_substrate = mocker.spy(Subtensor, "_get_substrate") + + # Call + _ = fake_subtensor.block + + # Assertions + assert spy_get_substrate.call_count == 1 + + +def test_connect_with_substrate(mocker): + """Ensure re-connection is non called when using an alive substrate.""" + # Prep + fake_substrate = mocker.MagicMock() + fake_substrate.websocket.sock.getsockopt.return_value = 0 + mocker.patch.object( + subtensor_module, "SubstrateInterface", return_value=fake_substrate + ) + fake_subtensor = Subtensor() + spy_get_substrate = mocker.spy(Subtensor, "_get_substrate") + + # Call + _ = fake_subtensor.block + + # Assertions + assert spy_get_substrate.call_count == 0 diff --git a/tests/unit_tests/test_synapse.py b/tests/unit_tests/test_synapse.py new file mode 100644 index 0000000000..80c127c587 --- /dev/null +++ b/tests/unit_tests/test_synapse.py @@ -0,0 +1,269 @@ +# The MIT License (MIT) +# Copyright © 2024 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 base64 +import json +from typing import Optional, ClassVar + +import pytest + +from bittensor.core.synapse import Synapse + + +def test_parse_headers_to_inputs(): + class Test(Synapse): + key1: list[int] + + # Define a mock headers dictionary to use for testing + headers = { + "bt_header_axon_nonce": "111", + "bt_header_dendrite_ip": "12.1.1.2", + "bt_header_input_obj_key1": base64.b64encode( + json.dumps([1, 2, 3, 4]).encode("utf-8") + ).decode("utf-8"), + "timeout": "12", + "name": "Test", + "header_size": "111", + "total_size": "111", + "computed_body_hash": "0xabcdef", + } + print(headers) + + # Run the function to test + inputs_dict = Test.parse_headers_to_inputs(headers) + print(inputs_dict) + # Check the resulting dictionary + assert inputs_dict == { + "axon": {"nonce": "111"}, + "dendrite": {"ip": "12.1.1.2"}, + "key1": [1, 2, 3, 4], + "timeout": "12", + "name": "Test", + "header_size": "111", + "total_size": "111", + "computed_body_hash": "0xabcdef", + } + + +def test_from_headers(): + class Test(Synapse): + key1: list[int] + + # Define a mock headers dictionary to use for testing + headers = { + "bt_header_axon_nonce": "111", + "bt_header_dendrite_ip": "12.1.1.2", + "bt_header_input_obj_key1": base64.b64encode( + json.dumps([1, 2, 3, 4]).encode("utf-8") + ).decode("utf-8"), + "timeout": "12", + "name": "Test", + "header_size": "111", + "total_size": "111", + "computed_body_hash": "0xabcdef", + } + + # Run the function to test + synapse = Test.from_headers(headers) + + # Check that the resulting object is an instance of YourClass + assert isinstance(synapse, Test) + + # Check the properties of the resulting object + # Replace with actual checks based on the structure of your class + assert synapse.axon.nonce == 111 + assert synapse.dendrite.ip == "12.1.1.2" + assert synapse.key1 == [1, 2, 3, 4] + assert synapse.timeout == 12 + assert synapse.name == "Test" + assert synapse.header_size == 111 + assert synapse.total_size == 111 + + +def test_synapse_create(): + # Create an instance of Synapse + synapse = Synapse() + + # Ensure the instance created is of type Synapse + assert isinstance(synapse, Synapse) + + # Check default properties of a newly created Synapse + assert synapse.name == "Synapse" + assert synapse.timeout == 12.0 + assert synapse.header_size == 0 + assert synapse.total_size == 0 + + # Convert the Synapse instance to a headers dictionary + headers = synapse.to_headers() + + # Ensure the headers is a dictionary and contains the expected keys + assert isinstance(headers, dict) + assert "timeout" in headers + assert "name" in headers + assert "header_size" in headers + assert "total_size" in headers + + # Ensure the 'name' and 'timeout' values match the Synapse's properties + assert headers["name"] == "Synapse" + assert headers["timeout"] == "12.0" + + # Create a new Synapse from the headers and check its 'timeout' property + next_synapse = synapse.from_headers(synapse.to_headers()) + assert next_synapse.timeout == 12.0 + + +def test_custom_synapse(): + # Define a custom Synapse subclass + class Test(Synapse): + a: int # Carried through because required. + b: int = None # Not carried through headers + c: Optional[int] # Required, carried through headers, cannot be None + d: Optional[list[int]] # Required, carried though headers, cannot be None + e: list[int] # Carried through headers + f: Optional[int] = ( + None # Not Required, Not carried through headers, can be None + ) + g: Optional[list[int]] = ( + None # Not Required, Not carried though headers, can be None + ) + + # Create an instance of the custom Synapse subclass + synapse = Test( + a=1, + c=3, + d=[1, 2, 3, 4], + e=[1, 2, 3, 4], + ) + + # Ensure the instance created is of type Test and has the expected properties + assert isinstance(synapse, Test) + assert synapse.name == "Test" + assert synapse.a == 1 + assert synapse.b is None + assert synapse.c == 3 + assert synapse.d == [1, 2, 3, 4] + assert synapse.e == [1, 2, 3, 4] + assert synapse.f is None + assert synapse.g is None + + # Convert the Test instance to a headers dictionary + headers = synapse.to_headers() + + # Ensure the headers contains 'a' but not 'b' + assert "bt_header_input_obj_a" in headers + assert "bt_header_input_obj_b" not in headers + + # Create a new Test from the headers and check its properties + next_synapse = synapse.from_headers(synapse.to_headers()) + assert next_synapse.a == 0 # Default value is 0 + assert next_synapse.b is None + assert next_synapse.c == 0 # Default is 0 + assert next_synapse.d == [] # Default is [] + assert next_synapse.e == [] # Empty list is default for list types + assert next_synapse.f is None + assert next_synapse.g is None + + +def test_body_hash_override(): + # Create a Synapse instance + synapse_instance = Synapse() + + # Try to set the body_hash property and expect an AttributeError + with pytest.raises( + AttributeError, + match="body_hash property is read-only and cannot be overridden.", + ): + synapse_instance.body_hash = [] + + +def test_default_instance_fields_dict_consistency(): + synapse_instance = Synapse() + assert synapse_instance.model_dump() == { + "name": "Synapse", + "timeout": 12.0, + "total_size": 0, + "header_size": 0, + "dendrite": { + "status_code": None, + "status_message": None, + "process_time": None, + "ip": None, + "port": None, + "version": None, + "nonce": None, + "uuid": None, + "hotkey": None, + "signature": None, + }, + "axon": { + "status_code": None, + "status_message": None, + "process_time": None, + "ip": None, + "port": None, + "version": None, + "nonce": None, + "uuid": None, + "hotkey": None, + "signature": None, + }, + "computed_body_hash": "", + } + + +class LegacyHashedSynapse(Synapse): + """Legacy Synapse subclass that serialized `required_hash_fields`.""" + + a: int + b: int + c: Optional[int] = None + d: Optional[list[str]] = None + required_hash_fields: Optional[list[str]] = ["b", "a", "d"] + + +class HashedSynapse(Synapse): + a: int + b: int + c: Optional[int] = None + d: Optional[list[str]] = None + required_hash_fields: ClassVar[tuple[str, ...]] = ("a", "b", "d") + + +@pytest.mark.parametrize("synapse_cls", [LegacyHashedSynapse, HashedSynapse]) +def test_synapse_body_hash(synapse_cls): + synapse_instance = synapse_cls(a=1, b=2, d=["foobar"]) + assert ( + synapse_instance.body_hash + == "ae06397d08f30f75c91395c59f05c62ac3b62b88250eb78b109213258e6ced0c" + ) + + # Extra non-hashed values should not influence the body hash + synapse_instance_slightly_different = synapse_cls(d=["foobar"], c=3, a=1, b=2) + assert synapse_instance.body_hash == synapse_instance_slightly_different.body_hash + + # Even if someone tries to override the required_hash_fields, it should still be the same + synapse_instance_try_override_hash_fields = synapse_cls( + a=1, b=2, d=["foobar"], required_hash_fields=["a"] + ) + assert ( + synapse_instance.body_hash + == synapse_instance_try_override_hash_fields.body_hash + ) + + # Different hashed values should result in different body hashes + synapse_different = synapse_cls(a=1, b=2) + assert synapse_instance.body_hash != synapse_different.body_hash diff --git a/tests/unit_tests/test_tensor.py b/tests/unit_tests/test_tensor.py new file mode 100644 index 0000000000..8bf7bf06ac --- /dev/null +++ b/tests/unit_tests/test_tensor.py @@ -0,0 +1,245 @@ +# The MIT License (MIT) +# Copyright © 2024 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 numpy +import numpy as np +import pytest +import torch + +from bittensor.core.tensor import Tensor + + +# This is a fixture that creates an example tensor for testing +@pytest.fixture +def example_tensor(): + # Create a tensor from a list using PyTorch + data = np.array([1, 2, 3, 4]) + + # Serialize the tensor into a Tensor instance and return it + return Tensor.serialize(data) + + +@pytest.fixture +def example_tensor_torch(force_legacy_torch_compatible_api): + # Create a tensor from a list using PyTorch + data = torch.tensor([1, 2, 3, 4]) + + # Serialize the tensor into a Tensor instance and return it + return Tensor.serialize(data) + + +def test_deserialize(example_tensor): + # Deserialize the tensor from the Tensor instance + tensor = example_tensor.deserialize() + + # Check that the result is a np.array with the correct values + assert isinstance(tensor, np.ndarray) + assert tensor.tolist() == [1, 2, 3, 4] + + +def test_deserialize_torch(example_tensor_torch, force_legacy_torch_compatible_api): + tensor = example_tensor_torch.deserialize() + # Check that the result is a PyTorch tensor with the correct values + assert isinstance(tensor, torch.Tensor) + assert tensor.tolist() == [1, 2, 3, 4] + + +def test_serialize(example_tensor): + # Check that the serialized tensor is an instance of Tensor + assert isinstance(example_tensor, Tensor) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor.buffer == example_tensor.buffer + assert example_tensor.dtype == example_tensor.dtype + assert example_tensor.shape == example_tensor.shape + + assert isinstance(example_tensor.tolist(), list) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor.buffer == example_tensor.buffer + assert example_tensor.dtype == example_tensor.dtype + assert example_tensor.shape == example_tensor.shape + + assert isinstance(example_tensor.numpy(), numpy.ndarray) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor.buffer == example_tensor.buffer + assert example_tensor.dtype == example_tensor.dtype + assert example_tensor.shape == example_tensor.shape + + assert isinstance(example_tensor.tensor(), np.ndarray) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor.buffer == example_tensor.buffer + assert example_tensor.dtype == example_tensor.dtype + assert example_tensor.shape == example_tensor.shape + + +def test_serialize_torch(example_tensor_torch, force_legacy_torch_compatible_api): + # Check that the serialized tensor is an instance of Tensor + assert isinstance(example_tensor_torch, Tensor) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor_torch.buffer == example_tensor_torch.buffer + assert example_tensor_torch.dtype == example_tensor_torch.dtype + assert example_tensor_torch.shape == example_tensor_torch.shape + + assert isinstance(example_tensor_torch.tolist(), list) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor_torch.buffer == example_tensor_torch.buffer + assert example_tensor_torch.dtype == example_tensor_torch.dtype + assert example_tensor_torch.shape == example_tensor_torch.shape + + assert isinstance(example_tensor_torch.numpy(), numpy.ndarray) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor_torch.buffer == example_tensor_torch.buffer + assert example_tensor_torch.dtype == example_tensor_torch.dtype + assert example_tensor_torch.shape == example_tensor_torch.shape + + assert isinstance(example_tensor_torch.tensor(), torch.Tensor) + + # Check that the Tensor instance has the correct buffer, dtype, and shape + assert example_tensor_torch.buffer == example_tensor_torch.buffer + assert example_tensor_torch.dtype == example_tensor_torch.dtype + assert example_tensor_torch.shape == example_tensor_torch.shape + + +def test_buffer_field(): + # Create a Tensor instance with a specified buffer, dtype, and shape + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="float32", shape=[3, 3] + ) + + # Check that the buffer field matches the provided value + assert tensor.buffer == "0x321e13edqwds231231231232131" + + +def test_buffer_field_torch(force_legacy_torch_compatible_api): + # Create a Tensor instance with a specified buffer, dtype, and shape + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="torch.float32", shape=[3, 3] + ) + + # Check that the buffer field matches the provided value + assert tensor.buffer == "0x321e13edqwds231231231232131" + + +def test_dtype_field(): + # Create a Tensor instance with a specified buffer, dtype, and shape + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="float32", shape=[3, 3] + ) + + # Check that the dtype field matches the provided value + assert tensor.dtype == "float32" + + +def test_dtype_field_torch(force_legacy_torch_compatible_api): + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="torch.float32", shape=[3, 3] + ) + assert tensor.dtype == "torch.float32" + + +def test_shape_field(): + # Create a Tensor instance with a specified buffer, dtype, and shape + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="float32", shape=[3, 3] + ) + + # Check that the shape field matches the provided value + assert tensor.shape == [3, 3] + + +def test_shape_field_torch(force_legacy_torch_compatible_api): + tensor = Tensor( + buffer="0x321e13edqwds231231231232131", dtype="torch.float32", shape=[3, 3] + ) + assert tensor.shape == [3, 3] + + +def test_serialize_all_types(): + Tensor.serialize(np.array([1], dtype=np.float16)) + Tensor.serialize(np.array([1], dtype=np.float32)) + Tensor.serialize(np.array([1], dtype=np.float64)) + Tensor.serialize(np.array([1], dtype=np.uint8)) + Tensor.serialize(np.array([1], dtype=np.int32)) + Tensor.serialize(np.array([1], dtype=np.int64)) + Tensor.serialize(np.array([1], dtype=bool)) + + +def test_serialize_all_types_torch(force_legacy_torch_compatible_api): + Tensor.serialize(torch.tensor([1], dtype=torch.float16)) + Tensor.serialize(torch.tensor([1], dtype=torch.float32)) + Tensor.serialize(torch.tensor([1], dtype=torch.float64)) + Tensor.serialize(torch.tensor([1], dtype=torch.uint8)) + Tensor.serialize(torch.tensor([1], dtype=torch.int32)) + Tensor.serialize(torch.tensor([1], dtype=torch.int64)) + Tensor.serialize(torch.tensor([1], dtype=torch.bool)) + + +def test_serialize_all_types_equality(): + rng = np.random.default_rng() + + tensor = rng.standard_normal((100,), dtype=np.float32) + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + tensor = rng.standard_normal((100,), dtype=np.float64) + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + tensor = np.random.randint(255, 256, (1000,), dtype=np.uint8) + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + tensor = np.random.randint(2_147_483_646, 2_147_483_647, (1000,), dtype=np.int32) + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + tensor = np.random.randint( + 9_223_372_036_854_775_806, 9_223_372_036_854_775_807, (1000,), dtype=np.int64 + ) + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + tensor = rng.standard_normal((100,), dtype=np.float32) < 0.5 + assert np.all(Tensor.serialize(tensor).tensor() == tensor) + + +def test_serialize_all_types_equality_torch(force_legacy_torch_compatible_api): + torchtensor = torch.randn([100], dtype=torch.float16) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randn([100], dtype=torch.float32) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randn([100], dtype=torch.float64) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randint(255, 256, (1000,), dtype=torch.uint8) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randint( + 2_147_483_646, 2_147_483_647, (1000,), dtype=torch.int32 + ) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randint( + 9_223_372_036_854_775_806, 9_223_372_036_854_775_807, (1000,), dtype=torch.int64 + ) + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) + + torchtensor = torch.randn([100], dtype=torch.float32) < 0.5 + assert torch.all(Tensor.serialize(torchtensor).tensor() == torchtensor) diff --git a/tests/unit_tests/utils/__init__.py b/tests/unit_tests/utils/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit_tests/utils/test_balance.py b/tests/unit_tests/utils/test_balance.py new file mode 100644 index 0000000000..66aa550f21 --- /dev/null +++ b/tests/unit_tests/utils/test_balance.py @@ -0,0 +1,520 @@ +"""Test the Balance class.""" + +from typing import Union + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from bittensor.utils.balance import Balance +from tests.helpers import CLOSE_IN_VALUE + + +valid_tao_numbers_strategy = st.one_of( + st.integers(max_value=21_000_000, min_value=-21_000_000), + st.floats( + allow_infinity=False, + allow_nan=False, + allow_subnormal=False, + max_value=21_000_000.00, + min_value=-21_000_000.00, + ), +) + + +def remove_zero_filter(x): + """Remove zero and rounded to zero from the list of valid numbers""" + return int(x * pow(10, 9)) != 0 + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_init(balance: Union[int, float]): + """ + Test the initialization of the Balance object. + """ + balance_ = Balance(balance) + if isinstance(balance, int): + assert balance_.rao == balance + elif isinstance(balance, float): + assert balance_.tao == CLOSE_IN_VALUE(balance, 0.00001) + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_add(balance: Union[int, float], balance2: Union[int, float]): + """ + Test the addition of two Balance objects. + """ + balance_ = Balance(balance) + balance2_ = Balance(balance2) + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + if isinstance(balance2, int): + rao2_ = balance2 + elif isinstance(balance2, float): + rao2_ = int(balance2 * pow(10, 9)) + + sum_ = balance_ + balance2_ + assert isinstance(sum_, Balance) + assert CLOSE_IN_VALUE(sum_.rao, 5) == rao_ + rao2_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_add_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the addition of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # convert balance2 to rao. Assume balance2 was rao + rao2_ = int(balance2) + + sum_ = balance_ + balance2_ + assert isinstance(sum_, Balance) + assert CLOSE_IN_VALUE(sum_.rao, 5) == rao_ + rao2_ + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_eq_other_not_balance(balance: Union[int, float]): + """ + Test the equality of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + rao2_: int + # convert balance2 to rao. This assumes balance2 is a rao value + rao2_ = int(balance_.rao) + + assert CLOSE_IN_VALUE(rao2_, 5) == balance_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_radd_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the right addition (radd) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = int(balance2) + + sum_ = balance2_ + balance_ # This is an radd + assert isinstance(sum_, Balance) + assert CLOSE_IN_VALUE(sum_.rao, 5) == rao2_ + rao_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_sub(balance: Union[int, float], balance2: Union[int, float]): + """ + Test the subtraction of two Balance objects. + """ + balance_ = Balance(balance) + balance2_ = Balance(balance2) + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + if isinstance(balance2, int): + rao2_ = balance2 + elif isinstance(balance2, float): + rao2_ = int(balance2 * pow(10, 9)) + + diff_ = balance_ - balance2_ + assert isinstance(diff_, Balance) + assert CLOSE_IN_VALUE(diff_.rao, 5) == rao_ - rao2_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_sub_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the subtraction of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = int(balance2) + + diff_ = balance_ - balance2_ + assert isinstance(diff_, Balance) + assert CLOSE_IN_VALUE(diff_.rao, 5) == rao_ - rao2_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_rsub_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the right subtraction (rsub) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = int(balance2) + + diff_ = balance2_ - balance_ # This is an rsub + assert isinstance(diff_, Balance) + assert CLOSE_IN_VALUE(diff_.rao, 5) == rao2_ - rao_ + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_mul(balance: Union[int, float], balance2: Union[int, float]): + """ + Test the multiplication of two Balance objects. + """ + balance_ = Balance(balance) + balance2_ = Balance(balance2) + rao_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + if isinstance(balance2, int): + rao2_ = balance2 + elif isinstance(balance2, float): + rao2_ = int(balance2 * pow(10, 9)) + + prod_ = balance_ * balance2_ + assert isinstance(prod_, Balance) + + assert ( + prod_.rao == pytest.approx(rao_ * rao2_, 9) + ), f"{balance_} * {balance2_} == {prod_.rao} != {rao_} * {balance2} == {rao_ * balance2}" + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_mul_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the multiplication of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + + prod_ = balance_ * balance2_ + assert isinstance(prod_, Balance) + + assert ( + abs(prod_.rao - int(rao_ * balance2)) <= 20 + ), f"{prod_.rao} != {int(rao_ * balance2)}" + assert prod_.rao == pytest.approx(int(rao_ * balance2)) + + +@given(balance=valid_tao_numbers_strategy, balance2=valid_tao_numbers_strategy) +def test_balance_rmul_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the right multiplication (rmul) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + + prod_ = balance2_ * balance_ # This is an rmul + assert isinstance(prod_, Balance) + + assert ( + abs(prod_.rao - int(balance2 * rao_)) <= 20 + ), f"{prod_.rao} != {int(balance2 * rao_)}" + assert prod_.rao == pytest.approx(int(balance2 * rao_)) + + +@given( + balance=valid_tao_numbers_strategy, + balance2=valid_tao_numbers_strategy.filter(remove_zero_filter), +) # Avoid zero division +def test_balance_truediv(balance: Union[int, float], balance2: Union[int, float]): + """ + Test the true division (/) of two Balance objects. + """ + balance_ = Balance(balance) + balance2_ = Balance(balance2) + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + if isinstance(balance2, int): + rao2_ = balance2 + elif isinstance(balance2, float): + rao2_ = int(balance2 * pow(10, 9)) + + quot_ = balance_ / balance2_ + assert isinstance(quot_, Balance) + assert ( + abs(quot_.rao - int(rao_ / rao2_)) <= 2 + ), f"{quot_.rao} != {int(rao_ / rao2_)}" + assert quot_.rao == pytest.approx(int(rao_ / rao2_)) + + +@given( + balance=valid_tao_numbers_strategy, + balance2=valid_tao_numbers_strategy.filter(remove_zero_filter), +) +def test_balance_truediv_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the true division (/) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = balance2 + + quot_ = balance_ / balance2_ + assert quot_.rao == pytest.approx(int(rao_ / rao2_)) + assert ( + abs(quot_.rao - int(rao_ / rao2_)) <= 10 + ), f"{quot_.rao} != {int(rao_ / rao2_)}" + + +@given( + balance=valid_tao_numbers_strategy.filter(remove_zero_filter), + balance2=valid_tao_numbers_strategy, +) # This is a filter to avoid division by zero +def test_balance_rtruediv_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the right true division (rtruediv) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = balance2 + + quot_ = balance2_ / balance_ # This is an rtruediv + assert isinstance(quot_, Balance) + expected_value = int(rao2_ / rao_) + assert ( + abs(quot_.rao - expected_value) <= 5 + ), f"{balance2_} / {balance_} = {quot_.rao} != {expected_value}" + assert quot_.rao == pytest.approx(expected_value) + + +@given( + balance=valid_tao_numbers_strategy, + balance2=valid_tao_numbers_strategy.filter(remove_zero_filter), +) # Avoid zero division +def test_balance_floordiv(balance: Union[int, float], balance2: Union[int, float]): + """ + Test the floor division (//) of two Balance objects. + """ + balance_ = Balance(balance) + balance2_ = Balance(balance2) + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + if isinstance(balance2, int): + rao2_ = balance2 + elif isinstance(balance2, float): + rao2_ = int(balance2 * pow(10, 9)) + + quot_ = balance_ // balance2_ + assert isinstance(quot_, Balance) + assert CLOSE_IN_VALUE(quot_.rao, 5) == rao_ // rao2_ + + +@given( + balance=valid_tao_numbers_strategy, + balance2=valid_tao_numbers_strategy.filter(remove_zero_filter), +) +def test_balance_floordiv_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the floor division (//) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = balance2 + + quot_ = balance_ // balance2_ + assert isinstance(quot_, Balance) + expected_value = rao_ // rao2_ + assert ( + abs(quot_.rao - expected_value) <= 5 + ), f"{balance_} // {balance2_} = {quot_.rao} != {expected_value}" + assert quot_.rao == pytest.approx(rao_ // rao2_) + + +@given( + balance=valid_tao_numbers_strategy.filter(remove_zero_filter), + balance2=valid_tao_numbers_strategy, +) # This is a filter to avoid division by zero +def test_balance_rfloordiv_other_not_balance( + balance: Union[int, float], balance2: Union[int, float] +): + """ + Test the right floor division (rfloordiv) of a Balance object and a non-Balance object. + """ + balance_ = Balance(balance) + balance2_ = balance2 + rao_: int + rao2_: int + if isinstance(balance, int): + rao_ = balance + elif isinstance(balance, float): + rao_ = int(balance * pow(10, 9)) + # assume balance2 is a rao value + rao2_ = balance2 + + quot_ = balance2_ // balance_ # This is an rfloordiv + assert isinstance(quot_, Balance) + expected_value = rao2_ // rao_ + assert quot_.rao == pytest.approx(rao2_ // rao_) + assert abs(quot_.rao - expected_value) <= 5 + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_not_eq_none(balance: Union[int, float]): + """ + Test the inequality (!=) of a Balance object and None. + """ + balance_ = Balance(balance) + assert balance_ is not None + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_neq_none(balance: Union[int, float]): + """ + Test the inequality (!=) of a Balance object and None. + """ + balance_ = Balance(balance) + assert balance_ is not None + + +def test_balance_init_from_invalid_value(): + """ + Test the initialization of a Balance object with an invalid value. + """ + with pytest.raises(TypeError): + Balance("invalid not a number") + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_add_invalid_type(balance: Union[int, float]): + """ + Test the addition of a Balance object with an invalid type. + """ + balance_ = Balance(balance) + with pytest.raises(NotImplementedError): + _ = balance_ + "" + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_sub_invalid_type(balance: Union[int, float]): + """ + Test the subtraction of a Balance object with an invalid type. + """ + balance_ = Balance(balance) + with pytest.raises(NotImplementedError): + _ = balance_ - "" + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_div_invalid_type(balance: Union[int, float]): + """ + Test the division of a Balance object with an invalid type. + """ + balance_ = Balance(balance) + with pytest.raises(NotImplementedError): + _ = balance_ / "" + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_mul_invalid_type(balance: Union[int, float]): + """ + Test the multiplication of a Balance object with an invalid type. + """ + balance_ = Balance(balance) + with pytest.raises(NotImplementedError): + _ = balance_ * "" + + +@given(balance=valid_tao_numbers_strategy) +def test_balance_eq_invalid_type(balance: Union[int, float]): + """ + Test the equality of a Balance object with an invalid type. + """ + balance_ = Balance(balance) + with pytest.raises(NotImplementedError): + balance_ == "" + + +def test_from_float(): + """Tests from_float method call.""" + assert Balance.from_tao(1.0) == Balance(1000000000) + + +def test_from_rao(): + """Tests from_rao method call.""" + assert Balance.from_tao(1) == Balance(1000000000) diff --git a/tests/unit_tests/utils/test_init.py b/tests/unit_tests/utils/test_init.py new file mode 100644 index 0000000000..fbbc8d5bc9 --- /dev/null +++ b/tests/unit_tests/utils/test_init.py @@ -0,0 +1,27 @@ +import pytest + +from bittensor import warnings, __getattr__, version_split, logging, trace, debug + + +def test_getattr_version_split(): + """Test that __getattr__ for 'version_split' issues a deprecation warning and returns the correct value.""" + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + assert __getattr__("version_split") == version_split + assert len(w) == 1 + assert issubclass(w[-1].category, DeprecationWarning) + assert "version_split is deprecated" in str(w[-1].message) + + +@pytest.mark.parametrize("test_input, expected", [(True, "Trace"), (False, "Default")]) +def test_trace(test_input, expected): + """Test the trace function turns tracing on|off.""" + trace(test_input) + assert logging.current_state_value == expected + + +@pytest.mark.parametrize("test_input, expected", [(True, "Debug"), (False, "Default")]) +def test_debug(test_input, expected): + """Test the debug function turns tracing on|off.""" + debug(test_input) + assert logging.current_state_value == expected diff --git a/tests/unit_tests/utils/test_networking.py b/tests/unit_tests/utils/test_networking.py new file mode 100644 index 0000000000..2037718578 --- /dev/null +++ b/tests/unit_tests/utils/test_networking.py @@ -0,0 +1,167 @@ +import os +import urllib +import pytest +import requests +import unittest.mock as mock +from bittensor import utils +from unittest.mock import MagicMock + + +# Test conversion functions for IPv4 +def test_int_to_ip_zero(): + """Test converting integer to IPv4 address for 0.""" + assert utils.networking.int_to_ip(0) == "0.0.0.0" + assert utils.networking.ip_to_int("0.0.0.0") == 0 + assert utils.networking.ip__str__(4, "0.0.0.0", 8888) == "/ipv4/0.0.0.0:8888" + + +def test_int_to_ip_range(): + """Test converting integer to IPv4 addresses in a range.""" + for i in range(10): + assert utils.networking.int_to_ip(i) == f"0.0.0.{i}" + assert utils.networking.ip_to_int(f"0.0.0.{i}") == i + assert ( + utils.networking.ip__str__(4, f"0.0.0.{i}", 8888) == f"/ipv4/0.0.0.{i}:8888" + ) + + +def test_int_to_ip4_max(): + """Test converting integer to maximum IPv4 address.""" + assert utils.networking.int_to_ip(4294967295) == "255.255.255.255" + assert utils.networking.ip_to_int("255.255.255.255") == 4294967295 + assert ( + utils.networking.ip__str__(4, "255.255.255.255", 8888) + == "/ipv4/255.255.255.255:8888" + ) + + +# Test conversion functions for IPv6 +def test_int_to_ip6_zero(): + """Test converting integer to IPv6 address for 0.""" + assert utils.networking.int_to_ip(4294967296) == "::1:0:0" + assert utils.networking.ip_to_int("::1:0:0") == 4294967296 + assert utils.networking.ip__str__(6, "::1:0:0", 8888) == "/ipv6/::1:0:0:8888" + + +def test_int_to_ip6_range(): + """Test converting integer to IPv6 addresses in a range.""" + for i in range(10): + assert utils.networking.int_to_ip(4294967296 + i) == f"::1:0:{i}" + assert utils.networking.ip_to_int(f"::1:0:{i}") == 4294967296 + i + assert ( + utils.networking.ip__str__(6, f"::1:0:{i}", 8888) == f"/ipv6/::1:0:{i}:8888" + ) + + +def test_int_to_ip6_max(): + """Test converting integer to maximum IPv6 address.""" + max_val = 340282366920938463463374607431768211455 + assert ( + utils.networking.int_to_ip(max_val) == "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" + ) + assert ( + utils.networking.ip_to_int("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") == max_val + ) + assert ( + utils.networking.ip__str__(6, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 8888) + == "/ipv6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:8888" + ) + + +def test_int_to_ip6_overflow(): + """Test handling overflow when converting integer to IPv6 address.""" + overflow = 340282366920938463463374607431768211455 + 1 + with pytest.raises(Exception): + utils.networking.int_to_ip(overflow) + + +def test_int_to_ip6_underflow(): + """Test handling underflow when converting integer to IPv6 address.""" + underflow = -1 + with pytest.raises(Exception): + utils.networking.int_to_ip(underflow) + + +# Test getting external IP address +def test_get_external_ip(): + """Test getting the external IP address.""" + assert utils.networking.get_external_ip() + + +def test_get_external_ip_os_broken(): + """Test getting the external IP address when os.popen is broken.""" + + class FakeReadline: + def readline(self): + return 1 + + def mock_call(): + return FakeReadline() + + with mock.patch.object(os, "popen", new=mock_call): + assert utils.networking.get_external_ip() + + +def test_get_external_ip_os_request_urllib_broken(): + """Test getting the external IP address when os.popen and requests.get/urllib.request are broken.""" + + class FakeReadline: + def readline(self): + return 1 + + def mock_call(): + return FakeReadline() + + class FakeResponse: + def text(self): + return 1 + + def mock_call_two(): + return FakeResponse() + + class FakeRequest: + def urlopen(self): + return 1 + + with mock.patch.object(os, "popen", new=mock_call): + with mock.patch.object(requests, "get", new=mock_call_two): + urllib.request = MagicMock(return_value=FakeRequest()) + with pytest.raises(Exception): + assert utils.networking.get_external_ip() + + +# Test formatting WebSocket endpoint URL +@pytest.mark.parametrize( + "url, expected", + [ + ("wss://exampleendpoint:9944", "wss://exampleendpoint:9944"), + ("ws://exampleendpoint:9944", "ws://exampleendpoint:9944"), + ( + "exampleendpoint:9944", + "ws://exampleendpoint:9944", + ), # should add ws:// not wss:// + ( + "ws://exampleendpoint", + "ws://exampleendpoint", + ), # should not add port if not specified + ( + "wss://exampleendpoint", + "wss://exampleendpoint", + ), # should not add port if not specified + ( + "exampleendpoint", + "ws://exampleendpoint", + ), # should not add port if not specified + ( + "exampleendpointwithws://:9944", + "ws://exampleendpointwithws://:9944", + ), # should only care about the front + ( + "exampleendpointwithwss://:9944", + "ws://exampleendpointwithwss://:9944", + ), # should only care about the front + ], +) +def test_format(url: str, expected: str): + """Test formatting WebSocket endpoint URL.""" + assert utils.networking.get_formatted_ws_endpoint_url(url) == expected diff --git a/tests/unit_tests/utils/test_registration.py b/tests/unit_tests/utils/test_registration.py new file mode 100644 index 0000000000..c85608b5f3 --- /dev/null +++ b/tests/unit_tests/utils/test_registration.py @@ -0,0 +1,62 @@ +# The MIT License (MIT) +# Copyright © 2024 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 pytest + +from bittensor.utils.registration import LazyLoadedTorch + + +class MockBittensorLogging: + def __init__(self): + self.messages = [] + + def error(self, message): + self.messages.append(message) + + +@pytest.fixture +def mock_bittensor_logging(monkeypatch): + mock_logger = MockBittensorLogging() + monkeypatch.setattr("bittensor.utils.registration.logging", mock_logger) + return mock_logger + + +def test_lazy_loaded_torch__torch_installed(monkeypatch, mock_bittensor_logging): + import torch + + lazy_torch = LazyLoadedTorch() + + assert bool(torch) is True + + assert lazy_torch.nn is torch.nn + with pytest.raises(AttributeError): + lazy_torch.no_such_thing + + +def test_lazy_loaded_torch__no_torch(monkeypatch, mock_bittensor_logging): + monkeypatch.setattr("bittensor.utils.registration._get_real_torch", lambda: None) + + torch = LazyLoadedTorch() + + assert not torch + + with pytest.raises(ImportError): + torch.some_attribute + + # Check if the error message is logged correctly + assert len(mock_bittensor_logging.messages) == 1 + assert "This command requires torch." in mock_bittensor_logging.messages[0] diff --git a/tests/unit_tests/utils/test_utils.py b/tests/unit_tests/utils/test_utils.py new file mode 100644 index 0000000000..8ed28c0670 --- /dev/null +++ b/tests/unit_tests/utils/test_utils.py @@ -0,0 +1,169 @@ +# The MIT License (MIT) +# Copyright © 2024 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. + +from bittensor import utils +from bittensor.core.settings import SS58_FORMAT +import pytest + + +def test_ss58_to_vec_u8(mocker): + """Tests `utils.ss58_to_vec_u8` function.""" + # Prep + test_ss58_address = "5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm" + fake_return = b"2\xa6?" + mocked_ss58_address_to_bytes = mocker.patch.object( + utils, "ss58_address_to_bytes", return_value=fake_return + ) + + # Call + result = utils.ss58_to_vec_u8(test_ss58_address) + + # Asserts + mocked_ss58_address_to_bytes.assert_called_once_with(test_ss58_address) + assert result == [int(byte) for byte in fake_return] + + +@pytest.mark.parametrize( + "test_input,expected", + [ + ("y", True), + ("yes", True), + ("t", True), + ("true", True), + ("on", True), + ("1", True), + ("n", False), + ("no", False), + ("f", False), + ("false", False), + ("off", False), + ("0", False), + ], +) +def test_strtobool(test_input, expected): + """Test truthy values.""" + assert utils.strtobool(test_input) is expected + + +@pytest.mark.parametrize( + "test_input", + [ + "maybe", + "2", + "onoff", + ], +) +def test_strtobool_raise_error(test_input): + """Tests invalid values.""" + with pytest.raises(ValueError): + utils.strtobool(test_input) + + +def test_get_explorer_root_url_by_network_from_map(): + """Tests private utils._get_explorer_root_url_by_network_from_map function.""" + # Prep + # Test with a known network + network_map = { + "entity1": {"network1": "url1", "network2": "url2"}, + "entity2": {"network1": "url3", "network3": "url4"}, + } + # Test with no matching network in the map + network_map_empty = { + "entity1": {}, + "entity2": {}, + } + + # Assertions + assert utils._get_explorer_root_url_by_network_from_map( + "network1", network_map + ) == { + "entity1": "url1", + "entity2": "url3", + } + # Test with an unknown network + assert ( + utils._get_explorer_root_url_by_network_from_map("unknown_network", network_map) + == {} + ) + assert ( + utils._get_explorer_root_url_by_network_from_map("network1", network_map_empty) + == {} + ) + + +def test_get_explorer_url_for_network(): + """Tests `utils.get_explorer_url_for_network` function.""" + # Prep + fake_block_hash = "0x1234567890abcdef" + fake_map = {"opentensor": {"network": "url"}, "taostats": {"network": "url2"}} + + # Call + result = utils.get_explorer_url_for_network("network", fake_block_hash, fake_map) + + # Assert + assert result == { + "opentensor": f"url/query/{fake_block_hash}", + "taostats": f"url2/extrinsic/{fake_block_hash}", + } + + +def test_ss58_address_to_bytes(mocker): + """Tests utils.ss58_address_to_bytes function.""" + # Prep + fake_ss58_address = "ss58_address" + mocked_scalecodec_ss58_decode = mocker.patch.object( + utils.scalecodec, "ss58_decode", return_value="" + ) + + # Call + result = utils.ss58_address_to_bytes(fake_ss58_address) + + # Asserts + mocked_scalecodec_ss58_decode.assert_called_once_with( + fake_ss58_address, SS58_FORMAT + ) + assert result == bytes.fromhex(mocked_scalecodec_ss58_decode.return_value) + + +@pytest.mark.parametrize( + "test_input, expected_result", + [ + (123, False), + ("0x234SD", True), + ("5D34SD", True), + (b"0x234SD", True), + ], +) +def test_is_valid_bittensor_address_or_public_key(mocker, test_input, expected_result): + """Tests utils.is_valid_bittensor_address_or_public_key function.""" + # Prep + mocked_is_valid_ed25519_pubkey = mocker.patch.object( + utils, "_is_valid_ed25519_pubkey", return_value=True + ) + mocked_ss58_is_valid_ss58_address = mocker.patch.object( + utils.ss58, "is_valid_ss58_address", side_effect=[False, True] + ) + + # Call + result = utils.is_valid_bittensor_address_or_public_key(test_input) + + # Asserts + if not isinstance(test_input, int) and isinstance(test_input, bytes): + mocked_is_valid_ed25519_pubkey.assert_called_with(test_input) + if isinstance(test_input, str) and not test_input.startswith("0x"): + assert mocked_ss58_is_valid_ss58_address.call_count == 2 + assert result == expected_result diff --git a/tests/unit_tests/utils/test_version.py b/tests/unit_tests/utils/test_version.py new file mode 100644 index 0000000000..fa96bddad3 --- /dev/null +++ b/tests/unit_tests/utils/test_version.py @@ -0,0 +1,171 @@ +# The MIT License (MIT) +# Copyright © 2021 Yuma Rao +# Copyright © 2022 Opentensor Foundation +# Copyright © 2023 Opentensor Technologies Inc + +# 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. + +from pathlib import Path +import pytest +from freezegun import freeze_time +from datetime import datetime, timedelta, timezone + +# from bittensor.utils.version import ( +# VERSION_CHECK_THRESHOLD, +# VersionCheckError, +# get_and_save_latest_version, +# check_version, +# version_checking, +# __version__ +# ) +from bittensor.utils import version + +from unittest.mock import MagicMock +from pytest_mock import MockerFixture + + +@pytest.fixture +def pypi_version(): + return "6.9.3" + + +@pytest.fixture +def mock_get_version_from_pypi(mocker: MockerFixture, pypi_version: str): + return mocker.patch( + "bittensor.utils.version._get_version_from_pypi", + return_value=pypi_version, + autospec=True, + ) + + +@pytest.fixture +def version_file_path(mocker: MockerFixture, tmp_path: Path): + file_path = tmp_path / ".version" + + mocker.patch( + "bittensor.utils.version._get_version_file_path", return_value=file_path + ) + return file_path + + +def test_get_and_save_latest_version_no_file( + mock_get_version_from_pypi: MagicMock, version_file_path: Path, pypi_version: str +): + assert not version_file_path.exists() + + assert version.get_and_save_latest_version() == pypi_version + + mock_get_version_from_pypi.assert_called_once() + assert version_file_path.exists() + assert version_file_path.read_text() == pypi_version + + +@pytest.mark.parametrize("elapsed", [0, version.VERSION_CHECK_THRESHOLD - 5]) +def test_get_and_save_latest_version_file_fresh_check( + mock_get_version_from_pypi: MagicMock, version_file_path: Path, elapsed: int +): + now = datetime.now(timezone.utc) + + version_file_path.write_text("6.9.5") + + with freeze_time(now + timedelta(seconds=elapsed)): + assert version.get_and_save_latest_version() == "6.9.5" + + mock_get_version_from_pypi.assert_not_called() + + +def test_get_and_save_latest_version_file_expired_check( + mock_get_version_from_pypi: MagicMock, version_file_path: Path, pypi_version: str +): + now = datetime.now(timezone.utc) + + version_file_path.write_text("6.9.5") + + with freeze_time(now + timedelta(seconds=version.VERSION_CHECK_THRESHOLD + 1)): + assert version.get_and_save_latest_version() == pypi_version + + mock_get_version_from_pypi.assert_called_once() + assert version_file_path.read_text() == pypi_version + + +@pytest.mark.parametrize( + ("current_version", "latest_version"), + [ + ("6.9.3", "6.9.4"), + ("6.9.3a1", "6.9.3a2"), + ("6.9.3a1", "6.9.3b1"), + ("6.9.3", "6.10"), + ("6.9.3", "7.0"), + ("6.0.15", "6.1.0"), + ], +) +def test_check_version_newer_available( + mocker: MockerFixture, current_version: str, latest_version: str, capsys +): + version.__version__ = current_version + mocker.patch( + "bittensor.utils.version.get_and_save_latest_version", + return_value=latest_version, + ) + + version.check_version() + + captured = capsys.readouterr() + + assert "update" in captured.out + assert current_version in captured.out + assert latest_version in captured.out + + +@pytest.mark.parametrize( + ("current_version", "latest_version"), + [ + ("6.9.3", "6.9.3"), + ("6.9.3", "6.9.2"), + ("6.9.3b", "6.9.3a"), + ], +) +def test_check_version_up_to_date( + mocker: MockerFixture, current_version: str, latest_version: str, capsys +): + version.__version__ = current_version + mocker.patch( + "bittensor.utils.version.get_and_save_latest_version", + return_value=latest_version, + ) + + version.check_version() + + captured = capsys.readouterr() + + assert captured.out == "" + + +def test_version_checking(mocker: MockerFixture): + mock = mocker.patch("bittensor.utils.version.check_version") + + version.version_checking() + + mock.assert_called_once() + + +def test_version_checking_exception(mocker: MockerFixture): + mock = mocker.patch( + "bittensor.utils.version.check_version", side_effect=version.VersionCheckError + ) + + version.version_checking() + + mock.assert_called_once() diff --git a/tests/unit_tests/utils/test_weight_utils.py b/tests/unit_tests/utils/test_weight_utils.py new file mode 100644 index 0000000000..74009434b9 --- /dev/null +++ b/tests/unit_tests/utils/test_weight_utils.py @@ -0,0 +1,681 @@ +# The MIT License (MIT) +# Copyright © 2021 Yuma Rao +# Copyright © 2022 Opentensor Foundation +# Copyright © 2023 Opentensor Technologies Inc + +# 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 logging +import numpy as np +from hypothesis import settings + +import bittensor.utils.weight_utils as weight_utils +import pytest + +from bittensor.utils import torch +from bittensor.core.settings import version_as_int + + +def test_convert_weight_and_uids(): + uids = np.arange(10) + weights = np.random.rand(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # min weight < 0 + weights[5] = -1 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # min uid < 0 + weights[5] = 0 + uids[3] = -1 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # len(uids) != len(weights) + uids[3] = 3 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights[1:]) + + # sum(weights) == 0 + weights = np.zeros(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # test for overflow and underflow + for _ in range(5): + uids = np.arange(10) + weights = np.random.rand(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + +def test_convert_weight_and_uids_torch(force_legacy_torch_compatible_api): + uids = torch.tensor(list(range(10))) + weights = torch.rand(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # min weight < 0 + weights[5] = -1 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + # min uid < 0 + weights[5] = 0 + uids[3] = -1 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + # len(uids) != len(weights) + uids[3] = 3 + with pytest.raises(ValueError) as pytest_wrapped_e: + weight_utils.convert_weights_and_uids_for_emit(uids, weights[1:]) + + # sum(weights) == 0 + weights = torch.zeros(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + # test for overflow and underflow + for _ in range(5): + uids = torch.tensor(list(range(10))) + weights = torch.rand(10) + weight_utils.convert_weights_and_uids_for_emit(uids, weights) + + +def test_normalize_with_max_weight(): + weights = np.random.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.01) + assert wn.max() <= 0.01 + + weights = np.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.01) + assert wn.max() <= 0.01 + + weights = np.random.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.02) + assert wn.max() <= 0.02 + + weights = np.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.02) + assert wn.max() <= 0.02 + + weights = np.random.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.03) + assert wn.max() <= 0.03 + + weights = np.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.03) + assert wn.max() <= 0.03 + + # Check for Limit + limit = 0.001 + weights = np.random.rand(2000) + w = weights / weights.sum() + wn = weight_utils.normalize_max_weight(weights, limit=limit) + assert abs((w.max() >= limit and (limit - wn.max())) < 0.001) or ( + w.max() < limit and wn.max() < limit + ) + + # Check for Zeros + limit = 0.01 + weights = np.zeros(2000) + wn = weight_utils.normalize_max_weight(weights, limit=limit) + assert wn.max() == 1 / 2000 + + # Check for Ordering after normalization + weights = np.random.rand(100) + wn = weight_utils.normalize_max_weight(weights, limit=1) + assert np.array_equal(wn, weights / weights.sum()) + + # Check for epsilon changes + epsilon = 0.01 + weights = np.sort(np.random.rand(100)) + x = weights / weights.sum() + limit = x[-10] + change = epsilon * limit + y = weight_utils.normalize_max_weight(x, limit=limit - change) + z = weight_utils.normalize_max_weight(x, limit=limit + change) + assert np.abs(y - z).sum() < epsilon + + +def test_normalize_with_max_weight__legacy_torch_api_compat( + force_legacy_torch_compatible_api, +): + weights = torch.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.01) + assert wn.max() <= 0.01 + + weights = torch.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.01) + assert wn.max() <= 0.01 + + weights = torch.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.02) + assert wn.max() <= 0.02 + + weights = torch.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.02) + assert wn.max() <= 0.02 + + weights = torch.rand(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.03) + assert wn.max() <= 0.03 + + weights = torch.zeros(1000) + wn = weight_utils.normalize_max_weight(weights, limit=0.03) + assert wn.max() <= 0.03 + + # Check for Limit + limit = 0.001 + weights = torch.rand(2000) + w = weights / weights.sum() + wn = weight_utils.normalize_max_weight(weights, limit=limit) + assert (w.max() >= limit and (limit - wn.max()).abs() < 0.001) or ( + w.max() < limit and wn.max() < limit + ) + + # Check for Zeros + limit = 0.01 + weights = torch.zeros(2000) + wn = weight_utils.normalize_max_weight(weights, limit=limit) + assert wn.max() == 1 / 2000 + + # Check for Ordering after normalization + weights = torch.rand(100) + wn = weight_utils.normalize_max_weight(weights, limit=1) + assert torch.isclose(wn, weights / weights.sum(), atol=1e-08, rtol=0).all() + + # Check for epsilon changes + epsilon = 0.01 + weights, _ = torch.sort(torch.rand(100)) + x = weights / weights.sum() + limit = x[-10] + change = epsilon * limit + y = weight_utils.normalize_max_weight(x, limit=limit - change) + z = weight_utils.normalize_max_weight(x, limit=limit + change) + assert (y - z).abs().sum() < epsilon + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, expected", + [ + ("happy-path-1", 3, [0, 1, 2], [15, 5, 80], np.array([0.15, 0.05, 0.8])), + ("happy-path-2", 4, [1, 3], [50, 50], np.array([0.0, 0.5, 0.0, 0.5])), + ], +) +def test_convert_weight_uids_and_vals_to_tensor_happy_path( + test_id, n, uids, weights, expected +): + # Act + result = weight_utils.convert_weight_uids_and_vals_to_tensor(n, uids, weights) + + # Assert + assert np.allclose(result, expected), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, subnets, expected", + [ + ( + "happy-path-1", + 3, + [0, 1, 2], + [15, 5, 80], + [0, 1, 2], + torch.tensor([0.15, 0.05, 0.8]), + ), + ( + "happy-path-2", + 3, + [0, 2], + [300, 300], + [0, 1, 2], + torch.tensor([0.5, 0.0, 0.5]), + ), + ], +) +def test_convert_weight_uids_and_vals_to_tensor_happy_path_torch( + test_id, n, uids, weights, subnets, expected, force_legacy_torch_compatible_api +): + # Act + result = weight_utils.convert_weight_uids_and_vals_to_tensor(n, uids, weights) + + # Assert + assert torch.allclose(result, expected), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, expected", + [ + ("edge_case_empty", 5, [], [], np.zeros(5)), + ("edge_case_single", 1, [0], [100], np.array([1.0])), + ("edge_case_all_zeros", 4, [0, 1, 2, 3], [0, 0, 0, 0], np.zeros(4)), + ], +) +def test_convert_weight_uids_and_vals_to_tensor_edge_cases( + test_id, n, uids, weights, expected +): + # Act + result = weight_utils.convert_weight_uids_and_vals_to_tensor(n, uids, weights) + + # Assert + assert np.allclose(result, expected), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, exception", + [ + ("error-case-mismatched-lengths", 3, [0, 1, 3, 4, 5], [10, 20, 30], IndexError), + ("error-case-negative-n", -1, [0, 1], [10, 20], ValueError), + ("error-case-invalid-uids", 3, [0, 3], [10, 20], IndexError), + ], +) +def test_convert_weight_uids_and_vals_to_tensor_error_cases( + test_id, n, uids, weights, exception +): + # Act / Assert + with pytest.raises(exception): + weight_utils.convert_weight_uids_and_vals_to_tensor(n, uids, weights) + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, subnets, expected", + [ + ( + "happy-path-1", + 3, + [0, 1, 2], + [15, 5, 80], + [0, 1, 2], + np.array([0.15, 0.05, 0.8]), + ), + ( + "happy-path-2", + 3, + [0, 2], + [300, 300], + [0, 1, 2], + np.array([0.5, 0.0, 0.5]), + ), + ], +) +def test_convert_root_weight_uids_and_vals_to_tensor_happy_paths( + test_id, n, uids, weights, subnets, expected +): + # Act + result = weight_utils.convert_root_weight_uids_and_vals_to_tensor( + n, uids, weights, subnets + ) + + # Assert + assert np.allclose(result, expected, atol=1e-4), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, subnets, expected", + [ + ( + "edge-1", + 1, + [0], + [0], + [0], + torch.tensor([0.0]), + ), # Single neuron with zero weight + ( + "edge-2", + 2, + [0, 1], + [0, 0], + [0, 1], + torch.tensor([0.0, 0.0]), + ), # All zero weights + ], +) +def test_convert_root_weight_uids_and_vals_to_tensor_edge_cases( + test_id, n, uids, weights, subnets, expected, force_legacy_torch_compatible_api +): + # Act + result = weight_utils.convert_root_weight_uids_and_vals_to_tensor( + n, uids, weights, subnets + ) + + # Assert + assert torch.allclose(result, expected, atol=1e-4), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, subnets, expected", + [ + ( + "edge-1", + 1, + [0], + [0], + [0], + np.array([0.0]), + ), # Single neuron with zero weight + ( + "edge-2", + 2, + [0, 1], + [0, 0], + [0, 1], + np.array([0.0, 0.0]), + ), # All zero weights + ], +) +def test_convert_root_weight_uids_and_vals_to_tensor_edge_cases( + test_id, n, uids, weights, subnets, expected +): + # Act + result = weight_utils.convert_root_weight_uids_and_vals_to_tensor( + n, uids, weights, subnets + ) + + # Assert + assert np.allclose(result, expected, atol=1e-4), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, weights, subnets, exception", + [ + # uid not in subnets + ( + "error-1", + 3, + [1, 3], + [100, 200], + [1, 2], + "The subnet is unavailable at the moment.", + ), + # More uids than subnets + ( + "error-2", + 3, + [1, 2, 3], + [100, 200], + [1], + "The subnet is unavailable at the moment.", + ), + ], +) +def test_convert_root_weight_uids_and_vals_to_tensor_error_cases( + test_id, n, uids, weights, subnets, exception, caplog +): + with caplog.at_level(logging.WARNING): + weight_utils.convert_root_weight_uids_and_vals_to_tensor( + n, uids, weights, subnets + ) + + assert any( + exception in record.message and record.levelname == "WARNING" + for record in caplog.records + ) + + +@pytest.mark.parametrize( + "test_id, n, uids, bonds, expected_output", + [ + ( + "happy-path-1", + 5, + [1, 3, 4], + [10, 20, 30], + np.array([0, 10, 0, 20, 30], dtype=np.int64), + ), + ( + "happy-path-2", + 3, + [0, 1, 2], + [7, 8, 9], + np.array([7, 8, 9], dtype=np.int64), + ), + ("happy-path-3", 4, [2], [15], np.array([0, 0, 15, 0], dtype=np.int64)), + ], +) +def test_happy_path(test_id, n, uids, bonds, expected_output): + # Act + result = weight_utils.convert_bond_uids_and_vals_to_tensor(n, uids, bonds) + + # Assert + assert np.array_equal(result, expected_output), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, bonds, expected_output", + [ + ( + "happy-path-1", + 5, + [1, 3, 4], + [10, 20, 30], + torch.tensor([0, 10, 0, 20, 30], dtype=torch.int64), + ), + ( + "happy-path-2", + 3, + [0, 1, 2], + [7, 8, 9], + torch.tensor([7, 8, 9], dtype=torch.int64), + ), + ("happy-path-3", 4, [2], [15], torch.tensor([0, 0, 15, 0], dtype=torch.int64)), + ], +) +def test_happy_path_torch( + test_id, n, uids, bonds, expected_output, force_legacy_torch_compatible_api +): + # Act + result = weight_utils.convert_bond_uids_and_vals_to_tensor(n, uids, bonds) + + # Assert + assert torch.equal(result, expected_output), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, bonds, expected_output", + [ + ("edge-1", 1, [0], [0], np.array([0], dtype=np.int64)), # Single element + ( + "edge-2", + 10, + [], + [], + np.zeros(10, dtype=np.int64), + ), # Empty uids and bonds + ], +) +def test_edge_cases(test_id, n, uids, bonds, expected_output): + # Act + result = weight_utils.convert_bond_uids_and_vals_to_tensor(n, uids, bonds) + + # Assert + assert np.array_equal(result, expected_output), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, bonds, expected_output", + [ + ("edge-1", 1, [0], [0], torch.tensor([0], dtype=torch.int64)), # Single element + ( + "edge-2", + 10, + [], + [], + torch.zeros(10, dtype=torch.int64), + ), # Empty uids and bonds + ], +) +def test_edge_cases_torch( + test_id, n, uids, bonds, expected_output, force_legacy_torch_compatible_api +): + # Act + result = weight_utils.convert_bond_uids_and_vals_to_tensor(n, uids, bonds) + + # Assert + assert torch.equal(result, expected_output), f"Failed {test_id}" + + +@pytest.mark.parametrize( + "test_id, n, uids, bonds, exception", + [ + ("error-1", 5, [1, 3, 6], [10, 20, 30], IndexError), # uid out of bounds + ("error-2", -1, [0], [10], ValueError), # Negative number of neurons + ], +) +def test_error_cases(test_id, n, uids, bonds, exception): + # Act / Assert + with pytest.raises(exception): + weight_utils.convert_bond_uids_and_vals_to_tensor(n, uids, bonds) + + +def test_process_weights_for_netuid(mocker): + """Test the process_weights_for_netuid function.""" + # Prep + fake_uids = np.array([1, 2, 3, 4, 5], dtype=np.int64) + fake_weights = np.array([1.0, 2.5, 3.3, 4.7, 5.9], dtype=np.float32) + fake_netuid = 1 + fake_subtensor = mocker.MagicMock() + fake_metagraph = mocker.MagicMock() + fake_exclude_quantile = 0 + + fake_subtensor.min_allowed_weights.return_value = 0.1 + fake_subtensor.max_weight_limit.return_value = 1.0 + fake_metagraph.n = 1 + mocked_normalize_max_weight = mocker.patch.object( + weight_utils, "normalize_max_weight" + ) + + # Call + result = weight_utils.process_weights_for_netuid( + uids=fake_uids, + weights=fake_weights, + netuid=fake_netuid, + subtensor=fake_subtensor, + metagraph=fake_metagraph, + exclude_quantile=fake_exclude_quantile, + ) + + # Asserts + fake_subtensor.min_allowed_weights.assert_called_once_with(netuid=fake_netuid) + fake_subtensor.max_weight_limit.assert_called_once_with(netuid=fake_netuid) + + res1, res2 = result + assert np.array_equal(res1, fake_uids) + assert res2 == mocked_normalize_max_weight.return_value + + +def test_process_weights_with_all_zero_weights(mocker): + """Test the process_weights_for_netuid function with all zero weights.""" + # Prep + fake_uids = np.array([1, 2, 3, 4, 5], dtype=np.int64) + fake_weights = np.array([0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32) + fake_netuid = 1 + fake_subtensor = mocker.MagicMock() + fake_metagraph = mocker.MagicMock() + fake_exclude_quantile = 0 + + fake_subtensor.min_allowed_weights.return_value = 0.1 + fake_subtensor.max_weight_limit.return_value = 1.0 + fake_metagraph.n = 1 + + # Call + result = weight_utils.process_weights_for_netuid( + uids=fake_uids, + weights=fake_weights, + netuid=fake_netuid, + subtensor=fake_subtensor, + metagraph=fake_metagraph, + exclude_quantile=fake_exclude_quantile, + ) + + # Asserts + fake_subtensor.min_allowed_weights.assert_called_once_with(netuid=fake_netuid) + fake_subtensor.max_weight_limit.assert_called_once_with(netuid=fake_netuid) + + res1, res2 = result + assert np.array_equal(res1, np.array([0])) + assert np.array_equal(res2, np.array([1.0])) + + +def test_process_weights_for_netuid_with_nzs_less_min_allowed_weights(mocker): + """Tests process_weights_for_netuid method when non-zero weights are less than the min allowed weights.""" + # Prep + fake_uids = np.array([1, 2, 3, 4, 5], dtype=np.int64) + fake_weights = np.array([0.1, 0.2, 0.3, 0.0, 0.0], dtype=np.float32) + fake_netuid = 1 + fake_subtensor = mocker.MagicMock() + fake_metagraph = None + fake_exclude_quantile = 0 + + fake_subtensor.min_allowed_weights.return_value = 4 + fake_subtensor.max_weight_limit.return_value = 1.0 + fake_subtensor.metagraph.return_value.n = 5 + mocked_np_arange = mocker.patch.object(np, "arange") + mocked_normalize_max_weight = mocker.patch.object( + weight_utils, "normalize_max_weight" + ) + + # Call + result = weight_utils.process_weights_for_netuid( + uids=fake_uids, + weights=fake_weights, + netuid=fake_netuid, + subtensor=fake_subtensor, + metagraph=fake_metagraph, + exclude_quantile=fake_exclude_quantile, + ) + + # Asserts + fake_subtensor.metagraph.assert_called_once_with(fake_netuid) + fake_subtensor.min_allowed_weights.assert_called_once_with(netuid=fake_netuid) + fake_subtensor.max_weight_limit.assert_called_once_with(netuid=fake_netuid) + assert result == ( + mocked_np_arange.return_value, + mocked_normalize_max_weight.return_value, + ) + + +def test_generate_weight_hash(mocker): + """Tests weight_utils.generate_weight_hash function.""" + # Prep + fake_address = "5D1ABCD" + fake_netuid = 1 + fake_uids = [1, 2] + fake_values = [10, 20] + fake_version_key = 80000 + fake_salt = [1, 2] + + mocked_scale_bytes = mocker.patch.object(weight_utils, "ScaleBytes") + mocked_keypair = mocker.patch.object(weight_utils, "Keypair") + mocker_vec = mocker.patch.object(weight_utils, "Vec") + mocked_u16 = mocker.patch.object(weight_utils, "U16") + mocked_hasher = mocker.patch.object(weight_utils.hashlib, "blake2b") + + # Call + result = weight_utils.generate_weight_hash( + address=fake_address, + netuid=fake_netuid, + uids=fake_uids, + values=fake_values, + version_key=fake_version_key, + salt=fake_salt, + ) + + # Asserts + mocked_scale_bytes.assert_called() + mocked_keypair.assert_called() + mocker_vec.assert_called() + mocked_u16.assert_called() + assert ( + result + == mocked_hasher.return_value.hexdigest.return_value.__radd__.return_value + )