File size: 14,353 Bytes
adaed20
eec79a3
adaed20
eec79a3
adaed20
eec79a3
 
adaed20
 
eec79a3
 
 
 
adaed20
eec79a3
 
 
 
 
adaed20
 
 
 
 
 
 
eec79a3
 
 
 
 
 
 
 
 
 
adaed20
 
 
 
eec79a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaed20
eec79a3
adaed20
 
eec79a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaed20
 
eec79a3
adaed20
eec79a3
adaed20
eec79a3
adaed20
 
 
eec79a3
 
 
adaed20
 
eec79a3
 
 
adaed20
eec79a3
 
 
 
 
adaed20
 
eec79a3
adaed20
 
 
 
 
 
eec79a3
adaed20
eec79a3
adaed20
 
 
eec79a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaed20
eec79a3
adaed20
 
eec79a3
adaed20
 
 
 
 
 
 
eec79a3
 
 
 
adaed20
eec79a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaed20
eec79a3
adaed20
 
 
eec79a3
adaed20
eec79a3
 
 
adaed20
eec79a3
 
 
 
 
adaed20
eec79a3
 
adaed20
eec79a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaed20
eec79a3
 
 
adaed20
 
eec79a3
adaed20
 
eec79a3
 
 
 
 
 
 
 
 
 
 
adaed20
 
eec79a3
 
 
 
 
 
 
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
"""

FastAPI server for Bitcoin mining dashboard - Complete Integration

"""
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import threading
import time
import json
import asyncio
from typing import Dict, Optional, List
import logging
import sys
import os

# Add the current directory to Python path to import your miner
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

app = FastAPI(title="Bitcoin Mining Dashboard", version="1.0.0")

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")

# Global mining state
class MiningState:
    def __init__(self):
        self.is_mining = False
        self.miner_instance = None
        self.mining_thread = None
        self.stats = {
            "status": "Stopped",
            "hashrate": "0 H/s",
            "total_hashes": "0",
            "blocks_found": "0",
            "best_hash": "None",
            "difficulty": "0",
            "network_difficulty": "0",
            "block_alert": "Ready to start mining",
            "mining_time": "0s",
            "cores_active": "0",
            "wallet_address": "1Ks4WtCEK96BaBF7HSuCGt3rEpVKPqcJKf"
        }
        self.start_time = None

mining_state = MiningState()

@app.get("/", response_class=HTMLResponse)
async def get_index():
    """Serve the dashboard HTML"""
    try:
        return FileResponse("static/index.html")
    except:
        # Fallback minimal HTML
        return """

        <!DOCTYPE html>

        <html>

        <head>

            <title>Bitcoin Mining Dashboard</title>

            <style>

                body { font-family: Arial, sans-serif; margin: 40px; background: #f0f0f0; }

                .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; }

                .stats { background: #2c3e50; color: white; padding: 20px; border-radius: 5px; margin: 10px 0; }

                .alert { background: #e74c3c; color: white; padding: 15px; border-radius: 5px; margin: 10px 0; }

                .success { background: #27ae60; }

                .button { background: #3498db; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin: 5px; }

                .button:disabled { background: #95a5a6; }

            </style>

        </head>

        <body>

            <div class="container">

                <h1>⛏️ Bitcoin Mining Dashboard</h1>

                <div id="blockAlert" class="alert">Ready to start mining</div>

                <div class="stats">

                    <h3>Mining Statistics</h3>

                    <div id="statsDisplay"></div>

                </div>

                <button class="button" onclick="startMining()" id="startBtn">Start Mining</button>

                <button class="button" onclick="stopMining()" id="stopBtn" disabled>Stop Mining</button>

                <script>

                    function updateStats(stats) {

                        document.getElementById('statsDisplay').innerHTML = `

                            <p><strong>Status:</strong> ${stats.status}</p>

                            <p><strong>Hash Rate:</strong> ${stats.hashrate}</p>

                            <p><strong>Total Hashes:</strong> ${stats.total_hashes}</p>

                            <p><strong>Blocks Found:</strong> ${stats.blocks_found}</p>

                            <p><strong>Best Hash:</strong> ${stats.best_hash}</p>

                            <p><strong>Mining Time:</strong> ${stats.mining_time}</p>

                            <p><strong>Wallet:</strong> ${stats.wallet_address}</p>

                        `;

                        document.getElementById('blockAlert').textContent = stats.block_alert;

                        document.getElementById('blockAlert').className = stats.blocks_found > 0 ? 'alert success' : 'alert';

                        

                        document.getElementById('startBtn').disabled = stats.status === 'Running';

                        document.getElementById('stopBtn').disabled = stats.status !== 'Running';

                    }

                    

                    async function startMining() {

                        const response = await fetch('/start_mining', { method: 'POST' });

                        const result = await response.json();

                        alert(result.message);

                    }

                    

                    async function stopMining() {

                        const response = await fetch('/stop_mining', { method: 'POST' });

                        const result = await response.json();

                        alert(result.message);

                    }

                    

                    // Poll for stats updates

                    setInterval(async () => {

                        const response = await fetch('/get_stats');

                        const stats = await response.json();

                        updateStats(stats);

                    }, 1000);

                </script>

            </div>

        </body>

        </html>

        """

def mining_worker(duration=None):
    """Worker function to run mining in background thread"""
    try:
        # Import and initialize the miner
        from parallel_miner_v3 import ParallelMiner
        
        mining_state.miner_instance = ParallelMiner(
            num_cores=7, 
            wallet_address="1Ks4WtCEK96BaBF7HSuCGt3rEpVKPqcJKf"
        )
        mining_state.start_time = time.time()
        
        # Start mining
        mining_state.miner_instance.start_mining(duration=duration)
        
    except Exception as e:
        logging.error(f"Mining worker error: {e}")
    finally:
        mining_state.is_mining = False
        mining_state.mining_thread = None

@app.post("/start_mining")
async def start_mining(background_tasks: BackgroundTasks):
    """Start the mining process"""
    global mining_state
    
    if mining_state.is_mining:
        raise HTTPException(status_code=400, detail="Mining is already running")
    
    try:
        mining_state.is_mining = True
        mining_state.stats["status"] = "Starting..."
        mining_state.stats["block_alert"] = "πŸ”„ Starting mining process..."
        
        # Start mining in background thread
        mining_state.mining_thread = threading.Thread(
            target=mining_worker,
            kwargs={"duration": None}  # Mine indefinitely
        )
        mining_state.mining_thread.daemon = True
        mining_state.mining_thread.start()
        
        logging.info("βœ… Mining started via API")
        return {"message": "Mining started successfully", "status": "started"}
        
    except Exception as e:
        mining_state.is_mining = False
        logging.error(f"Error starting mining: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/stop_mining")
async def stop_mining():
    """Stop the mining process"""
    global mining_state
    
    if not mining_state.is_mining:
        raise HTTPException(status_code=400, detail="Mining is not running")
    
    try:
        if mining_state.miner_instance:
            mining_state.miner_instance.mining = False
            mining_state.is_mining = False
            
            # Log final statistics
            if hasattr(mining_state.miner_instance, 'total_hashes'):
                total_hashes = mining_state.miner_instance.total_hashes
                blocks_found = mining_state.miner_instance.blocks_found
                mining_time = time.time() - mining_state.start_time
                
                logging.info("\n" + "="*50)
                logging.info("⛏️ FINAL MINING STATISTICS")
                logging.info("="*50)
                logging.info(f"⏱️ Total mining time: {mining_time:.2f} seconds")
                logging.info(f"πŸ”’ Total hashes: {total_hashes:,}")
                logging.info(f"πŸ’° Blocks found: {blocks_found}")
                logging.info(f"⚑ Average hash rate: {total_hashes/max(mining_time,1)/1000:.2f} KH/s")
                
                if hasattr(mining_state.miner_instance, 'cores'):
                    for core_idx, core in enumerate(mining_state.miner_instance.cores):
                        logging.info(f"πŸ”© Core {core_idx}: {core.total_hashes:,} hashes")
                logging.info("="*50)
            
            mining_state.stats["status"] = "Stopped"
            mining_state.stats["block_alert"] = "πŸ›‘ Mining stopped"
            
            return {"message": "Mining stopped successfully", "status": "stopped"}
            
        raise HTTPException(status_code=400, detail="No active mining instance")
        
    except Exception as e:
        logging.error(f"Error stopping mining: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/get_stats")
async def get_mining_stats():
    """Get current mining statistics"""
    global mining_state
    
    if not mining_state.is_mining or not mining_state.miner_instance:
        return mining_state.stats
    
    try:
        miner = mining_state.miner_instance
        
        # Calculate mining time
        mining_time = time.time() - mining_state.start_time
        time_str = f"{int(mining_time//3600)}h {int((mining_time%3600)//60)}m {int(mining_time%60)}s"
        
        # Create block alert message
        if miner.blocks_found > 0:
            block_alert = f"πŸŽ‰ FOUND {miner.blocks_found} BLOCK(S)! πŸŽ‰"
            if miner.best_hash:
                block_alert += f" Hash: {miner.best_hash.hex()[:16]}..."
        else:
            progress = (miner.best_hash_difficulty / max(miner.network_difficulty, 1)) * 100 if miner.best_hash_difficulty else 0
            block_alert = f"⛏️ Mining... Progress: {progress:.8f}%"
        
        # Update stats
        mining_state.stats.update({
            "status": "Running",
            "hashrate": f"{miner.current_hashrate/1000:.2f} KH/s",
            "total_hashes": f"{miner.total_hashes:,}",
            "blocks_found": str(miner.blocks_found),
            "best_hash": miner.best_hash.hex()[:32] + "..." if miner.best_hash else "None",
            "difficulty": f"{miner.best_hash_difficulty:.8f}" if miner.best_hash_difficulty else "0",
            "network_difficulty": f"{miner.network_difficulty:,.2f}" if hasattr(miner, 'network_difficulty') else "0",
            "block_alert": block_alert,
            "mining_time": time_str,
            "cores_active": f"{len(miner.cores)}" if hasattr(miner, 'cores') else "0"
        })
        
        return mining_state.stats
        
    except Exception as e:
        logging.error(f"Error getting mining stats: {e}")
        return {
            "status": "Error",
            "hashrate": "0 H/s",
            "total_hashes": "0",
            "blocks_found": "0",
            "best_hash": "Error",
            "difficulty": "0",
            "block_alert": f"Error: {str(e)}",
            "mining_time": "0s",
            "cores_active": "0"
        }

@app.get("/get_detailed_stats")
async def get_detailed_stats():
    """Get detailed mining statistics including per-core info"""
    global mining_state
    
    if not mining_state.is_mining or not mining_state.miner_instance:
        return {"error": "Mining not active"}
    
    try:
        miner = mining_state.miner_instance
        detailed_stats = {
            "overview": {
                "status": "Running",
                "total_hashes": miner.total_hashes,
                "blocks_found": miner.blocks_found,
                "current_hashrate": miner.current_hashrate,
                "best_hash_difficulty": miner.best_hash_difficulty,
                "network_difficulty": miner.network_difficulty,
                "mining_time": time.time() - mining_state.start_time
            },
            "cores": []
        }
        
        if hasattr(miner, 'cores'):
            for core in miner.cores:
                core_info = {
                    "core_id": core.core_id,
                    "total_hashes": core.total_hashes,
                    "blocks_found": core.blocks_found,
                    "units": []
                }
                
                for unit in core.units:
                    core_info["units"].append({
                        "unit_id": unit.unit_id,
                        "total_hashes": unit.total_hashes,
                        "blocks_found": unit.blocks_found
                    })
                
                detailed_stats["cores"].append(core_info)
        
        return detailed_stats
        
    except Exception as e:
        return {"error": str(e)}

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "mining_active": mining_state.is_mining,
        "timestamp": time.time()
    }

# Background task to periodically update stats
@app.on_event("startup")
async def startup_event():
    """Initialize on startup"""
    logging.info("πŸš€ Bitcoin Mining Dashboard starting up...")

@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    global mining_state
    if mining_state.is_mining and mining_state.miner_instance:
        mining_state.miner_instance.mining = False
        mining_state.is_mining = False
    logging.info("πŸ›‘ Bitcoin Mining Dashboard shutting down...")

if __name__ == "__main__":
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=7868,
        reload=False,
        log_level="info"
    )