-
Notifications
You must be signed in to change notification settings - Fork 7
/
dojo_cli.py
350 lines (284 loc) · 10.9 KB
/
dojo_cli.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
import argparse
from pathlib import Path
from typing import Callable, Dict
import bittensor
import requests
from prompt_toolkit import PromptSession, prompt
from prompt_toolkit.completion import FuzzyCompleter, WordCompleter
from rich.console import Console
from dojo import get_dojo_api_base_url
from dojo.utils.config import get_config, source_dotenv
get_config()
source_dotenv()
DOJO_API_BASE_URL = get_dojo_api_base_url()
console = Console()
def success(message: str, emoji: str = ":white_check_mark:"):
console.print(f"{emoji} [green]{message}[/green]")
def info(message: str, emoji: str = ":information_source:"):
console.print(f"{emoji} [white]{message}[/white]")
def error(message: str, emoji: str = ":x:"):
console.print(f"{emoji} [red]{message}[/red]")
def warning(message: str, emoji: str = ":warning:"):
console.print(f"{emoji} [yellow]{message}[/yellow]")
def api_key_list(cookies):
response = requests.get(
f"{DOJO_API_BASE_URL}/api/v1/miner/api-key/list", cookies=cookies
)
response.raise_for_status()
keys = response.json().get("body", {}).get("apiKeys")
if len(keys) == 0:
warning("No API keys found, please generate one.")
else:
success(f"All API keys: {keys}")
return keys
def api_key_generate(cookies):
response = requests.post(
f"{DOJO_API_BASE_URL}/api/v1/miner/api-key/generate", cookies=cookies
)
response.raise_for_status()
keys = response.json().get("body", {}).get("apiKeys")
success(f"All API keys: {keys}")
return keys
def api_key_delete(cookies):
keys = api_key_list(cookies)
if not keys:
return
key_completer = FuzzyCompleter(WordCompleter(keys, ignore_case=True))
selected_key = prompt(
"Select an API key to delete: ",
completer=key_completer,
swap_light_and_dark_colors=True,
)
if selected_key not in keys:
error("Invalid selection.")
return
response = requests.put(
f"{DOJO_API_BASE_URL}/api/v1/miner/api-key/disable",
json={"apiKey": selected_key},
cookies=cookies,
)
response.raise_for_status()
remaining_keys = response.json().get("body", {}).get("apiKeys")
success(f"Remaining API keys: {remaining_keys}")
return
def subscription_key_list(cookies):
response = requests.get(
f"{DOJO_API_BASE_URL}/api/v1/miner/subscription-key/list", cookies=cookies
)
response.raise_for_status()
keys = response.json().get("body", {}).get("subscriptionKeys")
if len(keys) == 0:
warning("No subscription keys found, please generate one.")
else:
success(f"All subscription keys: {keys}")
return keys
def subscription_key_generate(cookies):
response = requests.post(
f"{DOJO_API_BASE_URL}/api/v1/miner/subscription-key/generate", cookies=cookies
)
response.raise_for_status()
keys = response.json().get("body", {}).get("subscriptionKeys")
success(f"All subscription keys: {keys}")
return keys
def subscription_key_delete(cookies):
keys = subscription_key_list(cookies)
if not keys:
return
key_completer = FuzzyCompleter(WordCompleter(keys, ignore_case=True))
selected_key = prompt(
"Select a subscription key to delete: ",
completer=key_completer,
swap_light_and_dark_colors=True,
)
if selected_key not in keys:
error("Invalid selection.")
return
response = requests.put(
f"{DOJO_API_BASE_URL}/api/v1/miner/subscription-key/disable",
json={"subscriptionKey": selected_key},
cookies=cookies,
)
response.raise_for_status()
remaining_keys = response.json().get("body", {}).get("subscriptionKeys")
success(f"Remaining subscription keys: {remaining_keys}")
return
def _get_session_cookies(hotkey: str, signature: str, message: str):
url = f"{DOJO_API_BASE_URL}/api/v1/miner/session/auth"
if not signature.startswith("0x"):
signature = "0x" + signature
payload = {
"hotkey": hotkey,
"signature": signature,
"message": message,
}
response = requests.post(url, json=payload)
response.raise_for_status()
cookies = response.cookies.get_dict()
return cookies
class State:
def __init__(self, config):
self.cookies = None
self.wallet = bittensor.wallet(config=config)
# cli = bittensor.cli(config=config)
# self.subtensor = bittensor.subtensor(config=config)
# axons = self.subtensor.metagraph(netuid=cli.config.netuid, lite=False).axons
def get_session_cookies(wallet):
kp = wallet.hotkey
hotkey = str(wallet.hotkey.ss58_address)
raw_message = "Sign in to Dojo with Substrate"
def prepare_message(message: str):
return f"<Bytes>{message}</Bytes>"
prepared_message = prepare_message(raw_message)
signature = kp.sign(prepared_message).hex()
try:
cookies = _get_session_cookies(hotkey, signature, raw_message)
success("Successfully got session cookies :cookie:")
return cookies
except Exception as e:
error(f"Failed to get session cookies due to exception: {e}")
pass
return
def clear_session_cookies(state: State):
state.cookies = None
success("Successfully :skull: session cookies :cookie:")
return
def placeholder():
success("go implement it")
subscription_key_actions = {
"list": subscription_key_list,
"generate": subscription_key_generate,
"delete": subscription_key_delete,
}
api_key_actions = {
"list": api_key_list,
"generate": api_key_generate,
"delete": api_key_delete,
}
nested_actions: Dict[str, Callable] = {
"authenticate": get_session_cookies,
"api_key": api_key_actions,
"subscription_key": subscription_key_actions,
"clear_cookies": clear_session_cookies,
}
def nested_dict_none(d):
"""replace values which are func calls with None else assertion error"""
if not isinstance(d, dict):
return None
return {k: nested_dict_none(v) for k, v in d.items()}
# nested_completer_data = nested_dict_none(nested_actions)
def flatten_nested_dict(d, parent_key="", sep=" "):
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_nested_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def main():
parser = argparse.ArgumentParser(description="Bittensor Wallet CLI")
bittensor.wallet.add_args(parser)
config = bittensor.config(parser)
info(f"Using bittensor config:\n{config}")
is_wallet_valid = False
is_wallet_path_decided = False
is_coldkey_valid = False
is_hotkey_valid = False
default_wallet_path = Path(config.wallet.path).expanduser()
while not is_wallet_valid:
while not is_wallet_path_decided:
use_default_path = (
input(
f"Do you want to use the default wallet path {default_wallet_path}? (y/n): "
)
.strip()
.lower()
)
if use_default_path == "y":
config.wallet.path = str(default_wallet_path)
is_wallet_path_decided = True
elif use_default_path == "n":
config.wallet.path = str(input("Enter the wallet path: ").strip())
if Path(config.wallet.path).expanduser().exists():
is_wallet_path_decided = True
else:
error(
f"Invalid wallet path {config.wallet.path}, please try again."
)
continue
info(
"Please specify the wallet coldkey name and hotkey name to perform key management."
)
if not is_coldkey_valid:
# config.wallet.name = input("Enter the wallet coldkey name: ").strip()
coldkeys = [
f.name
for f in Path(config.wallet.path).expanduser().iterdir()
if f.is_dir()
]
coldkey_completer = WordCompleter(coldkeys, ignore_case=True)
config.wallet.name = prompt(
"Enter the wallet coldkey name: ",
completer=coldkey_completer,
swap_light_and_dark_colors=False,
).strip()
coldkey_path = Path(config.wallet.path).expanduser() / config.wallet.name
if not coldkey_path.exists():
error(f"Coldkey path is invalid {coldkey_path}")
continue
else:
is_coldkey_valid = True
if not is_hotkey_valid:
hotkeys_path = coldkey_path / "hotkeys"
hotkeys = [f.name for f in hotkeys_path.iterdir() if f.is_file()]
hotkey_completer = WordCompleter(hotkeys, ignore_case=True)
config.wallet.hotkey = prompt(
"Enter the wallet hotkey name: ",
completer=hotkey_completer,
swap_light_and_dark_colors=False,
).strip()
# config.wallet.hotkey = input("Enter the wallet hotkey name: ").strip()
hotkey_path = coldkey_path / "hotkeys" / config.wallet.hotkey
if not hotkey_path.exists():
error(f"Hotkey path is invalid {hotkey_path}")
continue
else:
is_hotkey_valid = True
info(f"Coldkey path: {coldkey_path}")
info(f"Hotkey path: {hotkey_path}")
if coldkey_path.exists() and hotkey_path.exists():
is_wallet_valid = True
success("Wallet coldkey name and hotkey name set successfully.")
state = State(config)
# method_completer = NestedCompleter.from_nested_dict(nested_dict_none(actions))
flattened_actions = flatten_nested_dict(nested_actions)
method_completer = WordCompleter(words=flattened_actions.keys(), ignore_case=True)
session = PromptSession(
completer=method_completer, swap_light_and_dark_colors=False
)
while True:
try:
text = session.prompt(">>> ", completer=method_completer)
parsed_text = text.strip().lower()
if parsed_text == "exit":
break
action = flattened_actions.get(parsed_text)
if action:
if action == get_session_cookies:
state.cookies = action(state.wallet)
elif action == clear_session_cookies:
action(state)
else:
if state.cookies is None:
warning("No session found, please authenticate first.")
continue
action(state.cookies)
else:
warning("Invalid action, please try again")
except (KeyboardInterrupt, EOFError):
break
except Exception as e:
error(f"Please try again, exception occurred: {e}")
pass
if __name__ == "__main__":
main()