Skip to content

Commit e01253c

Browse files
author
latentvector
committed
refactorign
1 parent 9c22ba5 commit e01253c

File tree

11 files changed

+264
-468
lines changed

11 files changed

+264
-468
lines changed

commune/key/app.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ class KeyDashboard(c.Module):
55

66
def __init__(self, state: dict=None):
77

8+
89
self.keys = c.keys()
910
self.key2index = {k:i for i,k in enumerate(self.keys)}
1011

@@ -45,16 +46,21 @@ def remove_key(self):
4546
c.rm_keys(rm_keys)
4647

4748
@classmethod
48-
def dashboard(cls, *args, **kwargs):
49+
def app(cls, *args, **kwargs):
4950
self = cls(*args, **kwargs)
5051

5152
for k in ['select', 'create', 'rename', 'remove']:
5253
fn_name = k + '_key'
5354
with st.expander(fn_name.capitalize().replace('_',' ')):
5455
getattr(self, fn_name)()
55-
5656
return self.key
5757

5858

59-
KeyDashboard.run(__name__)
59+
60+
def ticket(self, *args, **kwargs):
61+
data = st.text_input('Data', 'None')
62+
return self.key.ticket(data)
63+
64+
65+
b = KeyDashboard.run(__name__)
6066

commune/key/key.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,10 @@ def __init__(self,
116116

117117
self.crypto_type = crypto_type
118118
self.seed_hex = seed_hex
119-
self.derive_path = None
119+
self.derive_path = derive_path
120120
self.path = path
121121
self.ss58_format = ss58_format
122+
122123

123124

124125
if crypto_type != KeypairType.ECDSA and ss58_address and not public_key:
@@ -276,10 +277,6 @@ def load_key(cls, path=None):
276277
return {'status': 'success', 'message': f'key loaded from {path}'}
277278

278279

279-
@classmethod
280-
def load_keys(cls, path=keys_path, verbose:bool = False, refresh:bool = False, **kwargs):
281-
return cls.load_mems(path, verbose=verbose, refresh=refresh, **kwargs)
282-
283280
@classmethod
284281
def save_keys(cls, path='saved_keys.json', **kwargs):
285282
path = cls.resolve_path(path)

commune/module/module.py

+15-21
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,11 @@ def load_yaml(cls, path:str=None, default={}, **kwargs) -> Dict:
279279
'''
280280
import yaml
281281
path = cls.resolve_path(path)
282-
283282
try:
284283
with open(path, 'r') as file:
285284
data = yaml.safe_load(file)
286285
except:
287286
data = default
288-
289287
return data
290288

291289
get_yaml = load_yaml
@@ -372,23 +370,16 @@ def load_config(cls, path:str=None, to_munch:bool = False) -> Union[Munch, Dict]
372370
path: The path to the config file
373371
to_munch: If true, then convert the config to a munch
374372
'''
375-
376373
if path == None:
377374
path = cls.config_path()
378375
else:
379-
module_tree = c.tree()
380-
path = module_tree[path].replace('.py', '.yaml')
381-
376+
path = c.tree().get(path, path).replace('.py', '.yaml')
382377
config = cls.load_yaml(path)
383378

384-
# convert to munch
385-
if config == None:
386-
config = {}
387-
379+
config = config or {}
388380
# convert to munch
389381
if to_munch:
390382
config = cls.dict2munch(config)
391-
392383
return config
393384

394385

@@ -775,12 +766,18 @@ def sys_path(cls, *args, **kwargs):
775766
@classmethod
776767
def import_module(cls, import_path:str) -> 'Object':
777768
from importlib import import_module
769+
pwd = c.pwd()
778770
try:
779771
return import_module(import_path)
780772
except Exception as e:
781773
import sys
782-
sys.path.append(c.pwd())
783-
return import_module(import_path)
774+
sys.path.append(pwd)
775+
sys.path = list(set(sys.path))
776+
try:
777+
return import_module(import_path)
778+
except Exception as e:
779+
print(f'Error: {e}')
780+
raise e
784781

785782
def can_import_module(self, module:str) -> bool:
786783
'''
@@ -1322,7 +1319,6 @@ def get_module(cls,
13221319
try:
13231320
module = c.simple2object(path)
13241321
except Exception as e:
1325-
raise e
13261322
if trials == 0:
13271323
raise Exception(f'Could not find {path} in {c.modules(path)} modules')
13281324
c.print(f'Could not find {path} in {c.modules(path)} modules, so we are updating the tree', color='red')
@@ -1450,19 +1446,17 @@ def repo2module(self, repo:str, name=None, template_module='demo', **kwargs):
14501446
def simple2path(cls, path:str, **kwargs) -> str:
14511447
return c.module('tree').simple2path(path, **kwargs)
14521448

1449+
14531450
@classmethod
1454-
def simple2objectpath(cls, path:str,path2objectpath = {'tree': 'commune.tree.tree.Tree'}, **kwargs) -> str:
1451+
def simple2object(cls, path:str, path2objectpath = {'tree': 'commune.tree.tree.Tree'}, **kwargs) -> str:
14551452

14561453

14571454
if path in path2objectpath:
1458-
object_path = path2objectpath[path]
1455+
path = path2objectpath[path]
14591456
else:
1460-
object_path = c.module('tree').simple2objectpath(path, **kwargs)
1457+
path = c.module('tree').simple2objectpath(path, **kwargs)
14611458

1462-
return object_path
1463-
@classmethod
1464-
def simple2object(cls, path:str, **kwargs) -> str:
1465-
path = c.simple2objectpath(path, **kwargs)
1459+
14661460
try:
14671461
return c.import_object(path)
14681462
except Exception as e:

commune/server/access.py

+31-41
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ class Access(c.Module):
99

1010
def __init__(self,
1111
module : Union[c.Module, str] = None, # the module or any python object
12-
network: str = 'subspace:main', # mainnet
13-
netuid: int = 0, # subnet id
12+
network: str = 'subspace', # mainnet
13+
netuid: int = 'all', # subnet id
1414
timescale:str = 'min', # 'sec', 'min', 'hour', 'day'
1515
stake2rate: int = 100.0, # 1 call per every N tokens staked per timescale
1616
max_rate: int = 1000.0, # 1 call per every N tokens staked per timescale
@@ -25,84 +25,79 @@ def __init__(self,
2525

2626
self.set_config(locals())
2727
self.user_module = c.module("user")()
28-
self.address2key = c.address2key()
29-
self.set_module(module)
3028
self.state_path = state_path
3129
if refresh:
3230
self.rm_state()
33-
3431
self.last_time_synced = c.time()
3532
self.state = {'sync_time': 0,
3633
'stake_from': {},
3734
'role2rate': role2rate,
3835
'fn_info': {}}
36+
37+
self.set_module(module)
3938

4039
c.thread(self.run_loop)
4140

42-
43-
def set_module(self, module: c.Module):
44-
module = module or c.module('module')()
41+
def set_module(self, module):
4542
if isinstance(module, str):
4643
module = c.module(module)()
4744
self.module = module
48-
c.print(f'🚀 Access module set to {module} 🚀\033', color='yellow')
49-
self.whitelist = list(set(self.module.whitelist + c.whitelist))
50-
self.blacklist = list(set(self.module.blacklist + c.blacklist))
45+
return module
5146

52-
return {'success': True, 'msg': f'set module to {module}'}
5347

5448
def run_loop(self):
5549
while True:
5650
try:
5751
r = self.sync_network()
5852
except Exception as e:
5953
r = c.detailed_error(e)
54+
c.print(r)
6055
c.sleep(self.config.sync_interval)
6156

57+
6258
def sync_network(self, update=False, max_age=None):
6359
state = self.get(self.state_path, {}, max_age=self.config.sync_interval)
6460
time_since_sync = c.time() - state.get('sync_time', 0)
6561
self.key2address = c.key2address()
6662
self.address2key = c.address2key()
67-
if time_since_sync > self.config.sync_interval:
68-
if 'subspace:' in self.config.network:
69-
self.config.network = self.config.network.replace('subspace:', '')
70-
self.subspace = c.module('subspace')(network=self.config.network)
71-
max_age = max_age or self.config.max_age
72-
state['stakes'] = self.subspace.stakes(fmt='j', netuid='all', update=False, max_age=max_age)
73-
self.state = state
74-
self.put(self.state_path, self.state)
75-
c.print(f'🔄 Synced {self.state_path} 🔄\033', color='yellow')
76-
77-
response = {'success': True,
78-
'msg': f'synced {self.state_path}',
63+
response = {'msg': f'synced {self.state_path}',
7964
'until_sync': int(self.config.sync_interval - time_since_sync),
8065
'time_since_sync': int(time_since_sync)}
66+
67+
if time_since_sync < self.config.sync_interval:
68+
response['msg'] = 'synced too earlly'
69+
return response
70+
71+
self.subspace = c.module('subspace')(network=self.config.network)
72+
max_age = max_age or self.config.max_age
73+
state['stakes'] = self.subspace.stakes(fmt='j', netuid=self.config.netuid, update=update, max_age=max_age)
74+
self.state = state
75+
self.put(self.state_path, self.state)
76+
c.print(f'🔄 Synced {self.state_path} at {c.datetime()} 🔄\033', color='yellow')
77+
78+
8179
return response
8280

83-
def verify(self,
84-
address='5FNBuR2yVf4A1v5nt3w5oi4ScorraGRjiSVzkXBVEsPHaGq1',
85-
fn: str = 'info' ,
86-
input:dict = None) -> dict:
81+
def forward(self, fn: str = 'info' , input:dict = None, address=None) -> dict:
8782
"""
8883
input : dict
8984
fn : str
9085
address : str
9186
9287
returns : dict
9388
"""
94-
if input is not None:
95-
address = input.get('address', address)
96-
fn = input.get('fn', fn)
89+
input = input or {}
90+
address = input.get('address', address)
91+
assert address, f'address not in input or as an argument'
92+
fn = input.get('fn', fn)
9793

9894
# ONLY THE ADMIN CAN CALL ANY FUNCTION, THIS IS A SECURITY FEATURE
9995
# THE ADMIN KEYS ARE STORED IN THE CONFIG
10096
if c.is_admin(address):
10197
return {'success': True, 'msg': f'is verified admin'}
102-
10398

104-
assert fn in self.whitelist , f"Function {fn} not in whitelist={self.whitelist}"
105-
assert fn not in self.blacklist, f"Function {fn} is blacklisted={self.blacklist}"
99+
assert fn in self.module.whitelist , f"Function {fn} not in whitelist={self.module.whitelist}"
100+
assert fn not in self.module.blacklist, f"Function {fn} is blacklisted={self.module.blacklist}"
106101

107102
if address in self.address2key:
108103
return {'success': True, 'msg': f'address {address} is a local key'}
@@ -142,7 +137,6 @@ def verify(self,
142137

143138
rate_limit = (total_stake_score / stake2rate) # convert the stake to a rate
144139

145-
146140
# STEP 3: CHECK THE MAX RATE
147141
max_rate = fn2info.get('max_rate', self.config.max_rate)
148142
rate_limit = min(rate_limit, max_rate) # cap the rate limit at the max rate
@@ -181,11 +175,7 @@ def verify(self,
181175
self.state['user_info'][address] = user_info
182176
# check the rate limit
183177
return user_info
184-
185-
@classmethod
186-
def get_access_state(cls, module):
187-
access_state = cls.get(module)
188-
return access_state
178+
verify = forward
189179

190180
@classmethod
191181
def test_whitelist(cls, key='vali::fam', base_rate=2, fn='info'):
@@ -194,7 +184,7 @@ def test_whitelist(cls, key='vali::fam', base_rate=2, fn='info'):
194184

195185
for i in range(base_rate*3):
196186
t1 = c.time()
197-
result = module.verify(**{'address': key.ss58_address, 'fn': 'info'})
187+
result = module.forward(**{'address': key.ss58_address, 'fn': 'info'})
198188
t2 = c.time()
199189
c.print(f'🚨 {t2-t1} seconds... 🚨\033', color='yellow')
200190

0 commit comments

Comments
 (0)