File size: 9,548 Bytes
cca7387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

XMRig FastAPI Server - Web interface for RandomX benchmarking

Spawns xmrig_launcher.py as subprocess for mining operations

"""

import os
import sys
import subprocess
import platform
import ctypes
from pathlib import Path
from typing import Optional
from datetime import datetime
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import uvicorn
import threading

# ==================== Admin Detection ====================

def is_admin():
    """Check if running with admin privileges"""
    try:
        return ctypes.windll.shell.IsUserAnAdmin()
    except:
        return False


# ==================== Pydantic Models ====================

class BenchmarkRequest(BaseModel):
    benchmark: str = "1M"
    threads: Optional[int] = None


# ==================== Mining Manager Class ====================

class MiningManager:
    def __init__(self, base_dir=None):
        if base_dir is None:
            base_dir = Path(__file__).parent.absolute()
        
        self.base_dir = Path(base_dir)
        self.launcher_script = self.base_dir / "xmrig_launcher.py"
        self.process = None
        self.benchmark_config = {}
        self.logs = []
        self.log_reader_thread = None
        
    def start_mining(self, benchmark="1M", threads=None):
        """Start mining by spawning xmrig_launcher.py"""
        if self.process and self.process.poll() is None:
            raise HTTPException(status_code=400, detail="Mining already running")
        
        if threads is None:
            threads = os.cpu_count() or 4
        
        # Clear previous logs
        self.logs = []
        
        # Build command to run launcher script
        cmd = [
            sys.executable,
            str(self.launcher_script),
            "--bench", benchmark,
            "--threads", str(threads)
        ]
        
        # Store config
        self.benchmark_config = {
            "benchmark": benchmark,
            "threads": threads,
            "started_at": datetime.now().isoformat(),
            "status": "running"
        }
        
        try:
            # Start process with output capture
            self.process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            
            # Start log reader thread
            self.log_reader_thread = threading.Thread(target=self._read_logs, daemon=True)
            self.log_reader_thread.start()
            
            return True
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Failed to start mining: {e}")
    
    def _read_logs(self):
        """Read logs from process in real-time (daemon thread)"""
        try:
            if self.process and self.process.stdout:
                # This runs in a daemon thread, so blocking readline is fine
                while self.process and self.process.poll() is None:
                    try:
                        line = self.process.stdout.readline()
                        if line:
                            log_entry = {
                                "timestamp": datetime.now().isoformat(),
                                "message": line.rstrip()
                            }
                            self.logs.append(log_entry)
                            print(line.rstrip())
                        else:
                            # EOF reached
                            break
                    except Exception as e:
                        print(f"[!] Error reading line: {e}")
                        break
        except Exception as e:
            print(f"[!] Error in log reader: {e}")
    
    def stop_mining(self):
        """Stop running mining"""
        if self.process and self.process.poll() is None:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()
            self.benchmark_config["status"] = "stopped"
            return True
        return False
    
    def is_running(self):
        """Check if mining is running"""
        return self.process and self.process.poll() is None
    
    def get_xmrig_status(self):
        """Check if launcher script is available"""
        return {
            "launcher_available": self.launcher_script.exists(),
            "launcher_path": str(self.launcher_script)
        }


# Global manager instance
manager = MiningManager()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    print("\n[*] Server starting...")
    
    # Check if launcher script exists
    if not manager.launcher_script.exists():
        print(f"[!] Warning: xmrig_launcher.py not found at {manager.launcher_script}")
    else:
        print(f"[+] Launcher script found")
    
    print("[+] Server ready - click Start Mining button to begin")
    
    yield
    
    # Shutdown
    print("\n[*] Server shutting down...")
    manager.stop_mining()


# ==================== FastAPI App ====================

app = FastAPI(
    title="XMRig Mining Server",
    description="FastAPI server for RandomX benchmarking with XMRig launcher",
    version="1.0.0",
    lifespan=lifespan
)

# Mount static files (if directory exists)
static_dir = Path(__file__).parent / "static"
if static_dir.exists():
    app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/api")
async def api_info():
    """API endpoints info"""
    return {
        "name": "XMRig Mining Server",
        "version": "1.0.0",
        "endpoints": {
            "GET /health": "Health check",
            "GET /status": "Get system and mining status",
            "POST /mining/start": "Start mining with XMRig launcher",
            "POST /mining/stop": "Stop mining",
            "GET /mining/status": "Get mining status",
            "GET /logs": "Get mining logs"
        }
    }


@app.get("/")
async def root():
    """Root endpoint - serve static HTML UI"""
    try:
        with open("static/index.html", "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    except FileNotFoundError:
        return HTMLResponse(
            content="<h1>404</h1><p>static/index.html not found</p>",
            status_code=404
        )


@app.get("/health")
async def health():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "admin": is_admin()
    }


@app.get("/status")
async def status():
    """Get system and mining status"""
    return {
        "system": {
            "platform": platform.system(),
            "admin": is_admin(),
            "cpu_count": os.cpu_count() or 4
        },
        "xmrig": manager.get_xmrig_status(),
        "mining": {
            "running": manager.is_running(),
            "config": manager.benchmark_config if manager.benchmark_config else None
        }
    }


@app.post("/mining/start")
async def start_mining(request: BenchmarkRequest):
    """Start mining using xmrig_launcher.py"""
    if manager.is_running():
        raise HTTPException(status_code=400, detail="Mining already running")
    
    manager.start_mining(request.benchmark, request.threads)
    
    return {
        "status": "started",
        "benchmark": request.benchmark,
        "threads": request.threads or os.cpu_count() or 4,
        "admin": is_admin(),
        "admin_warning": "Run with admin for 2-3x better performance" if not is_admin() else None
    }


@app.post("/mining/stop")
async def stop_mining():
    """Stop running mining"""
    if manager.stop_mining():
        return {"status": "stopped"}
    else:
        raise HTTPException(status_code=400, detail="No mining running")


@app.get("/mining/status")
async def mining_status():
    """Get mining status"""
    return {
        "running": manager.is_running(),
        "config": manager.benchmark_config if manager.benchmark_config else None,
        "pid": manager.process.pid if manager.process else None
    }


@app.get("/logs")
async def get_logs():
    """Get mining logs"""
    return {
        "logs": manager.logs[-100:] if manager.logs else [],  # Last 100 logs
        "total_logs": len(manager.logs)
    }


# ==================== Main ====================

def main():
    """Run the FastAPI server"""
    print("\n" + "="*60)
    print("XMRig Mining Server")
    print("="*60)
    print("[*] Starting server on http://127.0.0.1:8000")
    print("[*] Web UI: http://127.0.0.1:8000/")
    print("[*] API docs: http://127.0.0.1:8000/docs")
    
    if is_admin():
        print("[+] Running as Administrator ✓")
    else:
        print("[!] NOT running as Administrator")
        print("    → Run as Admin for 2-3x better performance")
    
    print("="*60 + "\n")
    
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")


if __name__ == "__main__":
    main()