forked from revoxhere/duino-coin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PC_Miner.py
1486 lines (1297 loc) · 60.1 KB
/
PC_Miner.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
"""
Duino-Coin Official PC Miner 4.2 © MIT licensed
https://duinocoin.com
https://github.com/revoxhere/duino-coin
Duino-Coin Team & Community 2019-2024
"""
from time import time, sleep, strptime, ctime, time_ns
from hashlib import sha1
from socket import socket
from multiprocessing import cpu_count, current_process
from multiprocessing import Process, Manager, Semaphore
from threading import Thread
from datetime import datetime
from random import randint
from os import execl, mkdir, _exit
from os import name as osname
from os import system as ossystem
from subprocess import DEVNULL, Popen, check_call, PIPE
import pip
import sys
import base64 as b64
import os
import json
import zipfile
import traceback
import urllib.parse
from pathlib import Path
from re import sub
from random import choice
from platform import machine as osprocessor
from platform import python_version_tuple
from platform import python_version
from signal import SIGINT, signal
from locale import getdefaultlocale
from configparser import ConfigParser
import io
running_on_rpi = False
configparser = ConfigParser()
# Python <3.5 check
f"Your Python version is too old. Duino-Coin Miner requires version 3.6 or above. Update your packages and try again"
def handler(signal_received, frame):
"""
Nicely handle CTRL+C exit
"""
if current_process().name == "MainProcess":
pretty_print(
get_string("sigint_detected")
+ Style.NORMAL
+ Fore.RESET
+ get_string("goodbye"),
"warning")
if not "raspi_leds" in user_settings:
user_settings["raspi_leds"] = "y"
if running_on_rpi and user_settings["raspi_leds"] == "y":
# Reset onboard status LEDs
os.system(
'echo mmc0 | sudo tee /sys/class/leds/led0/trigger >/dev/null 2>&1')
os.system(
'echo 1 | sudo tee /sys/class/leds/led1/brightness >/dev/null 2>&1')
if sys.platform == "win32":
_exit(0)
else:
Popen("kill $(ps aux | grep PC_Miner | awk '{print $2}')",
shell=True, stdout=PIPE)
def install(package):
"""
Automatically installs python pip package and restarts the program
"""
try:
pip.main(["install", package])
except AttributeError:
check_call([sys.executable, '-m', 'pip', 'install', package])
execl(sys.executable, sys.executable, *sys.argv)
try:
import requests
except ModuleNotFoundError:
print("Requests is not installed. "
+ "Miner will try to automatically install it "
+ "If it fails, please manually execute "
+ "python3 -m pip install requests")
install("requests")
try:
from colorama import Back, Fore, Style, init
init(autoreset=True)
except ModuleNotFoundError:
print("Colorama is not installed. "
+ "Miner will try to automatically install it "
+ "If it fails, please manually execute "
+ "python3 -m pip install colorama")
install("colorama")
try:
import cpuinfo
except ModuleNotFoundError:
print("Cpuinfo is not installed. "
+ "Miner will try to automatically install it "
+ "If it fails, please manually execute "
+ "python3 -m pip install py-cpuinfo")
install("py-cpuinfo")
try:
import psutil
except ModuleNotFoundError:
print("Psutil is not installed. "
+ "Miner will try to automatically install it "
+ "If it fails, please manually execute "
+ "python3 -m pip install psutil")
install("psutil")
try:
from pypresence import Presence
except ModuleNotFoundError:
print("Pypresence is not installed. "
+ "Miner will try to automatically install it "
+ "If it fails, please manually execute "
+ "python3 -m pip install pypresence")
install("pypresence")
class Settings:
"""
Class containing default miner and server settings
"""
ENCODING = "UTF8"
SEPARATOR = ","
VER = 4.2
DATA_DIR = "Duino-Coin PC Miner " + str(VER)
TRANSLATIONS = ("https://raw.githubusercontent.com/"
+ "revoxhere/"
+ "duino-coin/master/Resources/"
+ "PC_Miner_langs.json")
TRANSLATIONS_FILE = "/Translations.json"
SETTINGS_FILE = "/Settings.cfg"
TEMP_FOLDER = "Temp"
SOC_TIMEOUT = 20
REPORT_TIME = 5*60
DONATE_LVL = 0
RASPI_LEDS = "y"
RASPI_CPU_IOT = "y"
try:
# Raspberry Pi latin encoding users can't display this character
BLOCK = " ‖ "
"‖".encode(sys.stdout.encoding)
except:
BLOCK = " | "
PICK = ""
COG = " @"
if (os.name != "nt"
or bool(os.name == "nt"
and os.environ.get("WT_SESSION"))):
# Windows' cmd does not support emojis, shame!
# Same for different encodinsg, for example the latin encoding doesn't support them
try:
"⛏ ⚙".encode(sys.stdout.encoding) # if the terminal support emoji
PICK = " ⛏"
COG = " ⚙"
except UnicodeEncodeError: # else
PICK = ""
COG = " @"
def title(title: str):
if osname == 'nt':
"""
Changing the title in Windows' cmd
is easy - just use the built-in
title command
"""
ossystem('title ' + title)
else:
"""
Most *nix terminals use
this escape sequence to change
the console window title
"""
try:
print('\33]0;' + title + '\a', end='')
sys.stdout.flush()
except Exception as e:
debug_output("Error setting title: " +str(e))
def check_updates():
"""
Function that checks if the miner is updated.
Downloads the new version and restarts the miner.
"""
try:
data = requests.get(
"https://api.github.com/repos/revoxhere/duino-coin/releases/latest"
).json()
zip_file = "Duino-Coin_" + data["tag_name"] + "_linux.zip"
if sys.platform == "win32":
zip_file = "Duino-Coin_" + data["tag_name"] + "_windows.zip"
process = psutil.Process(os.getpid())
running_script = False # If the process is from script
if "python" in process.name():
running_script = True
if float(Settings.VER) < float(data["tag_name"]): # If is outdated
update = input(Style.BRIGHT + get_string("new_version"))
if update.lower() == "y" or update == "":
pretty_print(get_string("updating"), "warning", "sys0")
DATA_DIR = "Duino-Coin PC Miner " + str(data["tag_name"]) # Create new version config folder
if not Path(DATA_DIR).is_dir():
mkdir(DATA_DIR)
try:
configparser.read(str(Settings.DATA_DIR) + '/Settings.cfg') # read the previous config
configparser["PC Miner"] = {
"username": configparser["PC Miner"]["username"],
"mining_key": configparser["PC Miner"]["mining_key"],
"intensity": configparser["PC Miner"]["intensity"],
"threads": configparser["PC Miner"]["threads"],
"start_diff": configparser["PC Miner"]["start_diff"],
"donate": int(configparser["PC Miner"]["donate"]),
"identifier": configparser["PC Miner"]["identifier"],
"algorithm": configparser["PC Miner"]["algorithm"],
"language": configparser["PC Miner"]["language"],
"soc_timeout": int(configparser["PC Miner"]["soc_timeout"]),
"report_sec": int(configparser["PC Miner"]["report_sec"]),
"discord_rp": configparser["PC Miner"]["discord_rp"]
}
with open(str(DATA_DIR) # save it on the new version folder
+ '/Settings.cfg', 'w') as configfile:
configparser.write(configfile)
pretty_print(Style.RESET_ALL + get_string('config_saved'),
"success", "sys0")
except Exception as e:
pretty_print(f"Error saving configfile: {e}" + str(e),
"error", "sys0")
pretty_print("Config won't be carried to the next version",
"warning", "sys0")
if not os.path.exists(Settings.TEMP_FOLDER): # Make the Temp folder
os.makedirs(Settings.TEMP_FOLDER)
file_path = os.path.join(Settings.TEMP_FOLDER, zip_file)
download_url = "https://github.com/revoxhere/duino-coin/releases/download/" + data["tag_name"] + "/" + zip_file
if running_script:
file_path = os.path.join(".", "PC_Miner_"+data["tag_name"]+".py")
download_url = "https://raw.githubusercontent.com/revoxhere/duino-coin/master/PC_Miner.py"
r = requests.get(download_url, stream=True)
if r.ok:
start = time()
dl = 0
file_size = int(r.headers["Content-Length"]) # Get file size
pretty_print(f"Saving update to: {os.path.abspath(file_path)}",
"warning", "sys0")
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024 * 8): # Download file in chunks
if chunk:
dl += len(chunk)
done = int(50 * dl / file_size)
dl_perc = str(int(100 * dl / file_size))
if running_script:
done = int(12.5 * dl / file_size)
dl_perc = str(int(22.5 * dl / file_size))
sys.stdout.write(
"\r%s [%s%s] %s %s" % (
dl_perc + "%",
'#' * done,
' ' * (50-done),
str(round(os.path.getsize(file_path) / 1024 / 1024, 2)) + " MB ",
str((dl // (time() - start)) // 1024) + " KB/s")) # ProgressBar
sys.stdout.flush()
f.write(chunk)
f.flush()
os.fsync(f.fileno())
pretty_print("Download complete", "success", "sys0")
if not running_script:
pretty_print("Unpacking archive", "warning", "sys0")
with zipfile.ZipFile(file_path, 'r') as zip_ref: # Unzip the file
for file in zip_ref.infolist():
if "PC_Miner" in file.filename:
if sys.platform == "win32":
file.filename = "PC_Miner_"+data["tag_name"]+".exe" # Rename the file
else:
file.filename = "PC_Miner_"+data["tag_name"]
zip_ref.extract(file, ".")
pretty_print("Unpacking complete", "success", "sys0")
os.remove(file_path) # Delete the zip file
os.rmdir(Settings.TEMP_FOLDER) # Delete the temp folder
if sys.platform == "win32":
os.startfile(os.getcwd() + "\\PC_Miner_"+data["tag_name"]+".exe") # Start the miner
else: # os.startfile is only for windows
os.system(os.getcwd() + "/PC_Miner_"+data["tag_name"])
else:
if sys.platform == "win32":
os.system(file_path)
else:
os.system("python3 " + file_path)
sys.exit() # Exit the program
else: # HTTP status code 4XX/5XX
pretty_print(f"Update failed: {r.status_code}: {r.text}",
"error", "sys0")
else:
pretty_print("Update aborted", "warning", "sys0")
except Exception as e:
print(e)
class Algorithms:
"""
Class containing algorithms used by the miner
For more info about the implementation refer to the Duino whitepaper:
https://github.com/revoxhere/duino-coin/blob/gh-pages/assets/whitepaper.pdf
"""
def DUCOS1(last_h: str, exp_h: str, diff: int, eff: int):
try:
import libducohasher
fasthash_supported = True
except:
fasthash_supported = False
if fasthash_supported:
time_start = time_ns()
hasher = libducohasher.DUCOHasher(bytes(last_h, encoding='ascii'))
nonce = hasher.DUCOS1(
bytes(bytearray.fromhex(exp_h)), diff, int(eff))
time_elapsed = time_ns() - time_start
if time_elapsed > 0:
hashrate = 1e9 * nonce / time_elapsed
else:
return [nonce,0]
return [nonce, hashrate]
else:
time_start = time_ns()
base_hash = sha1(last_h.encode('ascii'))
for nonce in range(100 * diff + 1):
temp_h = base_hash.copy()
temp_h.update(str(nonce).encode('ascii'))
d_res = temp_h.hexdigest()
if eff != 0:
if nonce % 5000 == 0:
sleep(eff / 100)
if d_res == exp_h:
time_elapsed = time_ns() - time_start
if time_elapsed > 0:
hashrate = 1e9 * nonce / time_elapsed
else:
return [nonce,0]
return [nonce, hashrate]
return [0, 0]
class Client:
"""
Class helping to organize socket connections
"""
def connect(pool: tuple):
global s
s = socket()
s.settimeout(Settings.SOC_TIMEOUT)
s.connect((pool))
def send(msg: str):
sent = s.sendall(str(msg).encode(Settings.ENCODING))
return sent
def recv(limit: int = 128):
data = s.recv(limit).decode(Settings.ENCODING).rstrip("\n")
return data
def fetch_pool(retry_count=1):
"""
Fetches the best pool from the /getPool API endpoint
"""
while True:
if retry_count > 60:
retry_count = 60
try:
pretty_print(get_string("connection_search"),
"info", "net0")
response = requests.get(
"https://server.duinocoin.com/getPool",
timeout=Settings.SOC_TIMEOUT).json()
if response["success"] == True:
pretty_print(get_string("connecting_node")
+ response["name"],
"info", "net0")
NODE_ADDRESS = response["ip"]
NODE_PORT = response["port"]
return (NODE_ADDRESS, NODE_PORT)
elif "message" in response:
pretty_print(f"Warning: {response['message']}")
+ (f", retrying in {retry_count*2}s",
"warning", "net0")
else:
raise Exception("no response - IP ban or connection error")
except Exception as e:
if "Expecting value" in str(e):
pretty_print(get_string("node_picker_unavailable")
+ f"{retry_count*2}s {Style.RESET_ALL}({e})",
"warning", "net0")
else:
pretty_print(get_string("node_picker_error")
+ f"{retry_count*2}s {Style.RESET_ALL}({e})",
"error", "net0")
sleep(retry_count * 2)
retry_count += 1
class Donate:
def load(donation_level):
if donation_level > 0:
if os.name == 'nt':
if not Path(
f"{Settings.DATA_DIR}/Donate.exe").is_file():
url = ('https://server.duinocoin.com/'
+ 'donations/DonateExecutableWindows.exe')
r = requests.get(url, timeout=Settings.SOC_TIMEOUT)
with open(f"{Settings.DATA_DIR}/Donate.exe",
'wb') as f:
f.write(r.content)
return
elif os.name == "posix":
if osprocessor() == "aarch64":
url = ('https://server.duinocoin.com/'
+ 'donations/DonateExecutableAARCH64')
elif osprocessor() == "armv7l":
url = ('https://server.duinocoin.com/'
+ 'donations/DonateExecutableAARCH32')
elif osprocessor() == "x86_64":
url = ('https://server.duinocoin.com/'
+ 'donations/DonateExecutableLinux')
else:
pretty_print(
"Donate executable unavailable: "
+ f"{os.name} {osprocessor()}")
return
if not Path(
f"{Settings.DATA_DIR}/Donate").is_file():
r = requests.get(url, timeout=Settings.SOC_TIMEOUT)
with open(f"{Settings.DATA_DIR}/Donate",
"wb") as f:
f.write(r.content)
return
def start(donation_level):
donation_settings = requests.get(
"https://server.duinocoin.com/donations/settings.json").json()
if os.name == 'nt':
cmd = (f'cd "{Settings.DATA_DIR}" & Donate.exe '
+ f'-o {donation_settings["url"]} '
+ f'-u {donation_settings["user"]} '
+ f'-p {donation_settings["pwd"]} '
+ f'-s 4 -e {donation_level*5}')
elif os.name == 'posix':
cmd = (f'cd "{Settings.DATA_DIR}" && chmod +x Donate '
+ '&& nice -20 ./Donate '
+ f'-o {donation_settings["url"]} '
+ f'-u {donation_settings["user"]} '
+ f'-p {donation_settings["pwd"]} '
+ f'-s 4 -e {donation_level*5}')
if donation_level <= 0:
pretty_print(
Fore.YELLOW + get_string('free_network_warning').lstrip()
+ get_string('donate_warning').replace("\n", "\n\t\t")
+ Fore.GREEN + 'https://duinocoin.com/donate'
+ Fore.YELLOW + get_string('learn_more_donate'),
'warning', 'sys0')
sleep(5)
if donation_level > 0:
donateExecutable = Popen(cmd, shell=True, stderr=DEVNULL)
pretty_print(get_string('thanks_donation').replace("\n", "\n\t\t"),
'error', 'sys0')
def get_prefix(symbol: str,
val: float,
accuracy: int):
"""
H/s, 1000 => 1 kH/s
"""
if val >= 1_000_000_000_000: # Really?
val = str(round((val / 1_000_000_000_000), accuracy)) + " T"
elif val >= 1_000_000_000:
val = str(round((val / 1_000_000_000), accuracy)) + " G"
elif val >= 1_000_000:
val = str(round((val / 1_000_000), accuracy)) + " M"
elif val >= 1_000:
val = str(round((val / 1_000))) + " k"
else:
val = str(round(val)) + " "
return val + symbol
def get_rpi_temperature():
output = Popen(args='cat /sys/class/thermal/thermal_zone0/temp',
stdout=PIPE,
shell=True).communicate()[0].decode()
return round(int(output) / 1000, 2)
def periodic_report(start_time, end_time, shares,
blocks, hashrate, uptime):
"""
Displays nicely formated uptime stats
"""
raspi_iot_reading = ""
if running_on_rpi and user_settings["raspi_cpu_iot"] == "y":
raspi_iot_reading = f"{get_string('rpi_cpu_temp')} {get_rpi_temperature()}°C"
seconds = round(end_time - start_time)
pretty_print(get_string("periodic_mining_report")
+ Fore.RESET + Style.NORMAL
+ get_string("report_period")
+ str(seconds) + get_string("report_time")
+ get_string("report_body1")
+ str(shares) + get_string("report_body2")
+ str(round(shares/seconds, 1))
+ get_string("report_body3")
+ get_string("report_body7")
+ str(blocks)
+ get_string("report_body4")
+ str(get_prefix("H/s", hashrate, 2))
+ get_string("report_body5")
+ str(int(hashrate*seconds))
+ get_string("report_body6")
+ get_string("total_mining_time")
+ str(uptime)
+ raspi_iot_reading + "\n", "success")
def calculate_uptime(start_time):
"""
Returns seconds, minutes or hours passed since timestamp
"""
uptime = time() - start_time
if uptime >= 7200: # 2 hours, plural
return str(uptime // 3600) + get_string('uptime_hours')
elif uptime >= 3600: # 1 hour, not plural
return str(uptime // 3600) + get_string('uptime_hour')
elif uptime >= 120: # 2 minutes, plural
return str(uptime // 60) + get_string('uptime_minutes')
elif uptime >= 60: # 1 minute, not plural
return str(uptime // 60) + get_string('uptime_minute')
else: # less than 1 minute
return str(round(uptime)) + get_string('uptime_seconds')
def pretty_print(msg: str = None,
state: str = "success",
sender: str = "sys0",
print_queue = None):
"""
Produces nicely formatted CLI output for messages:
HH:MM:S |sender| msg
"""
if sender.startswith("net"):
bg_color = Back.BLUE
elif sender.startswith("cpu"):
bg_color = Back.YELLOW
elif sender.startswith("sys"):
bg_color = Back.GREEN
if state == "success":
fg_color = Fore.GREEN
elif state == "info":
fg_color = Fore.BLUE
elif state == "error":
fg_color = Fore.RED
else:
fg_color = Fore.YELLOW
if print_queue != None:
print_queue.append(
Fore.WHITE + datetime.now().strftime(Style.DIM + "%H:%M:%S ")
+ Style.RESET_ALL + Style.BRIGHT + bg_color + " " + sender + " "
+ Style.NORMAL + Back.RESET + " " + fg_color + msg.strip())
else:
print(
Fore.WHITE + datetime.now().strftime(Style.DIM + "%H:%M:%S ")
+ Style.RESET_ALL + Style.BRIGHT + bg_color + " " + sender + " "
+ Style.NORMAL + Back.RESET + " " + fg_color + msg.strip())
def share_print(id, type,
accept, reject,
thread_hashrate, total_hashrate,
computetime, diff, ping,
back_color, reject_cause=None,
print_queue = None):
"""
Produces nicely formatted CLI output for shares:
HH:MM:S |cpuN| ⛏ Accepted 0/0 (100%) ∙ 0.0s ∙ 0 kH/s ⚙ diff 0 k ∙ ping 0ms
"""
thread_hashrate = get_prefix("H/s", thread_hashrate, 2)
total_hashrate = get_prefix("H/s", total_hashrate, 1)
diff = get_prefix("", int(diff), 0)
def _blink_builtin(led="green"):
if led == "green":
os.system(
'echo 1 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1')
sleep(0.1)
os.system(
'echo 0 | sudo tee /sys/class/leds/led0/brightness >/dev/null 2>&1')
else:
os.system(
'echo 1 | sudo tee /sys/class/leds/led1/brightness >/dev/null 2>&1')
sleep(0.1)
os.system(
'echo 0 | sudo tee /sys/class/leds/led1/brightness >/dev/null 2>&1')
if type == "accept":
if running_on_rpi and user_settings["raspi_leds"] == "y":
_blink_builtin()
share_str = get_string("accepted")
fg_color = Fore.GREEN
elif type == "block":
if running_on_rpi and user_settings["raspi_leds"] == "y":
_blink_builtin()
share_str = get_string("block_found")
fg_color = Fore.YELLOW
else:
if running_on_rpi and user_settings["raspi_leds"] == "y":
_blink_builtin("red")
share_str = get_string("rejected")
if reject_cause:
share_str += f"{Style.NORMAL}({reject_cause}) "
fg_color = Fore.RED
print_queue.append(Fore.WHITE + datetime.now().strftime(Style.DIM + "%H:%M:%S ")
+ Style.RESET_ALL + Fore.WHITE + Style.BRIGHT + back_color
+ f" cpu{id} " + Back.RESET + fg_color + Settings.PICK
+ share_str + Fore.RESET + f"{accept}/{(accept + reject)}"
+ Fore.YELLOW
+ f" ({(round(accept / (accept + reject) * 100))}%)"
+ Style.NORMAL + Fore.RESET
+ f" ∙ {('%04.1f' % float(computetime))}s"
+ Style.NORMAL + " ∙ " + Fore.BLUE + Style.BRIGHT
+ f"{thread_hashrate}" + Style.DIM
+ f" ({total_hashrate} {get_string('hashrate_total')})" + Fore.RESET + Style.NORMAL
+ Settings.COG + f" {get_string('diff')} {diff} ∙ " + Fore.CYAN
+ f"ping {(int(ping))}ms")
def print_queue_handler(print_queue):
"""
Prevents broken console logs with many threads
"""
while True:
if len(print_queue):
message = print_queue[0]
del print_queue[0]
print(message)
sleep(0.1)
def get_string(string_name):
"""
Gets a string from the language file
"""
if string_name in lang_file[lang]:
return lang_file[lang][string_name]
elif string_name in lang_file["english"]:
return lang_file["english"][string_name]
else:
return string_name
def has_mining_key(username):
response = requests.get(
"https://server.duinocoin.com/mining_key"
+ "?u=" + username,
timeout=10
).json()
return response["has_key"]
def check_mining_key(user_settings):
if user_settings["mining_key"] != "None":
key = '&k=' + urllib.parse.quote(b64.b64decode(user_settings["mining_key"]).decode('utf-8'))
else:
key = ''
response = requests.get(
"https://server.duinocoin.com/mining_key"
+ "?u=" + user_settings["username"]
+ key,
timeout=Settings.SOC_TIMEOUT
).json()
if response["success"] and not response["has_key"]:
# If user doesn't have a mining key
user_settings["mining_key"] = "None"
with open(Settings.DATA_DIR + Settings.SETTINGS_FILE,
"w") as configfile:
configparser.write(configfile)
print(Style.RESET_ALL + get_string("config_saved"))
sleep(1.5)
return
if not response["success"]:
if user_settings["mining_key"] == "None":
pretty_print(get_string("mining_key_required"), "warning")
mining_key = input("\t\t" + get_string("ask_mining_key")
+ Style.BRIGHT + Fore.YELLOW)
if mining_key == "": mining_key = "None" #replace empty input with "None" key
user_settings["mining_key"] = b64.b64encode(
mining_key.encode("utf-8")).decode('utf-8')
configparser["PC Miner"] = user_settings
with open(Settings.DATA_DIR + Settings.SETTINGS_FILE,
"w") as configfile:
configparser.write(configfile)
print(Style.RESET_ALL + get_string("config_saved"))
sleep(1.5)
check_mining_key(user_settings)
else:
pretty_print(get_string("invalid_mining_key"), "error")
retry = input(get_string("key_retry"))
if not retry or retry == "y" or retry == "Y":
mining_key = input(get_string("ask_mining_key"))
if mining_key == "": mining_key = "None" #replace empty input with "None" key
user_settings["mining_key"] = b64.b64encode(
mining_key.encode("utf-8")).decode('utf-8')
configparser["PC Miner"] = user_settings
with open(Settings.DATA_DIR + Settings.SETTINGS_FILE,
"w") as configfile:
configparser.write(configfile)
print(Style.RESET_ALL + get_string("config_saved"))
sleep(1.5)
check_mining_key(user_settings)
else:
return
class Miner:
def greeting():
diff_str = get_string("net_diff_short")
if user_settings["start_diff"] == "LOW":
diff_str = get_string("low_diff_short")
elif user_settings["start_diff"] == "MEDIUM":
diff_str = get_string("medium_diff_short")
current_hour = strptime(ctime(time())).tm_hour
greeting = get_string("greeting_back")
if current_hour < 12:
greeting = get_string("greeting_morning")
elif current_hour == 12:
greeting = get_string("greeting_noon")
elif current_hour > 12 and current_hour < 18:
greeting = get_string("greeting_afternoon")
elif current_hour >= 18:
greeting = get_string("greeting_evening")
print("\n" + Style.DIM + Fore.YELLOW + Settings.BLOCK + Fore.YELLOW
+ Style.BRIGHT + get_string("banner") + Style.RESET_ALL
+ Fore.MAGENTA + " (" + str(Settings.VER) + ") "
+ Fore.RESET + "2019-2024")
print(Style.DIM + Fore.YELLOW + Settings.BLOCK + Style.NORMAL
+ Fore.YELLOW + "https://github.com/revoxhere/duino-coin")
if lang != "english":
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET
+ get_string("translation") + Fore.YELLOW
+ get_string("translation_autor"))
try:
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + "CPU: " + Style.BRIGHT
+ Fore.YELLOW + str(user_settings["threads"])
+ "x " + str(cpu["brand_raw"]))
except:
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + "CPU: " + Style.BRIGHT
+ Fore.YELLOW + str(user_settings["threads"])
+ "x threads")
if os.name == "nt" or os.name == "posix":
print(Style.DIM + Fore.YELLOW
+ Settings.BLOCK + Style.NORMAL + Fore.RESET
+ get_string("donation_level") + Style.BRIGHT
+ Fore.YELLOW + str(user_settings["donate"]))
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + get_string("algorithm")
+ Style.BRIGHT + Fore.YELLOW + user_settings["algorithm"]
+ Settings.COG + " " + diff_str)
if user_settings["identifier"] != "None":
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + get_string("rig_identifier")
+ Style.BRIGHT + Fore.YELLOW + user_settings["identifier"])
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + get_string("using_config")
+ Style.BRIGHT + Fore.YELLOW
+ str(Settings.DATA_DIR + Settings.SETTINGS_FILE))
print(Style.DIM + Fore.YELLOW + Settings.BLOCK
+ Style.NORMAL + Fore.RESET + str(greeting)
+ ", " + Style.BRIGHT + Fore.YELLOW
+ str(user_settings["username"]) + "!\n")
def preload():
"""
Creates needed directories and files for the miner
"""
global lang_file
global lang
if not Path(Settings.DATA_DIR).is_dir():
mkdir(Settings.DATA_DIR)
if not Path(Settings.DATA_DIR + Settings.TRANSLATIONS_FILE).is_file():
with open(Settings.DATA_DIR + Settings.TRANSLATIONS_FILE,
"wb") as f:
f.write(requests.get(Settings.TRANSLATIONS,
timeout=Settings.SOC_TIMEOUT).content)
with open(Settings.DATA_DIR + Settings.TRANSLATIONS_FILE, "r",
encoding=Settings.ENCODING) as file:
lang_file = json.load(file)
try:
if not Path(Settings.DATA_DIR + Settings.SETTINGS_FILE).is_file():
locale = getdefaultlocale()[0]
if locale.startswith("es"):
lang = "spanish"
elif locale.startswith("pl"):
lang = "polish"
elif locale.startswith("fr"):
lang = "french"
elif locale.startswith("jp"):
lang = "japanese"
elif locale.startswith("fa"):
lang = "farsi"
elif locale.startswith("mt"):
lang = "maltese"
elif locale.startswith("ru"):
lang = "russian"
elif locale.startswith("uk"):
lang = "ukrainian"
elif locale.startswith("de"):
lang = "german"
elif locale.startswith("tr"):
lang = "turkish"
elif locale.startswith("pr"):
lang = "portuguese"
elif locale.startswith("it"):
lang = "italian"
elif locale.startswith("sk"):
lang = "slovak"
if locale.startswith("zh_TW"):
lang = "chinese_Traditional"
elif locale.startswith("zh"):
lang = "chinese_simplified"
elif locale.startswith("th"):
lang = "thai"
elif locale.startswith("ko"):
lang = "korean"
elif locale.startswith("id"):
lang = "indonesian"
elif locale.startswith("cz"):
lang = "czech"
elif locale.startswith("fi"):
lang = "finnish"
else:
lang = "english"
else:
try:
configparser.read(Settings.DATA_DIR
+ Settings.SETTINGS_FILE)
lang = configparser["PC Miner"]["language"]
except Exception:
lang = "english"
except Exception as e:
print("Error with lang file, falling back to english: " + str(e))
lang = "english"
def load_cfg():
"""
Loads miner settings file or starts the config tool
"""
if not Path(Settings.DATA_DIR + Settings.SETTINGS_FILE).is_file():
print(Style.BRIGHT
+ get_string("basic_config_tool")
+ Settings.DATA_DIR
+ get_string("edit_config_file_warning")
+ "\n"
+ Style.RESET_ALL
+ get_string("dont_have_account")
+ Fore.YELLOW
+ get_string("wallet")
+ Fore.RESET
+ get_string("register_warning"))
correct_username = False
while not correct_username:
username = input(get_string("ask_username") + Style.BRIGHT)
if not username:
username = choice(["revox", "Bilaboz"])
r = requests.get(f"https://server.duinocoin.com/users/{username}",
timeout=Settings.SOC_TIMEOUT).json()
correct_username = r["success"]
if not correct_username:
print(get_string("incorrect_username"))
mining_key = "None"
if has_mining_key(username):
mining_key = input(Style.RESET_ALL +
get_string("ask_mining_key") +
Style.BRIGHT)
mining_key = b64.b64encode(mining_key.encode("utf-8")).decode('utf-8')
algorithm = "DUCO-S1"
intensity = sub(r"\D", "",
input(Style.NORMAL +
get_string("ask_intensity") +
Style.BRIGHT))
if not intensity:
intensity = 95
elif float(intensity) > 100:
intensity = 100
elif float(intensity) < 1:
intensity = 1
threads = sub(r"\D", "",
input(Style.NORMAL + get_string("ask_threads")
+ str(cpu_count()) + "): " + Style.BRIGHT))
if not threads:
threads = cpu_count()
if int(threads) > 16:
threads = 16
print(Style.BRIGHT + Fore.BLUE
+ get_string("max_threads_notice")
+ Style.RESET_ALL)
elif int(threads) < 1:
threads = 1
print(Style.BRIGHT
+ "1" + Style.NORMAL + " - " + get_string("low_diff")
+ "\n" + Style.BRIGHT
+ "2" + Style.NORMAL + " - " + get_string("medium_diff")
+ "\n" + Style.BRIGHT
+ "3" + Style.NORMAL + " - " + get_string("net_diff"))