-
Notifications
You must be signed in to change notification settings - Fork 302
/
axon.py
1471 lines (1223 loc) · 65.7 KB
/
axon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Create and initialize Axon, which services the forward and backward requests from other neurons."""
# 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 argparse
import asyncio
import contextlib
import copy
import inspect
import json
import os
import threading
import time
import traceback
import typing
import uuid
from inspect import signature, Signature, Parameter
from typing import List, Optional, Tuple, Callable, Any, Dict, Awaitable
import uvicorn
from fastapi import FastAPI, APIRouter, Depends
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
import bittensor
from bittensor.errors import (
InvalidRequestNameError,
SynapseDendriteNoneException,
SynapseParsingError,
UnknownSynapseError,
NotVerifiedException,
BlacklistedException,
PriorityException,
PostProcessException,
SynapseException,
)
from bittensor.constants import ALLOWED_DELTA, V_7_2_0
from bittensor.threadpool import PriorityThreadPoolExecutor
from bittensor.utils import networking
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.
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.
"""
pass
@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 MySyanpse( bittensor.Synapse ):
input: int = 1
output: int = None
# Define a custom request forwarding function using your synapse class
def forward( synapse: MySyanpse ) -> MySyanpse:
# Apply custom logic to synapse and return it
synapse.output = 2
return synapse
# Define a custom request verification function
def verify_my_synapse( synapse: MySyanpse ):
# Apply custom verification logic to synapse
# Optionally raise Exception
assert synapse.input == 1
...
# Define a custom request blacklist fucntion
def blacklist_my_synapse( synapse: MySyanpse ) -> bool:
# Apply custom blacklist
return False ( if non blacklisted ) or True ( if blacklisted )
# Define a custom request priority fucntion
def prioritize_my_synape( synapse: MySyanpse ) -> float:
# Apply custom priority
return 1.0
# Initialize Axon object with a custom configuration
my_axon = bittensor.axon(
config=my_config,
wallet=my_wallet,
port=9090,
ip="192.0.2.0",
external_ip="203.0.113.0",
external_port=7070
)
# Attach the endpoint with the specified verification and forward functions.
my_axon.attach(
forward_fn = forward_my_synapse,
verify_fn = verify_my_synapse,
blacklist_fn = blacklist_my_synapse,
priority_fn = prioritize_my_synape
)
# Serve and start your axon.
my_axon.serve(
netuid = ...
subtensor = ...
).start()
# If you have multiple forwarding functions, you can chain attach them.
my_axon.attach(
forward_fn = forward_my_synapse,
verify_fn = verify_my_synapse,
blacklist_fn = blacklist_my_synapse,
priority_fn = prioritize_my_synape
).attach(
forward_fn = forward_my_synapse_2,
verify_fn = verify_my_synapse_2,
blacklist_fn = blacklist_my_synapse_2,
priority_fn = prioritize_my_synape_2
).serve(
netuid = ...
subtensor = ...
).start()
Args:
wallet (bittensor.wallet, optional): Wallet with hotkey and coldkeypub.
config (bittensor.config, optional): Configuration parameters for the axon.
port (int, optional): Port for server binding.
ip (str, optional): Binding IP address.
external_ip (str, optional): External IP address to broadcast.
external_port (int, optional): External port to broadcast.
max_workers (int, optional): Number of active threads for request handling.
Returns:
bittensor.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["bittensor.wallet"] = None,
config: Optional["bittensor.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,
):
r"""Creates a new bittensor.Axon object from passed arguments.
Args:
config (:obj:`Optional[bittensor.config]`, `optional`):
bittensor.axon.config()
wallet (:obj:`Optional[bittensor.wallet]`, `optional`):
bittensor wallet with hotkey and coldkeypub.
port (:type:`Optional[int]`, `optional`):
Binding port.
ip (:type:`Optional[str]`, `optional`):
Binding ip.
external_ip (:type:`Optional[str]`, `optional`):
The external ip of the server to broadcast to the network.
external_port (:type:`Optional[int]`, `optional`):
The external port of the server to broadcast to the network.
max_workers (:type:`Optional[int]`, `optional`):
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 config.axon.get("ip", bittensor.defaults.axon.ip)
config.axon.port = port or config.axon.get("port", bittensor.defaults.axon.port)
config.axon.external_ip = external_ip or config.axon.get(
"external_ip", bittensor.defaults.axon.external_ip
)
config.axon.external_port = external_port or config.axon.get(
"external_port", bittensor.defaults.axon.external_port
)
config.axon.max_workers = max_workers or config.axon.get(
"max_workers", bittensor.defaults.axon.max_workers
)
axon.check_config(config)
self.config = config # type: ignore [method-assign]
# Get wallet or use default.
self.wallet = wallet or bittensor.wallet()
# Build axon objects.
self.uuid = str(uuid.uuid1())
self.ip = self.config.axon.ip
self.port = self.config.axon.port
self.external_ip = (
self.config.axon.external_ip
if self.config.axon.external_ip is not None
else bittensor.utils.networking.get_external_ip()
)
self.external_port = (
self.config.axon.external_port
if self.config.axon.external_port is not None
else self.config.axon.port
)
self.full_address = str(self.config.axon.ip) + ":" + str(self.config.axon.port)
self.started = False
# Build middleware
self.thread_pool = bittensor.PriorityThreadPoolExecutor(
max_workers=self.config.axon.max_workers
)
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 bittensor.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: bittensor.Synapse) -> bittensor.Synapse:
return r
self.attach(
forward_fn=ping, verify_fn=None, blacklist_fn=None, priority_fn=None
)
def info(self) -> "bittensor.AxonInfo":
"""Returns the axon info object associated with this axon."""
return bittensor.AxonInfo(
version=bittensor.__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,
) -> "bittensor.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 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 (Callable, optional): 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 (Callable, optional): 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 (Callable, optional): 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, bittensor.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_synapse = forward_fn(*args, **kwargs)
if isinstance(response_synapse, Awaitable):
response_synapse = await response_synapse
return await self.middleware_cls.synapse_to_response(
synapse=response_synapse, start_time=start_time
)
# replace the endpoint signature, but set return annotation to JSONResponse
endpoint.__signature__ = Signature( # type: ignore
parameters=list(forward_sig.parameters.values()),
return_annotation=JSONResponse,
)
# Add the endpoint to the router, making it available on both GET and POST methods
self.router.add_api_route(
f"/{request_name}",
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(
"synapse",
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
), "The blacklist_fn function must have the signature: blacklist( synapse: {} ) -> Tuple[bool, str]".format(
request_name
)
if priority_fn:
priority_sig = Signature(expected_params, return_annotation=float)
assert (
signature(priority_fn) == priority_sig
), "The priority_fn function must have the signature: priority( synapse: {} ) -> float".format(
request_name
)
if verify_fn:
verify_sig = Signature(expected_params, return_annotation=None)
assert (
signature(verify_fn) == verify_sig
), "The verify_fn function must have the signature: verify( synapse: {} ) -> None".format(
request_name
)
# 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) -> "bittensor.config":
"""
Parses the command-line arguments to form a Bittensor configuration object.
Returns:
bittensor.config: Configuration object with settings from command-line arguments.
"""
parser = argparse.ArgumentParser()
axon.add_args(parser) # Add specific axon-related arguments
return bittensor.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 (str, optional): 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:
# Get default values from environment variables or use default values
default_axon_port = os.getenv("BT_AXON_PORT") or 8091
default_axon_ip = os.getenv("BT_AXON_IP") or "[::]"
default_axon_external_port = os.getenv("BT_AXON_EXTERNAL_PORT") or None
default_axon_external_ip = os.getenv("BT_AXON_EXTERNAL_IP") or None
default_axon_max_workers = os.getenv("BT_AXON_MAX_WORERS") or 10
# 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=default_axon_port,
)
parser.add_argument(
"--" + prefix_str + "axon.ip",
type=str,
help="""The local ip this axon binds to. ie. [::]""",
default=default_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=default_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=default_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=default_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: "bittensor.config"):
"""
This method checks the configuration for the axon's port and wallet.
Args:
config (bittensor.config): The config object holding axon settings.
Raises:
AssertionError: If the axon or external ports are not in range [1024, 65535]
"""
assert (
config.axon.port > 1024 and config.axon.port < 65535
), "Axon port must be in range [1024, 65535]"
assert config.axon.external_port is None or (
config.axon.external_port > 1024 and 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.
"""
return "Axon({}, {}, {}, {}, {})".format(
self.ip,
self.port,
self.wallet.hotkey.ss58_address,
"started" if self.started else "stopped",
list(self.forward_fns.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) -> "bittensor.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.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) -> "bittensor.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.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[bittensor.subtensor] = None
) -> "bittensor.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 (bittensor.subtensor, optional): The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations.
Returns:
bittensor.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: bittensor.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.
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.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")
# If we don't have a nonce stored, ensure that the nonce falls within
# a reasonable delta.
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.
if (
self.nonces.get(endpoint_key) is None
and synapse.dendrite.nonce
<= time.time_ns() - ALLOWED_DELTA - (synapse.timeout or 0)
):
raise Exception("Nonce is too old")
if (
self.nonces.get(endpoint_key) is not None
and synapse.dendrite.nonce <= self.nonces[endpoint_key]
):
raise Exception("Nonce is too old")
else:
if (
endpoint_key in self.nonces.keys()
and self.nonces[endpoint_key] is not None
and synapse.dendrite.nonce <= self.nonces[endpoint_key]
):
raise Exception("Nonce is too small")
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: bittensor.Synapse):
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: bittensor.Synapse,
exception: Exception,
status_code: typing.Optional[int] = None,
start_time: typing.Optional[float] = None,
):
if isinstance(exception, SynapseException):
synapse = exception.synapse or synapse
bittensor.logging.trace(f"Forward handled exception: {exception}")
else:
bittensor.logging.trace(f"Forward exception: {traceback.format_exc()}")
if synapse.axon is None:
synapse.axon = bittensor.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
bittensor.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.