-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
388 lines (333 loc) · 14.3 KB
/
__main__.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, subprocess, time, pprint, os, getpass, json
from tabulate import tabulate
from casper import CasperCore
from casper.utils import verify_password, parse_yaml, Yaml, date_crop
from janalyze import JAnalyze
# os.environ["PYTHONIOENCODING"] = "utf-8"
yaml = Yaml()
_MENU = """
Please choose an option:
(1) Create New Testnet Address (2) Import Existing Address (3) Load Address
(4) Create Stake Pool (5) Delegate Stake (6) Send Transaction
(7) Display Current Address (8) Check Balance (9) Show All Accounts
(10) Show Message Log (11) Show Node stats (12) Show Established Peers
(13) Show Stake Pools (14) Show Stake (15) Show Blockchain Size
(16) Show Leader Logs (17) Show Settings (18) Aggregate Blocks Produced
(19) Stake Distribution (20) Genesis Decode (21) Lost Blocks
(e) Export All Accounts (i) Import accounts.yaml (f) View Config File
(v) Show Versions (c) Clear Screen (q) Quit
"""
if os.path.exists("config/settings.yaml") is False:
exec(open("config/__main__.py").read(), globals())
print("\n\nSTARTING CASPER")
settings = parse_yaml("config/settings.yaml", file=True)
if "userpwd" in settings:
# saving password in settings file is only thought for dev mode
# use on your own risk
_USER_PWD = settings["userpwd"]
else:
_USER_PWD = getpass.getpass("Enter your Password: ")
if "cryptomodule" in settings:
_DEFAULT_CRYPTO = settings["cryptomodule"]
else:
_DEFAULT_CRYPTO = input("ENTER CRYPT MODULE (Fernet, PyCrypto, RAW): ")
if _DEFAULT_CRYPTO is "RAW":
_DEFAULT_CRYPTO = None
cspr = CasperCore(settings, USER_PWD=_USER_PWD, CRYPTO_MOD=_DEFAULT_CRYPTO)
analyze = JAnalyze(settings)
class CliInterface:
@classmethod
def typed_text(cls, string, sleep_time, pause=0.5):
cls.string = string
cls.sleep_time = sleep_time
cls.pause = pause
''' Mimic human typing '''
for letter in cls.string:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(cls.sleep_time)
time.sleep(cls.pause)
print("\n\n")
def __init__(self):
self.end_loop = False
self.account = None
self.typed_text('CASPER CLI UI v1.2 -- Kodex Data Systems 2019', 0.004)
print('\n\n')
def determine_status(self, log):
if "Rejected" in log["status"]:
_status = log["status"]["Rejected"]["reason"]
elif "InABlock" in log["status"]:
blockhash = log["status"]["InABlock"]["block"]
_status = blockhash[:-20] + "..."
elif "Pending" in log["status"]:
_status = "Pending"
elif "Block" in log["status"]:
_status = (log["status"]["Block"]["block"], log["status"]["Block"]["chain_length"])
else:
_status = "UNKNOWN"
return _status
def clear(self):
cls_platforms = ["linux", "linux2", "darwin"]
if sys.platform == 'win32':
subprocess.call('cls', shell=True)
elif sys.platform in cls_platforms:
subprocess.call('clear', shell=True)
else:
self.typed_text('Command not compatible with your OS', 0.002)
def save_acct_by_secret(self, _sk):
try:
secret, public, address = cspr.cli.acct_by_secret(_sk)
cspr.db.save_acct(secret, public, address)
self.typed_text(f'Account Added: {address}', 0.002)
except:
print("IMPORT ERROR")
def run(self):
while not self.end_loop:
print(_MENU)
choice = input('Your Choice: ')
if choice == '1': # Create.
self.clear()
_sk, _pk, _ak = cspr.cli.create_acct()
cspr.db.save_acct(_sk, _pk, _ak)
self.typed_text(f'Account Created: {_ak}', 0.002)
if choice == '2': # Import existing.
self.clear()
_sk = input("Input Secret Key: ")
self.save_acct_by_secret(_sk)
if choice == '3': # Load.
self.clear()
myaccounts = cspr.db.all_acct()
if myaccounts is not None:
for acct in myaccounts:
print(acct[0], acct[1])
_id = input("\nSelect Acount Number: ")
try:
_selected = cspr.db.get_acct_by_id(int(_id))
if _selected is not None:
self.typed_text(f'Account Loaded: {_selected[1]}', 0.002)
self.account = _selected
self.clear()
else:
print("Account Not In Database")
except:
self.typed_text(f'Account Not In List', 0.002)
if choice == '4': # Create Stake Pool
self.clear()
if self.account is not None:
pool_name = input('Enter the pool name: ')
account = self.account[1]
secret = self.account[2]
public = self.account[3]
print('\nStake Pool ID')
print('-' * 33)
cspr.cli.create_pool(public, secret, account, pool_name)
else:
print("You Need To Load An Account First")
if choice == '5': # Delegate Stake Pool
self.clear()
if self.account is not None:
pool = input('Enter Stake Pool: ')
account = self.account[1]
public = self.account[3]
secret = self.account[2]
self.clear()
tx = cspr.cli.create_delegation_certificate(pool, public, secret, account)
print(f"Delegation Fragment: {tx[0]}")
else:
print("You Need To Load An Account First")
if choice in ("6", "tx"): # Send Tx.
self.clear()
if self.account is not None:
sender = self.account[1]
secret = self.account[2]
amount = int(input('Enter Send Amount: '))
receiver = input('Receiver: ')
rounds = input("Send Single Transaction (Y/n): ").lower()
if rounds == "y":
self.clear()
cspr.cli.send_single_tx(
amount,
sender,
receiver,
secret
)
else:
self.clear()
rounds = int(input("Enter Number Of Cycles: "))
cspr.cli.send_multiple_tx(
amount,
sender,
receiver,
secret,
rounds,
False
)
else:
print("You Need To Load An Account First")
if choice == '7': # Display current.
self.clear()
if self.account is None:
print("No Account Loaded")
else:
print(f'Loaded Account: {self.account}')
if choice in ("8", "b"):
self.clear()
if self.account is None:
print("No Account Loaded")
else:
try:
addr, balance, nonce, pools = cspr.cli.show_balance(
self.account[1],
raw=False
)
print(f"Address: {addr}\nBalance: {balance}\nNonce: {nonce}")
c = 0
if len(pools) > 0:
for pool in pools:
c = c + 1
print(f"POOL {c}: {pool[0]} || WEIGHT: {pool[1]}")
except:
print("0")
if choice == "9": # Show all accounts
self.clear()
pprint.pprint(cspr.db.all_acct())
if choice in ("10", "m"): # Message log.
self.clear()
message_logs = []
for log in cspr.cli.message_logs():
message_logs.append({
"fragment_id": log["fragment_id"],
"last_updated_at": date_crop(log["last_updated_at"]),
"received_at": date_crop(log["received_at"]),
"received_from": log["received_from"],
"status": self.determine_status(log)
})
if message_logs is not None and len(message_logs) > 0:
header = message_logs[0].keys()
rows = [x.values() for x in message_logs]
table = tabulate(rows, header, tablefmt="psql")
print(table)
else:
print("Message Logs are Empty")
if choice == '11': # Node stats.
self.clear()
pprint.pprint(cspr.node.show_node_stats())
if choice == '12': # Show Peers.
self.clear()
pprint.pprint(cspr.node.show_peers())
if choice == '13': # Show Stake Pools.
self.clear()
pools = cspr.node.show_stake_pools()
pprint.pprint(pools)
print("\n\n")
self.typed_text(f'Number of registered pools: {str(len(pools))}', 0.004)
if choice == '14': # Show Stake.
self.clear()
stake = cspr.node.show_stake()["stake"]["pools"]
table = tabulate(
stake,
headers=[
"Hex-encoded stake pool ID",
"Total pool value"
],
tablefmt="psql"
)
print(table)
if choice == '15': # Show Chain Size.
self.clear()
pprint.pprint(cspr.cli.show_blockchain_size())
if choice == '16': # Show Leaders Logs.
self.clear()
# pprint.pprint(cspr.node.show_leader_logs())
leaderlogs = []# cspr.node.show_leader_logs()
for llog in cspr.node.show_leader_logs():
_llog = {
"created_at_time": date_crop(llog["created_at_time"]),
"scheduled_at_time": date_crop(llog["scheduled_at_time"]),
"scheduled_at_date": llog["scheduled_at_date"],
"finished_at_time": date_crop(llog["finished_at_time"]),
}
if "wake_at_time" in llog:
_llog["wake_at_time"] = date_crop(llog["wake_at_time"])
_llog["status"] = self.determine_status(llog)
leaderlogs.append(_llog)
if leaderlogs is not None and len(leaderlogs) > 0:
header = leaderlogs[0].keys()
rows = [x.values() for x in leaderlogs]
table = tabulate(rows, header, tablefmt="psql")
print(table)
else:
print("Leader logs are empty")
if choice == '17': # Show Chain Settings.
self.clear()
pprint.pprint(cspr.node.show_settings())
if choice == "18": # janalyze.py aggreate blocks
self.clear()
analyze.aggregate()
if choice == "19": # janalyze.py distribution
self.clear()
analyze.distribution()
if choice == '20': # Genesis Decode.
self.clear()
print(cspr.cli.genesis_decode())
if choice == '21': # Lost Blocks
self.clear()
try:
analyze.lostblocks()
except:
print("ERROR LOST BLOCKS\n")
if choice == 'f': # Show Config.
self.clear()
pprint.pprint(settings)
if choice == 'v': # Show Versions.
self.clear()
cspr.versions()
if choice == 'q': # Quit.
self.end_loop = True
if choice == 'c': # Clear.
self.clear()
if choice == "u":
self.clear()
print(cspr.db.user)
if choice == "s":
self.clear()
pprint.pprint(settings)
if choice == "i":
self.clear()
filepath = input("PATH TO accounts.yaml: ")
if os.path.isfile(filepath):
try:
toimport = parse_yaml(filepath, file=True)
except:
print("PARSING ERROR")
for iacc in toimport:
self.save_acct_by_secret(iacc["secret"])
else:
print("FILE NOT FOUND")
if choice == "e":
self.clear()
accts = cspr.db.all_acct()
_accts = []
for acct in accts:
_accts.append({
"address": acct[1],
"public": acct[3],
"secret": acct[2]
})
_type = input("EXPORT FORMAT? (json[j] / yaml[y]): ")
if _type.lower() in ("yaml", "y"):
yaml.save_file(_accts, location=f"config/accounts.yaml")
elif _type.lower() in ("json", "j"):
with open('config/accounts.json', 'w') as f:
json.dump(_accts, f, indent=4)
else:
print("Invalid format selected")
if __name__ == "__main__":
if sys.platform == 'win32':
print("Windows not supported")
sys.exit(2)
cliui = CliInterface()
cliui.clear()
cliui.run()