-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathghostVault.py
1474 lines (1183 loc) · 55 KB
/
ghostVault.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
#!/usr/bin/env python3
import urllib.request
from urllib.request import urlopen
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import requests, os, sys, json, pprint, shutil, platform, subprocess, textwrap, time, os.path, git, psutil
import hashlib
from datetime import datetime, timedelta
from colorama import Fore, Back, Style
from colorama import init
from crontab import CronTab
init()
RPCUSER = 'user'
RPCPASSWORD = 'password'
RPCPORT = 51725
version = "v1.3.2"
system = platform.system()
def rpcproxy():
rpcproxy = AuthServiceProxy('http://%s:%[email protected]:%d/' % (RPCUSER, RPCPASSWORD, RPCPORT), timeout=120)
return rpcproxy
def checkConnect():
try:
rpcproxy().getblockchaininfo()
return True
except:
return False
def checkWalletLoad():
try:
rpcproxy().getstakinginfo()
return True
except:
return False
def daemonInfo():
with open('daemon.json') as f:
data = json.loads(f.read())
return data
def getExplorerHeight():
url = f"https://explorer.myghost.org/api/getblockcount"
response = urlopen(url)
data = json.loads(response.read())
return data
def getExplorerBlockHash(index):
url = f"https://explorer.myghost.org/api/getblockhash?index={index}"
response = urlopen(url)
data = json.loads(response.read())
return data
def getPeerCount():
peerCount = rpcproxy().getconnectioncount()
return peerCount
def getBlockHeight():
blocks = rpcproxy().getblockcount()
return blocks
def getBlockChainInfo():
blockChainInfo = rpcproxy().getblockchaininfo()
return blockChainInfo
def importKey(words):
print("Building wallet from mnemonic words.")
try:
rpcproxy().extkeyimportmaster(words, "", False, "", "", -1)
except Exception as e:
showError(e)
print('Sucessfully imported mnemonic.')
def getNewExtAddr(label):
extAddr = rpcproxy().getnewextaddress(label)
return extAddr
def getNewStealthAddr():
addr = rpcproxy().getnewstealthaddress()
return addr
def validateAddress(address):
addr = rpcproxy().validateaddress(address)
if addr['isvalid'] == True:
return True
else:
return False
def getColdStakingInfo():
if checkWalletLoad() == False:
showError(f"No wallet loaded!")
csInfo = rpcproxy().getcoldstakinginfo()
return csInfo
def getStakingInfo():
if checkWalletLoad() == False:
showError(f"No wallet loaded!")
sInfo = rpcproxy().getstakinginfo()
return sInfo
def getUptime():
uptime = rpcproxy().uptime()
return uptime
def getNetworkInfo():
network = rpcproxy().getnetworkinfo()
return network
def getBalances():
return rpcproxy().getbalances()
def getKeysAvailable():
keys = []
allKeys = rpcproxy().extkey("account")
for i in allKeys['chains']:
keyDict = {"key": "", "label": ""}
if 'function' in i or 'use_type' in i or i['receive_on'] == False or i['label'] == '':
continue
keyDict['key'] = i['chain']
keyDict['label'] = i['label']
keys.append(keyDict)
return keys
def setRewardAddress(rewardAddress, anon=False):
if validateAddress(rewardAddress) == False:
showError(f"Invalid Ghost address: {rewardAddress}")
if anon == True:
print(f"Setting reward address to: {Fore.CYAN}<Internal Stealth Address>{Style.RESET_ALL}...")
else:
print(f"Setting reward address to: {Fore.CYAN}{rewardAddress}{Style.RESET_ALL}...")
try:
rpcproxy().walletsettings("stakingoptions", {"rewardaddress": rewardAddress})
except Exception as e:
showError(e)
dInfo = daemonInfo()
dInfo['rewardAddress'] = rewardAddress
updateDaemonInfo(dInfo)
print(f"Reward address successfully updated.")
def setAnonAddress(rewardAddress):
if validateAddress(rewardAddress) == False:
showError(f"Invalid Ghost address: {rewardAddress}")
print(f"Setting anon reward address to: {Fore.CYAN}{rewardAddress}{Style.RESET_ALL}...")
dInfo = daemonInfo()
dInfo['anonRewardAddress'] = rewardAddress
updateDaemonInfo(dInfo)
print(f"Anon reward address successfully updated.")
def getRewardAddressFromWallet():
walletInfo = rpcproxy().walletsettings("stakingoptions")
if walletInfo['stakingoptions'] == 'default':
return None
elif 'rewardaddress' in walletInfo['stakingoptions']:
return walletInfo['stakingoptions']['rewardaddress']
else:
return None
def mnemonic():
words = rpcproxy().mnemonic("new", "", "english")['mnemonic']
return words
def getWallets():
wallets = rpcproxy().listwallets()
return wallets
def getWalletInfo():
walletInfo = rpcproxy().getwalletinfo()
return walletInfo
def createWallet(walletName):
rpcproxy().createwallet(walletName)
def loadWallet(walletName):
if checkWalletLoad() == True:
wallet = rpcproxy().getwalletinfo()['walletname']
if wallet == walletName:
print(f"Wallet {walletName} already loaded.")
return
else:
rpcproxy().loadwallet(walletName)
return
rpcproxy().loadwallet(walletName)
def isBadFork():
bcInfo = getBlockChainInfo()
block = bcInfo['blocks']
bestBlockHash = bcInfo['bestblockhash']
if bestBlockHash == getExplorerBlockHash(block):
return False
else:
return True
def getSystem():
arch = platform.uname()[-2]
if arch == 'armv7l':
arch = 'arm'
elif arch == 'aarch64':
arch = 'aarch64'
elif arch == 'x86_64' or arch == 'AMD64':
arch = 'x86_64'
if system == 'Darwin':
systemOS = 'MacOS'
arch = 'x86_64'
return f'{arch}-{systemOS}'
return f'{arch}-{system}'
def syncProgress():
while True:
bcInfo = getBlockChainInfo()
blocks = bcInfo['blocks']
headers = bcInfo['headers']
initialDl = bcInfo['initialblockdownload']
if headers == 0 or getPeerCount() == 0:
continue
progress = blocks / headers * 100
clear()
print(f"Ghostd is currently syncing with the Ghost network.")
print(f"Progress: {blocks:,}/{headers:,} {Fore.GREEN}{round(progress, 3)}%{Style.RESET_ALL}")
if initialDl == False or progress == 100:
time.sleep(1)
break
time.sleep(1)
def isSyncing():
bcInfo = getBlockChainInfo()
blocks = bcInfo['blocks']
headers = bcInfo['headers']
initialDl = bcInfo['initialblockdownload']
if initialDl == True or blocks != headers:
return True
else:
return False
def convertFromSat(value):
sat_readable = value / 10**8
return sat_readable
def convertToSat(value):
sat_readable = value * 10**8
return sat_readable
def clear():
if system == "Windows":
os.system('cls')
else:
os.system('clear')
def showError(err):
print(f"GhostVualt has encountered an error.\nERROR:{Fore.RED}{err}{Style.RESET_ALL}")
sys.exit()
def getLink():
with open("links.json") as f:
links = json.loads(f.read())
return links[getSystem()]['link']
def downloadFromUrl(url, path):
clear()
with open(path, "wb") as f:
print("Downloading %s" % path)
response = requests.get(url, stream=True)
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write(f"{Fore.GREEN}\r[%s%s]{Style.RESET_ALL}" % ('=' * done, ' ' * (50-done)) )
sys.stdout.flush()
clear()
def downloadDaemon():
url = getLink()
archive = getLink().split("/")[-1]
if os.path.isfile(archive) == True:
if isValidArchiveHash(archive) == False:
os.remove(archive)
downloadFromUrl(url, archive)
else:
print(f'Valid archive file found, skipping download.')
return
else:
downloadFromUrl(url, archive)
def extractDaemon():
removeDaemon()
archive = getLink().split("/")[-1]
if os.path.isfile(archive) == False:
showError(f"File {archive} not found.")
elif isValidArchiveHash(archive) == False:
showError("SHA256 hash of archive invalid. Download may be corrupted. Please retry download.")
if os.path.isfile(daemonInfo()['ghostdPath']):
print("Removing existing ghostd in favor of new one.")
removeDaemon()
if archive.endswith(".tar.gz"):
archiveFormat = 'gztar'
elif archive.endswith(".tar.xz"):
archiveFormat = 'xztar'
elif archive.endswith(".zip"):
archiveFormat = 'zip'
print("Extracting Ghostd from archive...")
try:
shutil.unpack_archive(archive, os.getcwd(), archiveFormat)
except Exception as e:
showError(e)
#time.sleep(5)
#shutil.unpack_archive(archive, os.getcwd(), archiveFormat)
for dirpath, dirnames, filenames in os.walk("."):
if system == "Windows":
for filename in [f for f in filenames if f == "ghostd.exe"]:
daemonPath = os.path.join(dirpath, filename)
else:
for filename in [f for f in filenames if f == "ghostd"]:
daemonPath = os.path.join(dirpath, filename)
dInfo = daemonInfo()
dInfo['ghostdPath'] = daemonPath
dInfo['ghostdHash'] = getDaemonHash(daemonPath)
dInfo['archive'] = archive
updateDaemonInfo(dInfo)
print("Daemon Extraction success!")
def getDaemonHash(daemonPath):
return getHash(daemonPath)
def isValidArchiveHash(archive):
readable_hash = getHash(archive)
with open("links.json") as f:
links = json.loads(f.read())
if links[getSystem()]['hash'] == readable_hash:
return True
else:
return False
def isValidDaemonHash():
storeHash = daemonInfo()['ghostdHash']
readable_hash = getHash(daemonInfo()['ghostdPath'])
if storeHash == readable_hash:
return True
else:
return False
def isStealthAddr(addr):
if validateAddress(addr) == True and addr.startswith("SP") == True:
return True
else:
return False
def getHash(path):
with open(path,"rb") as f:
bytes = f.read()
readable_hash = hashlib.sha256(bytes).hexdigest();
return readable_hash
def prepareDataDir():
if system == 'Linux':
datadir = os.path.expanduser('~/.ghost/')
elif system == 'Darwin':
datadir = os.path.expanduser('~/Library/Application Support/Ghost/')
elif system == 'Windows':
datadir = os.path.expanduser('~/AppData/Roaming/Ghost/')
if os.path.isdir(datadir):
print('Data directory found...')
print('Copying configuration file to data directory...')
shutil.copy('templates/ghost.conf', datadir)
else:
print("Data directory not found, creating...")
os.mkdir(datadir)
print('Copying configuration file to data directory...')
shutil.copy('templates/ghost.conf', datadir)
def clearBlocks():
if system == 'Linux':
datadir = os.path.expanduser('~/.ghost')
elif system == 'Darwin':
datadir = os.path.expanduser('~/Library/Application Support/Ghost')
elif system == 'Windows':
datadir = os.path.expanduser('~/AppData/Roaming/Ghost')
rmdir = ['blocks', 'chainstate']
print("Clearing blocks...")
for i in rmdir:
shutil.rmtree(f'{datadir}/{i}/')
os.remove(f'{datadir}/peers.dat')
os.remove(f'{datadir}/banlist.dat')
print('Blocks successfully cleared.')
def createBatchFiles():
print('Preparing batch files...')
batchFiles = [('vaultStart.bat', 'start'), ('vaultUpdate.bat', 'update'), ('vaultPay.bat', 'cronpay')]
for i in batchFiles:
if os.path.isfile(f'{i[0]}'):
print(f"Batch file '{i[0]}' found. Skipping")
else:
print(f"Creating batch file '{i[0]}'...")
with open(f"{i[0]}", "w") as f:
f.write(f'@echo off\npowershell -window hidden -command "cd {os.path.expanduser("~")}\\GhostVault\\ ; {shutil.which("python")} ghostVault.py {i[1]}\nexit"')
print("Success!")
def updateDaemonInfo(dInfo):
with open('daemon.json', 'r+') as f:
f.seek(0)
json.dump(dInfo, f, indent = 4)
f.truncate()
def startDaemon():
if os.path.isfile(daemonInfo()['ghostdPath']) == False:
showError(f"ghostd not found! run GhostVault with 'forceupdate' or 'quickstart' argument to install daemon.")
elif getDaemonHash(daemonInfo()['ghostdPath']) != daemonInfo()['ghostdHash']:
showError(f"Daemon hash not as expected! Daemon may be courupted.\nPlease run 'ghostVault.py forceupdate' to rectify.")
elif checkConnect() == True:
print("Daemon already running...")
else:
if system == "Windows":
print("Ghost Core starting")
subprocess.Popen(f"start cmd /C {daemonInfo()['ghostdPath']}", shell=True)
else:
subprocess.call([f"{daemonInfo()['ghostdPath']}", "-daemon"])
waitForDaemon()
try:
loadWallet(daemonInfo()['walletName'])
except:
pass
def stopDaemon():
if checkConnect() == False:
print("Daemon not running...")
else:
print(rpcproxy().stop())
def restartDaemon():
print('Restarting daemon...')
stopDaemon()
waitForDaemonShutdown()
startDaemon()
def removeDaemon():
if daemonInfo()['ghostdPath'] == "":
return
elif os.path.isfile(daemonInfo()['ghostdPath']) == False:
return
if system == 'Windows':
daemonDir = daemonInfo()['ghostdPath'].split('\\')[1]
else:
daemonDir = f"{daemonInfo()['ghostdPath'].split('/')[1]}/"
stopDaemon()
print('Removing deamon directory.')
shutil.rmtree(daemonDir)
dInfo = daemonInfo()
dInfo['ghostdPath'] = ""
dInfo['ghostdHash'] = ""
updateDaemonInfo(dInfo)
def removeArchive():
archive = getLink().split("/")[-1]
if os.path.isfile(archive):
print(f'Removing archive file {archive}...')
os.remove(archive)
else:
print('Archive file not found.')
dInfo = daemonInfo()
dInfo['archive'] = ""
updateDaemonInfo(dInfo)
def getStats(duration="all", days=None):
tnow = time.time()
day = 86400
if checkWalletLoad() == False:
try:
loadWallet(daemonInfo()['walletName'])
except:
showError(f"Now wallet loaded!")
if duration == 'all' and days == None:
last24 = tnow - day
last7d = tnow - day *7
last30d = tnow - day *30
last180d = tnow - day *180
last365d = tnow - day *365
durations = [("24h", last24), ("7 Days", last7d), ("30 Days", last30d), ("180 Days", last180d), ("Year", last365d)]
clear()
print(f"GhostVault {version} Staking Stats Page\n")
print(f"{Fore.BLUE}DURATION STAKES FOUND AMOUNT EARNED{Style.RESET_ALL}")
for i in durations:
filter = rpcproxy().filtertransactions({"from":int(i[1]), "to":int(tnow),"count":100000,"category":"stake","collate":True,"include_watchonly":True,"with_reward":True})
print(f"Last {i[0]:<9} {Fore.GREEN}{filter['collated']['records']} {filter['collated']['total_reward']}{Style.RESET_ALL}")
oneStake = rpcproxy().filtertransactions({"count":1,"category":"stake","include_watchonly":True})
timeToFind = getStakingInfo()['expectedtime']
if timeToFind == 0:
timeToFind = 1
if len(oneStake) != 0:
etime = tnow - int(oneStake[0]['time'])
nextReward = timeToFind - etime
else:
etime = 1
nextReward = 0
percentToReward = etime / timeToFind * 100
ghostPerDay = day / timeToFind
print("\n")
print(f"Network stake weight : {convertFromSat(int(getStakingInfo()['netstakeweight'])):,}")
print(f"Current stake weight : {getColdStakingInfo()['currently_staking']:,} | {round(float(getColdStakingInfo()['currently_staking']) / convertFromSat(int(getStakingInfo()['netstakeweight']))*100, 2)}%")
if timeToFind == 1:
pass
else:
print(f"EST Time to find : {str(timedelta(seconds=timeToFind)).split('.')[0]}")
if nextReward == 0:
pass
else:
if nextReward < 0:
print(f"EST Time to next reward: -{str(timedelta(seconds=nextReward*-1)).split('.')[0]} | {round(percentToReward, 2)}%")
else:
print(f"EST Time to next reward: {str(timedelta(seconds=nextReward)).split('.')[0]} | {round(percentToReward, 2)}%")
print(f"EST Stakes per day : {round(ghostPerDay, 2)}")
print(f"EST Ghost per day : {round(ghostPerDay*3.876, 8):,}")
def quickstart():
newWallet = True
clear()
print(f"Welcome to GhostVault quickstart guide.")
print(f"This is an automated guide that will assist you in setting up your coldstakig node.")
print(f"This guide will also try to detect existing wallets and settings.")
print(f"To start with, we will download the daemon and get synced with the Ghost network.")
input("Press Enter to continue...")
stopDaemon()
waitForDaemonShutdown()
downloadDaemon()
extractDaemon()
prepareDataDir()
startDaemon()
try:
loadWallet(daemonInfo()['walletName'])
except:
pass
if isSyncing() == True:
syncProgress()
if isBadFork() == True:
print(f"ERROR: {Fore.RED}Bad Fork detected!{Style.RESET_ALL}")
while True:
ans = input(f"Would you like to resync to the correct chain? {Fore.GREEN}Y/{Fore.RED}n{Style.RESET_ALL} ")
if ans.lower() == 'y' or ans.lower() == '':
print("Forcing resync...")
stopDaemon()
waitForDaemonShutdown()
clearBlocks()
startDaemon()
if isSyncing() == True:
syncProgress()
if isBadFork() == True:
showError(f"Bad fork still detected. Re-run GhostVault with 'forcerescan'")
break
elif ans.lower() == 'n':
print(f"{Fore.RED}Exiting!{Style.RESET_ALL}")
sys.exit()
else:
print("Invalid answer! Please enter either 'y' or 'n'")
input("Press Enter to continue...")
clear()
if len(getWallets()) == 0:
print(f"No existing wallets detected.")
print(f"Sometimes GhostVault will not find a wallet that is existing.\nYou can enter the wallet name and GhostVault will try to load it.\n")
walletName = input(f"Please enter a wallet name or leave blank to make new: ")
if walletName != "":
print(f"Attempting to load wallet: {walletName}")
try:
rpcproxy().loadwallet(walletName)
except:
showError(f"Failed to load wallet '{walletName}'. Please ensure the wallet exists and is spelled correctly.")
print(f"Successfully loaded wallet {walletName}")
dInfo = daemonInfo()
dInfo['walletName'] = walletName
updateDaemonInfo(dInfo)
newWallet = False
else:
print("Making new wallet...")
makeWallet()
else:
clear()
print("Existing wallets detected!")
while True:
ans = input(f"Would you like to use one of these? No to make new: {Fore.GREEN}Y/{Fore.RED}n{Style.RESET_ALL} ")
if ans.lower() == 'y' or ans.lower() == '':
count = 1
clear()
for i in getWallets():
if i == "":
i = '[default wallet]'
print(f"{count}. {i}")
count += 1
while True:
walletIndex = input(f"Please enter the number of the wallet you want to use: ")
if walletIndex.isdigit() == False:
print(f"{Fore.RED}Invalid answer. Answer must be a number matching a wallet.{Style.RESET_ALL}")
elif int(walletIndex) > len(getWallets()):
print(f"{Fore.RED}Invalid answer. Answer must be a number matching a wallet.{Style.RESET_ALL}")
else:
walletName = getWallets()[int(walletIndex)-1]
break
dInfo = daemonInfo()
dInfo['walletName'] = walletName
updateDaemonInfo(dInfo)
try:
loadWallet(walletName)
except Exception as e:
pass
newWallet = False
break
elif ans.lower() == 'n':
makeWallet()
break
else:
print("Invalid answer! Please enter either 'y' or 'n'")
if newWallet == False and len(getKeysAvailable()) > 0:
keys = getKeysAvailable()
print(f"Extended public keys detected.")
while True:
ans = input(f"Would you like to use an existing key? No to make new: {Fore.GREEN}Y/{Fore.RED}n{Style.RESET_ALL} ")
if ans.lower() == 'y' or ans.lower() == '':
count = 1
clear()
for i in keys:
print(f"{count}. ExtPubKey: {i['key'][0:24]} Label: {i['label']}")
count += 1
while True:
keyIndex = input(f"Please enter the number of the ExtPubKey you want to use: ")
if keyIndex.isdigit() == False:
print(f"{Fore.RED}Invalid answer. Answer must be a number matching a key.{Style.RESET_ALL}")
elif int(keyIndex) > len(getWallets()):
print(f"{Fore.RED}Invalid answer. Answer must be a number matching a key.{Style.RESET_ALL}")
else:
extKey = keys[int(keyIndex)-1]['key']
extLabel = keys[int(keyIndex)-1]['label']
break
dInfo = daemonInfo()
dInfo['extPubKey'] = extKey
dInfo['extPubKeyLabel'] = extLabel
updateDaemonInfo(dInfo)
input(f"Your ExtPublicKey is:\n{Fore.GREEN}{extKey}{Style.RESET_ALL}\nPress Enter to continue...")
break
elif ans.lower() == 'n':
print(f"Generating new extended public key...")
makeExtKey()
break
else:
print("Invalid answer! Please enter either 'y' or 'n'")
input("Press Enter to continue...")
else:
print(f"Generating new extended public key...")
makeExtKey()
print(f"Checking for existing reward address...")
if getRewardAddressFromWallet() == None:
print(f"Reward address not found.")
print(f"The reward address is where block rewards will be sent. Must be a valid public Ghost address")
makeRewardAddress()
else:
print(f"Reward address found.")
while True:
ans = input(f"Would you like to continue using {getRewardAddressFromWallet()} as your reward address? {Fore.GREEN}Y/{Fore.RED}n{Style.RESET_ALL} ")
if ans.lower() == 'y' or ans.lower() == '':
dInfo = daemonInfo()
dInfo['rewardAddress'] = getRewardAddressFromWallet()
updateDaemonInfo(dInfo)
print(f"Reward address successfully updated.")
break
elif ans.lower() == 'n':
makeRewardAddress()
break
else:
print("Invalid answer! Please enter either 'y' or 'n'")
input("Press Enter to continue...")
if system != 'Windows':
cronFound = False
cronBoot = False
cmd = f"cd {os.path.expanduser('~/GhostVault/')} && {shutil.which('python3')} ghostVault.py update"
cmdBoot = f"cd {os.path.expanduser('~/GhostVault/')} && {shutil.which('python3')} ghostVault.py start"
print("Setting up cron job...")
cron = CronTab(user=True)
for job in cron:
if cmd in str(job):
print(f"Update cron found, skipping")
cronFound = True
elif cmdBoot in str(job):
print(f"Start on boot cron found, skipping")
cronBoot = True
if cronFound == False:
try:
job3 = cron.new(command=cmd)
job3.minute.on(0)
job3.hour.every(2)
cron.write()
print("Update cron successfully set.\n")
except Exception as e:
showError(e)
if cronBoot == False:
try:
job4 = cron.new(command=cmdBoot)
job4.every_reboot()
cron.write()
print("Start on boot cron successfully set.\n")
except Exception as e:
showError(e)
elif system == 'Windows':
createBatchFiles()
print(f"Setting up Windows Tasks...")
try:
subprocess.call(f'{shutil.which("schtasks")} /create /sc hourly /mo 2 /tn "GhostVault Updater" /tr "{os.path.expanduser("~")}\\GhostVault\\vaultUpdate.bat"')
print(f"Update task successfully set.\n")
except Exception as e:
showError(e)
shutil.copy('vaultStart.bat', f"{os.path.expanduser('~')}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\")
print(f"Startup task successfully set.\n")
print(f"Quick start success!")
dInfo = daemonInfo()
dInfo['firstRun'] = False
updateDaemonInfo(dInfo)
def makeExtKey():
while True:
keyLabel = input(f"Please enter a label for your new extended public key: ")
if len(keyLabel) == 0:
pass
else:
break
extKey = getNewExtAddr(keyLabel)
print(f"Deriving keys...")
rpcproxy().deriverangekeys(0, 999, extKey, False, True, True)
dInfo = daemonInfo()
dInfo['extPubKey'] = extKey
dInfo['extPubKeyLabel'] = keyLabel
updateDaemonInfo(dInfo)
input(f"Your extPublicKey is:\n{Fore.GREEN}{extKey}{Style.RESET_ALL}\nPress Enter to continue...")
def makeWallet():
while True:
walletName = input(f"Please enter a name for your wallet: ")
if len(walletName) == 0:
pass
else:
break
dInfo = daemonInfo()
dInfo['walletName'] = walletName
createWallet(walletName)
try:
loadWallet(walletName)
except:
pass
updateDaemonInfo(dInfo)
words = mnemonic()
clear()
print(f"Your mnemonic recovery words are:\n")
print(textwrap.fill(f"{Fore.GREEN}{words}{Style.RESET_ALL}", 80))
input(f"\nPlease write down or copy these words, in order, and store them in a safe place.\nThese are your recovery words, needed to recover a corrupted wallet.\nPress Enter to continue.")
importKey(words)
def getLoad():
if system == "Windows":
load1, load5, load15 = psutil.getloadavg()
else:
load1, load5, load15 = os.getloadavg()
return [load1, load5, load15]
def uptime():
return time.time() - psutil.boot_time()
def isUpToDate():
with open("links.json") as f:
dvers = json.loads(f.read())
if dvers['version'] != getNetworkInfo()['subversion'].split(':')[1].replace('/', ''):
return False
else:
return True
def private():
if daemonInfo()['firstRun'] == True:
showError(f"You must run 'ghostVault.py quickstart' fisrt.")
if daemonInfo()['anonMode'] == True:
print(f"ANON mode is {Fore.GREEN}Active!{Style.RESET_ALL}\n\n")
print(f"You can run '{Fore.CYAN}ghostVault.py setrewardaddress{Style.RESET_ALL}' to disable this mode.")
else:
print(f"ANON mode is {Fore.RED}NOT Active!{Style.RESET_ALL}\n\n")
while True:
print(f"Press Enter to quit or type '{Fore.CYAN}private{Style.RESET_ALL}' to continue with")
ans = input(f"ANON mode setup. ")
if ans == "private":
privateSetup()
break
elif ans == "":
break
else:
print(f"Invalid answer")
input("Press Enter to continue...")
def privateSetup():
cronPayFound = False
clear()
print(f"Welcome the the ANON Mode setup wizard.\n")
print(f"Reward Address:\n{Fore.CYAN}{daemonInfo()['rewardAddress']}{Style.RESET_ALL}\n")
if isStealthAddr(daemonInfo()['rewardAddress']) == True:
atype = "Stealth"
else:
atype = "Public"
print(f"Address Type: {atype}\n")
print(f"If you use a stealth address funds will be sent directly to it.")
print(f"If you use a public address, funds will pass through your\ncoldstaking node's internal anon wallet before being sent to your public address\n")
while True:
ans = input(f"Would you like to use this address? {Fore.GREEN}Y/{Fore.RED}n{Style.RESET_ALL} ")
if ans.lower() == 'y' or ans.lower() == '':
setAnonAddress(daemonInfo()['rewardAddress'])
break
elif ans.lower() == 'n':
makeAnonAddress()
break
else:
print("Invalid answer! Please enter either 'y' or 'n'")
input("Press Enter to continue...")
addr = getNewStealthAddr()
setRewardAddress(addr, anon=True)
if system != 'Windows':
cmdPay = f"cd {os.path.expanduser('~/GhostVault/')} && {shutil.which('python3')} ghostVault.py cronpay"
print("Setting up cron job")
cron = CronTab(user=True)
for job in cron:
if cmdPay in str(job):
print(f"cron job found, skipping")
cronPayFound = True
if cronPayFound == False:
try:
job3 = cron.new(command=cmdPay)
job3.minute.every(15)
cron.write()
print("Cron successfully set.\n")
except Exception as e:
showError(e)
elif system == 'Windows':
createBatchFiles()
print(f"Creating Windows task...")
try:
subprocess.call(f'{shutil.which("schtasks")} /create /sc minute /mo 15 /tn "GhostVault Payment Processor" /tr "{os.path.expanduser("~")}\\GhostVault\\vaultPay.bat"')
print(f"Task successfully set.\n")
except Exception as e:
showError(e)
dInfo = daemonInfo()
dInfo['anonMode'] = True
dInfo['internalAnon'] = addr
updateDaemonInfo(dInfo)
print(f"ANON mode successfully activated!")
def cronPayment():
if daemonInfo()['anonRewardAddress'] == "" or validateAddress(daemonInfo()['anonRewardAddress']) == False:
return
balance = getBalances()['mine']['trusted']
if isStealthAddr(daemonInfo()['anonRewardAddress']) == True:
payee = daemonInfo()['anonRewardAddress']
ptype = "ext anon"
else:
payee = daemonInfo()['internalAnon']
ptype = "int anon"
if balance >= 0.1:
try:
txid = rpcproxy().sendtypeto("ghost", "anon", [{"address": payee, "amount": balance, "subfee": True}])
except Exception as e: