-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmining_controller.py
More file actions
1309 lines (1106 loc) · 51.6 KB
/
mining_controller.py
File metadata and controls
1309 lines (1106 loc) · 51.6 KB
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
import os
import json
import time
import subprocess
import threading
import signal
import sys
import queue
from pathlib import Path
import psutil
import urllib.request
import urllib.error
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
from rich.prompt import Prompt, IntPrompt, Confirm
from rich.columns import Columns
from rich.align import Align
from rich.markdown import Markdown
def get_script_dir():
"""Get the directory where the script is located"""
return Path(__file__).parent.absolute()
def load_user_settings():
"""Load user settings from file"""
settings_file = get_script_dir() / "user_settings.json"
if settings_file.exists():
try:
with open(settings_file, 'r') as f:
return json.load(f)
except:
return {}
return {}
def save_user_settings(settings):
"""Save user settings to file"""
settings_file = get_script_dir() / "user_settings.json"
try:
with open(settings_file, 'w') as f:
json.dump(settings, f, indent=2)
return True
except:
return False
class PoolSelector:
"""Handles pool selection and comparison"""
def __init__(self, pools_file=None):
if pools_file is None:
pools_file = get_script_dir() / "pools.json"
elif not Path(pools_file).is_absolute():
pools_file = get_script_dir() / pools_file
self.pools_file = str(pools_file)
self.pools = []
self.load_pools()
def load_pools(self):
"""Load pool data from JSON file"""
try:
with open(self.pools_file, 'r') as f:
data = json.load(f)
self.pools = data.get('pools', [])
self.notes = data.get('notes', {})
except FileNotFoundError:
print(f"Pools file {self.pools_file} not found!")
self.pools = []
self.notes = {}
except json.JSONDecodeError:
print(f"Invalid pools file {self.pools_file}!")
self.pools = []
self.notes = {}
def display_pool_comparison(self, console):
"""Display comparison table of available pools"""
if not self.pools:
console.print("[red]No pools available![/red]")
return
table = Table(title="Monero Mining Pool Comparison")
table.add_column("Pool Name", style="cyan", no_wrap=True)
table.add_column("Fee %", style="yellow", justify="right")
table.add_column("Min Payout", style="green", justify="right")
table.add_column("Type", style="magenta")
table.add_column("Location", style="blue")
table.add_column("Description", style="white")
for pool in self.pools:
fee = f"{pool['fee']:.1f}"
min_payout = f"{pool['min_payout']:.4f}"
recommended_marker = " ⭐" if pool.get('recommended', False) else ""
table.add_row(
pool['name'] + recommended_marker,
fee,
min_payout,
pool['type'],
pool['location'],
pool['description']
)
console.print(table)
# Show recommendations
if 'recommendations' in self.notes:
console.print("\n[bold]Recommendations:[/bold]")
recs = self.notes['recommendations']
for category, recommendation in recs.items():
console.print(f"• [cyan]{category.title()}[/cyan]: {recommendation}")
def select_pool_interactive(self, console):
"""Interactive pool selection"""
self.display_pool_comparison(console)
console.print("\n[bold]Pool Selection Options:[/bold]")
for i, pool in enumerate(self.pools, 1):
recommended = " ⭐" if pool.get('recommended', False) else ""
console.print(f"{i}. {pool['name']}{recommended}")
console.print(f"{len(self.pools) + 1}. Enter custom pool details")
while True:
try:
choice = IntPrompt.ask(
f"\nSelect a pool (1-{len(self.pools) + 1})",
default=1
)
if 1 <= choice <= len(self.pools):
selected_pool = self.pools[choice - 1]
console.print(f"[green]Selected: {selected_pool['name']}[/green]")
return selected_pool
elif choice == len(self.pools) + 1:
return self.add_custom_pool(console)
else:
console.print("[red]Invalid choice![/red]")
except KeyboardInterrupt:
return None
def add_custom_pool(self, console):
"""Add a custom pool"""
console.print("[bold]Add Custom Pool[/bold]")
name = Prompt.ask("Pool name")
url = Prompt.ask("Pool URL (without port)")
port = IntPrompt.ask("Pool port")
fee = float(Prompt.ask("Pool fee (%)", default="1.0"))
min_payout = float(Prompt.ask("Minimum payout (XMR)", default="0.1"))
custom_pool = {
"name": name,
"url": url,
"port": port,
"fee": fee,
"min_payout": min_payout,
"type": "Custom",
"location": "Custom",
"description": f"Custom pool: {name}",
"features": ["Custom configuration"],
"recommended": False
}
console.print(f"[green]Added custom pool: {name}[/green]")
return custom_pool
def get_pool_info(self, pool_name):
"""Get pool information by name"""
for pool in self.pools:
if pool['name'].lower() == pool_name.lower():
return pool
return None
class CPUController:
"""Handles CPU configuration and control"""
def __init__(self, config_file=None):
if config_file is None:
config_file = get_script_dir() / "config.json"
elif not Path(config_file).is_absolute():
config_file = get_script_dir() / config_file
self.config_file = str(config_file)
def get_cpu_info(self):
"""Get CPU information"""
return {
'physical_cores': psutil.cpu_count(logical=False),
'logical_cores': psutil.cpu_count(logical=True),
'usage_percent': psutil.cpu_percent(interval=1)
}
def update_cpu_config(self, max_threads=None, priority=None, affinity=None):
"""Update CPU configuration in XMRig config"""
try:
with open(self.config_file, 'r') as f:
config = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return False
if 'cpu' not in config:
config['cpu'] = {}
updated = False
if max_threads is not None:
# Set CPU affinity to use specific cores
if max_threads > 0:
cores_to_use = min(max_threads, psutil.cpu_count(logical=True))
affinity_str = ",".join(str(i) for i in range(cores_to_use))
config['cpu']['affinity'] = affinity_str
updated = True
if priority is not None:
# Set CPU priority (0=highest to 5=lowest)
if 0 <= priority <= 5:
config['cpu']['priority'] = priority
updated = True
if affinity is not None:
config['cpu']['affinity'] = affinity
updated = True
if updated:
try:
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=4)
return True
except Exception:
return False
return False
def get_current_config(self):
"""Get current CPU configuration"""
try:
with open(self.config_file, 'r') as f:
config = json.load(f)
return config.get('cpu', {})
except:
return {}
def display_cpu_config(self, console):
"""Display current CPU configuration"""
cpu_info = self.get_cpu_info()
current_config = self.get_current_config()
table = Table(title="CPU Configuration")
table.add_column("Setting", style="cyan")
table.add_column("Current Value", style="green")
table.add_column("Description", style="white")
table.add_row("Physical Cores", str(cpu_info['physical_cores']), "Physical CPU cores")
table.add_row("Logical Cores", str(cpu_info['logical_cores']), "Logical CPU cores (including hyperthreading)")
table.add_row("Current Usage", f"{cpu_info['usage_percent']:.1f}%", "Current CPU usage")
affinity = current_config.get('affinity', 'Auto')
if isinstance(affinity, str) and affinity != 'Auto':
affinity_cores = len(affinity.split(','))
table.add_row("Active Threads", str(affinity_cores), "Number of CPU threads allocated to mining")
else:
table.add_row("Active Threads", "Auto", "Automatic thread allocation")
priority = current_config.get('priority')
if priority is not None:
priority_desc = {
0: "Highest (most aggressive)",
1: "High",
2: "Above normal",
3: "Normal",
4: "Below normal",
5: "Lowest (most conservative)"
}.get(priority, f"Level {priority}")
table.add_row("CPU Priority", f"{priority} ({priority_desc})", "Mining process priority")
else:
table.add_row("CPU Priority", "Default", "System default priority")
console.print(table)
class MiningMonitor:
"""Handles XMRig process monitoring and statistics parsing"""
def __init__(self, xmrig_process=None):
self.xmrig_process = xmrig_process
self.start_time = time.time()
self.stats = {
'hashrate': 0.0,
'peak_hashrate': 0.0,
'shares': {'accepted': 0, 'rejected': 0},
'uptime': 0,
'start_time': time.time()
}
self.monitoring = False
self.monitor_thread = None
def start_monitoring(self, xmrig_process):
"""Start monitoring XMRig process"""
self.xmrig_process = xmrig_process
self.monitoring = True
self.start_time = time.time()
self.monitor_thread = threading.Thread(target=self._monitor_output)
self.monitor_thread.daemon = True
self.monitor_thread.start()
def stop_monitoring(self):
"""Stop monitoring"""
self.monitoring = False
if self.monitor_thread and self.monitor_thread.is_alive():
self.monitor_thread.join(timeout=2)
def _monitor_output(self):
"""Monitor XMRig stdout for statistics"""
if not self.xmrig_process:
return
import select
import os
try:
while self.monitoring and self.xmrig_process.poll() is None:
# Use select to check if data is available (non-blocking)
if hasattr(self.xmrig_process.stdout, 'fileno'):
try:
# Check if stdout has data available
ready, _, _ = select.select([self.xmrig_process.stdout], [], [], 0.1)
if ready:
line = self.xmrig_process.stdout.readline()
if line:
self._parse_xmrig_line(line.strip())
except (OSError, ValueError):
# Handle case where fileno is not available or select fails
time.sleep(0.1)
continue
else:
# Fallback for systems where select doesn't work
try:
line = self.xmrig_process.stdout.readline()
if line:
self._parse_xmrig_line(line.strip())
else:
time.sleep(0.1)
except:
time.sleep(0.1)
except Exception as e:
# Log the error but don't crash
print(f"Monitoring error: {e}")
pass
def _parse_xmrig_line(self, line):
"""Parse XMRig output line for statistics"""
line = line.lower()
# Parse hashrate (various formats)
if any(keyword in line for keyword in ['speed', 'h/s', 'hashrate']):
try:
# Look for patterns like "speed 2.5s/60s/15m H/s max"
if 'h/s' in line:
parts = line.split()
for i, part in enumerate(parts):
if 'h/s' in part:
# Get the value before h/s
rate_part = parts[i-1] if i > 0 else ""
if rate_part:
# Handle K, M, G suffixes
multiplier = 1
if rate_part.endswith('k'):
multiplier = 1000
rate_part = rate_part[:-1]
elif rate_part.endswith('m'):
multiplier = 1000000
rate_part = rate_part[:-1]
elif rate_part.endswith('g'):
multiplier = 1000000000
rate_part = rate_part[:-1]
try:
new_hashrate = float(rate_part) * multiplier
self.stats['hashrate'] = new_hashrate
# Track peak hashrate
if new_hashrate > self.stats['peak_hashrate']:
self.stats['peak_hashrate'] = new_hashrate
except ValueError:
pass
break
except:
pass
# Parse accepted shares
if 'accepted' in line and ('share' in line or 'shares' in line):
try:
# Look for patterns like "accepted (123/0) diff"
import re
match = re.search(r'accepted\s*\((\d+)/(\d+)\)', line)
if match:
accepted = int(match.group(1))
rejected = int(match.group(2))
self.stats['shares']['accepted'] = accepted
self.stats['shares']['rejected'] = rejected
except:
pass
def get_system_stats(self):
"""Get current system statistics"""
return {
'cpu_usage': psutil.cpu_percent(interval=0.1),
'memory': psutil.virtual_memory().percent,
'cpu_cores': psutil.cpu_count(logical=True),
'uptime': time.time() - self.start_time
}
def is_xmrig_running(self):
"""Check if XMRig process is still running"""
if not self.xmrig_process:
return False
return self.xmrig_process.poll() is None
def get_stats_summary(self):
"""Get formatted statistics summary"""
system_stats = self.get_system_stats()
uptime_str = self._format_uptime(system_stats['uptime'])
# Calculate acceptance rate
total_shares = self.stats['shares']['accepted'] + self.stats['shares']['rejected']
acceptance_rate = (self.stats['shares']['accepted'] / total_shares * 100) if total_shares > 0 else 0
return {
'hashrate': self.stats['hashrate'],
'peak_hashrate': self.stats['peak_hashrate'],
'accepted_shares': self.stats['shares']['accepted'],
'rejected_shares': self.stats['shares']['rejected'],
'acceptance_rate': acceptance_rate,
'cpu_usage': system_stats['cpu_usage'],
'memory_usage': system_stats['memory'],
'uptime': uptime_str,
'cpu_cores': system_stats['cpu_cores'],
'status': 'Running' if self.is_xmrig_running() else 'Stopped'
}
def _format_uptime(self, seconds):
"""Format uptime in human readable format"""
hours, remainder = divmod(int(seconds), 3600)
minutes, seconds = divmod(remainder, 60)
if hours > 0:
return f"{hours}h {minutes}m {seconds}s"
elif minutes > 0:
return f"{minutes}m {seconds}s"
else:
return f"{seconds}s"
class XMRigController:
"""Main controller for XMRig process management"""
def __init__(self, xmrig_path=None, config_path=None):
script_dir = get_script_dir()
if xmrig_path is None:
xmrig_path = script_dir / "xmrig"
elif not Path(xmrig_path).is_absolute():
xmrig_path = script_dir / xmrig_path
self.xmrig_path = str(xmrig_path)
if config_path is None:
config_path = script_dir / "config.json"
elif not Path(config_path).is_absolute():
config_path = script_dir / config_path
self.config_path = str(config_path)
self.xmrig_process = None
self.monitor = MiningMonitor()
def load_config(self):
"""Load XMRig configuration"""
try:
with open(self.config_path, 'r') as f:
return json.load(f)
except FileNotFoundError:
print(f"Config file not found: {self.config_path}")
return None
except json.JSONDecodeError:
print(f"Invalid config file: {self.config_path}")
return None
def save_config(self, config):
"""Save XMRig configuration"""
try:
with open(self.config_path, 'w') as f:
json.dump(config, f, indent=4)
return True
except Exception as e:
print(f"Error saving config: {e}")
return False
def update_pool_config(self, pool_info, wallet_address, tls_enabled=False):
"""Update pool configuration in XMRig config"""
config = self.load_config()
if not config:
return False
if 'pools' not in config or not config['pools']:
config['pools'] = [{}]
pool_config = config['pools'][0]
pool_config.update({
'coin': 'monero',
'url': f"{pool_info['url']}:{pool_info['port']}",
'user': wallet_address,
'pass': 'x',
'tls': tls_enabled,
'keepalive': True,
'nicehash': False
})
return self.save_config(config)
def start_mining(self):
"""Start XMRig mining process"""
if self.monitor.is_xmrig_running():
return False, "XMRig is already running"
try:
# Check if XMRig executable exists and is executable
if not os.path.exists(self.xmrig_path):
return False, f"XMRig executable not found: {self.xmrig_path}"
if not os.access(self.xmrig_path, os.X_OK):
return False, f"XMRig executable not executable: {self.xmrig_path}"
# Start XMRig process with proper pipe handling
self.xmrig_process = subprocess.Popen(
[self.xmrig_path, "-c", self.config_path],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True,
# Prevent blocking on pipes
stdin=subprocess.DEVNULL,
# Add environment and working directory
cwd=os.path.dirname(self.xmrig_path) if os.path.dirname(self.xmrig_path) else None
)
# Wait up to 3 seconds for process to start properly
start_time = time.time()
while time.time() - start_time < 3.0:
if self.xmrig_process.poll() is None:
# Process is running, start monitoring
self.monitor.start_monitoring(self.xmrig_process)
return True, "XMRig started successfully"
time.sleep(0.1)
# Process didn't start within timeout
if self.xmrig_process.poll() is not None:
return_code = self.xmrig_process.returncode
return False, f"XMRig failed to start (exit code: {return_code})"
else:
# Process started but took too long to respond
self.monitor.start_monitoring(self.xmrig_process)
return True, "XMRig started (initializing...)"
except Exception as e:
return False, f"Failed to start XMRig: {e}"
def stop_mining(self):
"""Stop XMRig mining process"""
if not self.monitor.is_xmrig_running():
return False, "XMRig is not running"
try:
if self.xmrig_process:
self.xmrig_process.terminate()
self.xmrig_process.wait(timeout=5)
self.monitor.stop_monitoring()
return True, "XMRig stopped"
except subprocess.TimeoutExpired:
self.xmrig_process.kill()
self.monitor.stop_monitoring()
return True, "XMRig force killed"
except Exception as e:
return False, f"Error stopping XMRig: {e}"
def restart_mining(self):
"""Restart XMRig with new configuration"""
success, message = self.stop_mining()
if not success:
return False, message
time.sleep(1) # Brief pause
return self.start_mining()
class MiningUI:
"""Main terminal user interface"""
def __init__(self):
self.console = Console()
self.pool_selector = PoolSelector()
self.cpu_controller = CPUController()
self.xmrig_controller = XMRigController()
self.monitor = self.xmrig_controller.monitor
self.running = True
# Load saved settings
settings = load_user_settings()
self.selected_pool = settings.get('selected_pool')
self.wallet_address = settings.get('wallet_address')
def _get_performance_level(self, hashrate):
"""Determine performance level based on hashrate"""
if hashrate <= 0:
return "stopped", "dim", ""
elif hashrate < 1000: # < 1 KH/s
return "slow", "yellow", "🐌"
elif hashrate < 10000: # < 10 KH/s
return "good", "green", "👍"
elif hashrate < 100000: # < 100 KH/s
return "fast", "bright_green", "🚀"
elif hashrate < 1000000: # < 1 MH/s
return "blazing", "bold bright_green", "🔥"
else: # >= 1 MH/s
return "legendary", "bold bright_cyan", "⚡💎"
def _format_hashrate(self, hashrate):
"""Format hashrate with appropriate units and visual styling"""
if hashrate <= 0:
return Text("N/A", style="dim")
level, style, emoji = self._get_performance_level(hashrate)
# Format with appropriate units
if hashrate >= 1000000: # MH/s
value = hashrate / 1000000
unit = "MH/s"
elif hashrate >= 1000: # KH/s
value = hashrate / 1000
unit = "KH/s"
else: # H/s
value = hashrate
unit = "H/s"
# Create styled text
text = Text()
text.append(f"{value:.1f} {unit}", style=style)
# Add celebration for high performance
if level in ["blazing", "legendary"]:
text.append(f" {emoji}", style="bold yellow")
if level == "legendary":
text.append(" LEGENDARY!", style="bold bright_magenta")
elif level == "fast":
text.append(f" {emoji}", style="bright_green")
return text
def _get_status_style(self, status):
"""Get styled text for mining status"""
if status == "Running":
return Text("▶️ Running", style="bold bright_green")
elif status == "Stopped":
return Text("⏹️ Stopped", style="bold red")
elif status == "Starting":
return Text("⏳ Starting", style="bold yellow")
else:
return Text(status, style="white")
def create_stats_panel(self):
"""Create statistics display panel"""
stats = self.monitor.get_stats_summary()
table = Table(title="Mining Statistics")
table.add_column("Metric", style="cyan")
table.add_column("Value")
# Enhanced status display
status_text = self._get_status_style(stats['status'])
table.add_row("Status", status_text)
# Enhanced hashrate display with fun formatting
hashrate_text = self._format_hashrate(stats['hashrate'])
table.add_row("Hashrate", hashrate_text)
# Peak hashrate display
if stats['peak_hashrate'] > 0:
peak_text = self._format_hashrate(stats['peak_hashrate'])
peak_text.append(" (Peak)", style="dim")
table.add_row("Peak Hashrate", peak_text)
table.add_row("Accepted Shares", Text(str(stats['accepted_shares']), style="green"))
table.add_row("Rejected Shares", Text(str(stats['rejected_shares']), style="red"))
# Acceptance rate
acceptance_rate = stats.get('acceptance_rate', 0)
acceptance_style = "green" if acceptance_rate >= 95 else "yellow" if acceptance_rate >= 90 else "red"
table.add_row("Acceptance Rate", Text(f"{acceptance_rate:.1f}%", style=acceptance_style))
# CPU usage with color coding
cpu_style = "green" if stats['cpu_usage'] < 70 else "yellow" if stats['cpu_usage'] < 90 else "red"
table.add_row("CPU Usage", Text(f"{stats['cpu_usage']:.1f}%", style=cpu_style))
# Memory usage with color coding
mem_style = "green" if stats['memory_usage'] < 70 else "yellow" if stats['memory_usage'] < 90 else "red"
table.add_row("Memory Usage", Text(f"{stats['memory_usage']:.1f}%", style=mem_style))
table.add_row("Uptime", Text(stats['uptime'], style="cyan"))
return Panel(table, title="Statistics", border_style="blue")
def create_menu_panel(self):
"""Create control menu panel"""
menu_text = Text()
menu_text.append("Control Menu:\n\n", style="bold blue")
if not self.selected_pool:
menu_text.append("1. Select Mining Pool\n", style="yellow")
else:
menu_text.append(f"1. Change Mining Pool (Current: {self.selected_pool['name']})\n", style="green")
if not self.wallet_address:
menu_text.append("2. Set Wallet Address\n", style="yellow")
else:
menu_text.append("2. Change Wallet Address\n", style="green")
menu_text.append("3. Configure CPU Usage\n", style="cyan")
menu_text.append("4. Start Mining\n", style="green")
menu_text.append("5. Stop Mining\n", style="red")
menu_text.append("6. Restart with New Settings\n", style="magenta")
menu_text.append("7. View Current Configuration\n", style="white")
menu_text.append("8. View Pool Comparison\n", style="white")
menu_text.append("9. View XMRig Logs\n", style="white")
menu_text.append("10. Check Mining Status\n", style="white")
menu_text.append("11. Troubleshoot Connection\n", style="white")
menu_text.append("12. Reset Settings\n", style="yellow")
menu_text.append("13. Check Earnings\n", style="bold green")
menu_text.append("0. Exit\n", style="red")
return Panel(menu_text, title="Menu", border_style="green")
def _display_ui(self):
"""Display the current UI state"""
self.console.clear()
self.console.print("[bold blue]🚀 Monero Mining Controller[/bold blue]")
self.console.print("[dim]Control your XMRig mining with dynamic CPU allocation[/dim]\n")
# Show welcome message if settings are configured
if self.selected_pool and self.wallet_address:
self.console.print(f"[green]✅ Ready to mine![/green] Pool: {self.selected_pool['name']} | Wallet: {self.wallet_address[:10]}...")
self.console.print("[dim]Press 4 to start mining immediately[/dim]\n")
# Create layout
stats_panel = self.create_stats_panel()
menu_panel = self.create_menu_panel()
layout = Columns([stats_panel, menu_panel], equal=True)
self.console.print(Align.center(layout))
self.console.print() # Add a blank line before prompt
def handle_menu_choice(self, choice):
"""Handle menu selection"""
if choice == "1":
old_pool = self.selected_pool
self.selected_pool = self.pool_selector.select_pool_interactive(self.console)
if self.selected_pool:
self.console.print(f"[green]Pool selected: {self.selected_pool['name']}[/green]")
# Save setting if it changed
if self.selected_pool != old_pool:
settings = load_user_settings()
settings['selected_pool'] = self.selected_pool
save_user_settings(settings)
elif choice == "2":
self._set_wallet_address()
elif choice == "3":
self._configure_cpu()
elif choice == "4":
if not self.selected_pool:
self.console.print("[red]Please select a mining pool first![/red]")
time.sleep(2) # Brief pause to show message
return
if not self.wallet_address:
self.console.print("[red]Please set your wallet address first![/red]")
time.sleep(2) # Brief pause to show message
return
# Update config with pool and wallet
if self.xmrig_controller.update_pool_config(self.selected_pool, self.wallet_address, tls_enabled=False):
self.console.print("[yellow]Starting XMRig...[/yellow]")
success, message = self.xmrig_controller.start_mining()
if success:
self.console.print(f"[green]{message}[/green]")
self.console.print("[dim]Check the stats panel for mining status and hashrate[/dim]")
else:
self.console.print(f"[red]{message}[/red]")
self.console.print("[yellow]Check the XMRig logs for more details (option 9)[/yellow]")
else:
self.console.print("[red]Failed to update configuration[/red]")
time.sleep(3) # Longer pause to show message
elif choice == "5":
success, message = self.xmrig_controller.stop_mining()
if success:
self.console.print(f"[yellow]{message}[/yellow]")
else:
self.console.print(f"[red]{message}[/red]")
time.sleep(2) # Brief pause to show message
elif choice == "6":
if not self.selected_pool or not self.wallet_address:
self.console.print("[red]Please select pool and set wallet address first![/red]")
time.sleep(2) # Brief pause to show message
return
if self.xmrig_controller.update_pool_config(self.selected_pool, self.wallet_address, tls_enabled=False):
success, message = self.xmrig_controller.restart_mining()
if success:
self.console.print(f"[green]{message}[/green]")
else:
self.console.print(f"[red]{message}[/red]")
else:
self.console.print("[red]Failed to update configuration[/red]")
time.sleep(2) # Brief pause to show message
elif choice == "7":
self._view_configuration()
time.sleep(3) # Longer pause for configuration viewing
elif choice == "8":
self.pool_selector.display_pool_comparison(self.console)
time.sleep(3) # Longer pause for pool comparison viewing
elif choice == "9":
self._view_xmrig_logs()
elif choice == "10":
self._check_mining_status()
elif choice == "11":
self._troubleshoot_connection()
elif choice == "12":
self._reset_settings()
elif choice == "13":
self._check_earnings()
elif choice == "0":
self.xmrig_controller.stop_mining()
self.running = False
else:
self.console.print("[red]Invalid choice![/red]")
time.sleep(2) # Brief pause for error message
def _set_wallet_address(self):
"""Set wallet address"""
while True:
wallet = Prompt.ask("Enter your Monero wallet address")
if wallet and len(wallet) > 50: # Basic validation
old_wallet = self.wallet_address
self.wallet_address = wallet
self.console.print("[green]Wallet address set![/green]")
# Save setting if it changed
if self.wallet_address != old_wallet:
settings = load_user_settings()
settings['wallet_address'] = self.wallet_address
save_user_settings(settings)
break
else:
self.console.print("[red]Invalid wallet address. Please try again.[/red]")
def _configure_cpu(self):
"""Configure CPU usage"""
cpu_info = self.cpu_controller.get_cpu_info()
max_cores = cpu_info['logical_cores']
self.cpu_controller.display_cpu_config(self.console)
self.console.print(f"\n[bold]CPU Configuration:[/bold]")
self.console.print(f"Available cores: {max_cores}")
# Configure threads
threads = IntPrompt.ask(
f"Number of CPU threads to use (1-{max_cores})",
default=min(4, max_cores)
)
if 1 <= threads <= max_cores:
# Configure priority
priority = IntPrompt.ask(
"CPU priority (0=highest, 5=lowest)",
default=3
)
if 0 <= priority <= 5:
if self.cpu_controller.update_cpu_config(max_threads=threads, priority=priority):
self.console.print(f"[green]CPU configured: {threads} threads, priority {priority}[/green]")
else:
self.console.print("[red]Failed to update CPU configuration[/red]")
else:
self.console.print("[red]Invalid priority level[/red]")
else:
self.console.print("[red]Invalid thread count[/red]")
def _view_configuration(self):
"""View current configuration"""
config = self.xmrig_controller.load_config()
if config:
self.console.print("[bold]Current Configuration:[/bold]")
self.console.print_json(json.dumps(config, indent=2))
else:
self.console.print("[red]Could not load configuration[/red]")
def _view_xmrig_logs(self):
"""View XMRig log file contents"""
log_file = get_script_dir() / "xmrig.log"
if not log_file.exists():
self.console.print("[yellow]No XMRig log file found. Start mining first to generate logs.[/yellow]")
self.console.print(f"[dim]Expected location: {log_file}[/dim]")
time.sleep(2)
return
try:
with open(log_file, 'r') as f:
content = f.read()
if not content.strip():
self.console.print("[yellow]Log file is empty. Start mining to generate log entries.[/yellow]")
else:
self.console.print("[bold]XMRig Logs:[/bold]")
self.console.print("[dim]" + "="*50 + "[/dim]")
self.console.print(content[-2000:]) # Show last 2000 characters to avoid overwhelming output
self.console.print("[dim]" + "="*50 + "[/dim]")
self.console.print(f"[dim]Full log available at: {log_file}[/dim]")
except Exception as e:
self.console.print(f"[red]Error reading log file: {e}[/red]")
time.sleep(3) # Give time to read the logs
def _check_mining_status(self):
"""Check detailed mining process status"""
self.console.print("[bold]Mining Process Status:[/bold]")
# Check if XMRig process exists
if not hasattr(self.xmrig_controller, 'xmrig_process') or self.xmrig_controller.xmrig_process is None:
self.console.print("❌ [red]No XMRig process found[/red]")
return
process = self.xmrig_controller.xmrig_process
# Check process status
return_code = process.poll()
if return_code is None:
self.console.print("✅ [green]XMRig process is running[/green]")
self.console.print(f" PID: {process.pid}")
else:
self.console.print(f"❌ [red]XMRig process exited with code: {return_code}[/red]")
# Check if monitoring is active
if hasattr(self.xmrig_controller.monitor, 'monitoring') and self.xmrig_controller.monitor.monitoring:
self.console.print("✅ [green]Monitoring thread is active[/green]")
else:
self.console.print("❌ [red]Monitoring thread is not active[/red]")
# Check if log file exists
log_file = get_script_dir() / "xmrig.log"
if log_file.exists():
size = log_file.stat().st_size
self.console.print(f"📄 [blue]Log file exists ({size} bytes)[/blue]")
else:
self.console.print("❌ [red]No log file found[/red]")
# Show recent stats
stats = self.monitor.get_stats_summary()
self.console.print(f"\n[bold]Current Stats:[/bold]")
self.console.print(f"Status: {stats['status']}")
self.console.print(f"Hashrate: {stats['hashrate']:.1f} H/s")
self.console.print(f"Accepted: {stats['accepted_shares']}")
self.console.print(f"Rejected: {stats['rejected_shares']}")
time.sleep(4) # Give time to read the status
def _troubleshoot_connection(self):
"""Troubleshoot mining pool connection issues"""
self.console.print("[bold]🔧 Mining Connection Troubleshooter[/bold]")
self.console.print("=" * 50)
# Check current pool configuration
config = self.xmrig_controller.load_config()
if config and 'pools' in config and config['pools']:
pool = config['pools'][0]
pool_url = pool.get('url', 'Unknown')
tls_enabled = pool.get('tls', False)
self.console.print(f"[blue]Current Pool:[/blue] {pool_url}")
self.console.print(f"[blue]TLS Enabled:[/blue] {tls_enabled}")
else:
self.console.print("[red]❌ No pool configuration found[/red]")
time.sleep(2)