-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
367 lines (334 loc) · 16.2 KB
/
proxy.py
File metadata and controls
367 lines (334 loc) · 16.2 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
import asyncio
import json
import time
import os
import socket
from datetime import datetime
from collections import deque
from aiohttp import web
import aiohttp
CONFIG_FILE = 'config.json'
LISTEN_PORT = 3333
WEB_PORT = 8080
def load_config():
default_config = {
"host": "xxx",
"port": 3440,
"wallet": "xxx",
"worker": "xxx",
"pass": "x",
"host2": "",
"port2": 3333,
"wallet2": "",
"worker2": "",
"pass2": "x",
"discord_url": ""
}
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
loaded = json.load(f)
default_config.update(loaded)
except: pass
return default_config
config = load_config()
def save_config(data):
config.update({
"host": data['host'],
"port": int(data['port']),
"wallet": data['wallet'],
"worker": data['worker'],
"pass": data.get('pass', 'x'),
"host2": data.get('host2', ''),
"port2": int(data.get('port2', 3333)) if data.get('port2') else 3333,
"wallet2": data.get('wallet2', ''),
"worker2": data.get('worker2', ''),
"pass2": data.get('pass2', 'x'),
"discord_url": data.get('discord_url', '')
})
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
stats = {
"start_time": time.time(),
"connected_miners": 0,
"shares_submitted": 0,
"pool_errors": 0,
"pool_rejects": 0
}
share_history = deque()
current_difficulty = 1.0
active_connections = set()
log_history = deque(maxlen=50)
def log(msg):
formatted_msg = f"[{datetime.now().strftime('%H:%M:%S')}] {msg}"
print(formatted_msg, flush=True)
log_history.append(formatted_msg)
async def send_discord(msg):
url = config.get("discord_url")
if not url: return
try:
async with aiohttp.ClientSession() as session:
await session.post(url, json={"content": f"⛏️ **Bitaxe Proxy:** {msg}"})
except Exception as e:
log(f"⚠️ Discord Webhook Error: {e}")
def get_hashrate():
now = time.time()
while share_history and share_history[0][0] < now - 60:
share_history.popleft()
if not share_history: return "0.00 TH/s"
total_diff = sum(diff for _, diff in share_history)
hps = (total_diff * (2**32)) / 60
if hps > 1e15: return f"{hps / 1e15:.2f} PH/s"
elif hps > 1e12: return f"{hps / 1e12:.2f} TH/s"
elif hps > 1e9: return f"{hps / 1e9:.2f} GH/s"
else: return f"{hps:.2f} H/s"
def apply_keepalive(writer):
sock = writer.get_extra_info('socket')
if sock is not None:
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, 'TCP_KEEPIDLE'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
except Exception: pass
async def pipe(rd, wr, is_client, other_wr, client_ip, target_user, target_pass):
global current_difficulty
buffer = b""
try:
while True:
chunk = await rd.read(4096)
if not chunk: break
buffer += chunk
while b'\n' in buffer:
line, buffer = buffer.split(b'\n', 1)
if not line.strip(): continue
try:
msg = json.loads(line)
if is_client:
method = msg.get('method')
if method == 'mining.submit':
stats["shares_submitted"] += 1
share_history.append((time.time(), current_difficulty))
log(f"📤 SHARE SUBMITTED: {client_ip}")
if method in ['mining.authorize', 'mining.submit']:
msg['params'][0] = target_user
if method == 'mining.authorize':
if len(msg['params']) > 1:
msg['params'][1] = target_pass
else:
msg['params'].append(target_pass)
elif method == 'mining.suggest_difficulty':
msg['params'][0] = float(msg['params'][0])
out_data = json.dumps(msg, separators=(',', ':')).encode() + b'\n'
else:
method = msg.get('method')
if method == 'mining.set_difficulty':
current_difficulty = float(msg['params'][0])
log(f"📈 POOL SET DIFF: {current_difficulty}")
elif method == 'mining.notify':
job_id = msg['params'][0]
log(f"📋 NEW JOB: {job_id[:8]}...")
if msg.get('error'):
stats["pool_errors"] += 1
err_msg = msg['error']
log(f"⚠️ POOL ERROR: {err_msg}")
elif msg.get('result') is False:
stats["pool_rejects"] += 1
log(f"❌ POOL REJECTED AUTH/SUBMIT")
out_data = line + b'\n'
except:
out_data = line + b'\n'
wr.write(out_data)
await wr.drain()
except: pass
finally:
wr.close()
other_wr.close()
async def handle_client(reader, writer):
client_ip = writer.get_extra_info('peername')[0]
active_connections.add(writer)
stats["connected_miners"] += 1
log(f"🔌 CONNECTED: {client_ip} (Total: {stats['connected_miners']})")
try:
p_rd, p_wr = await asyncio.wait_for(asyncio.open_connection(config["host"], config["port"]), timeout=5)
apply_keepalive(p_wr)
active_user = f"{config['wallet']}.{config['worker']}"
active_pass = config['pass']
except Exception as e:
log(f"⚠️ MAIN POOL FAILED. TRYING BACKUP...")
await send_discord(f"⚠️ **Main Pool Failed!** สลับไปใช้พูลสำรองอัตโนมัติ")
try:
bk_host = config.get("host2") or config["host"]
bk_port = config.get("port2") or config["port"]
p_rd, p_wr = await asyncio.wait_for(asyncio.open_connection(bk_host, bk_port), timeout=5)
apply_keepalive(p_wr)
bk_wallet = config.get("wallet2") or config["wallet"]
bk_worker = config.get("worker2") or config["worker"]
active_user = f"{bk_wallet}.{bk_worker}"
active_pass = config.get('pass2', 'x')
except:
log(f"❌ ALL POOLS FAILED")
await send_discord(f"🚨 **CRITICAL:** เชื่อมต่อพูลไม่ได้เลย! เครื่องขุดหยุดทำงาน")
stats["connected_miners"] -= 1
active_connections.discard(writer)
writer.close()
return
try:
await asyncio.gather(
pipe(reader, p_wr, True, writer, client_ip, active_user, active_pass),
pipe(p_rd, writer, False, p_wr, client_ip, active_user, active_pass)
)
except: pass
finally:
stats["connected_miners"] -= 1
active_connections.discard(writer)
writer.close()
log(f"🔴 DISCONNECTED: {client_ip}")
async def update_config(request):
data = await request.post()
save_config(data)
log(f"⚙️ CONFIG SAVED. Disconnecting all miners to apply changes...")
await send_discord(f"🔧 **ตั้งค่าใหม่ถูกบันทึก** กำลังรีสตาร์ทเครื่องขุดทั้งหมด...")
for w in list(active_connections):
try: w.close()
except: pass
raise web.HTTPFound('/')
async def web_dashboard(request):
uptime_sec = int(time.time() - stats["start_time"])
hours, remainder = divmod(uptime_sec, 3600)
minutes, seconds = divmod(remainder, 60)
hashrate_str = get_hashrate()
current_active_user = f"{config['wallet']}.{config['worker']}"
logs_html = "<br>".join(log_history)
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Bitaxe Proxy Dashboard</title>
<style>
body {{ font-family: Arial; background: #1e1e1e; color: #fff; padding: 20px; display: flex; gap: 20px; justify-content: center; flex-wrap: wrap; max-width: 1100px; margin: auto; }}
.card {{ background: #333; padding: 20px; border-radius: 8px; width: 450px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }}
.log-card {{ width: 100%; max-width: 940px; background: #222; }}
h2 {{ color: #4CAF50; margin-top: 0; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }}
ul {{ list-style: none; padding: 0; margin: 0; }}
li {{ padding: 10px 0; border-bottom: 1px solid #444; }}
span {{ float: right; font-weight: bold; color: #4CAF50; }}
.pool {{ color: #2196F3; font-size: 14px; }}
.wallet {{ color: #FFC107; font-size: 12px; word-break: break-all; }}
.error {{ color: #f44336; }}
.hashrate {{ color: #00BCD4; font-size: 18px; }}
input {{ width: 100%; padding: 8px; margin: 5px 0 15px; box-sizing: border-box; background: #222; color: #888; border: 1px solid #555; }}
input:not(:disabled) {{ color: #fff; border: 1px solid #4CAF50; }}
.input-group {{ display: flex; gap: 10px; }}
.input-group > div {{ flex: 1; }}
button {{ width: 100%; padding: 10px; background: #4CAF50; color: white; border: none; cursor: pointer; font-weight: bold; border-radius: 4px; margin-bottom: 10px; }}
button:hover {{ background: #45a049; }}
.btn-edit {{ background: #2196F3; }}
.btn-edit:hover {{ background: #0b7dda; }}
hr {{ border-color: #555; margin: 20px 0; }}
label {{ font-size: 12px; color: #ccc; }}
#log-content {{ font-family: monospace; font-size: 13px; color: #0f0; height: 200px; overflow-y: auto; padding: 10px; background: #111; border-radius: 4px; border: 1px solid #444; }}
</style>
<script>
setInterval(function() {{
fetch('/?t=' + new Date().getTime()).then(res => res.text()).then(html => {{
let parser = new DOMParser();
let doc = parser.parseFromString(html, 'text/html');
document.getElementById('stats-box').innerHTML = doc.getElementById('stats-box').innerHTML;
let logBox = document.getElementById('log-content');
let newLogContent = doc.getElementById('log-content').innerHTML;
if (logBox.innerHTML !== newLogContent) {{
let isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 1;
logBox.innerHTML = newLogContent;
if(isScrolledToBottom) {{
logBox.scrollTop = logBox.scrollHeight;
}}
}}
}});
}}, 5000);
function enableEdit() {{
let inputs = document.querySelectorAll('#settings-form input');
inputs.forEach(inp => inp.disabled = false);
document.getElementById('btn-edit').style.display = 'none';
document.getElementById('btn-save').style.display = 'block';
}}
window.onload = function() {{
let logBox = document.getElementById('log-content');
logBox.scrollTop = logBox.scrollHeight;
}};
</script>
</head>
<body>
<div class="card" id="stats-box">
<h2>📊 Bitaxe Status</h2>
<ul>
<li>Uptime <span>{hours}h {minutes}m {seconds}s</span></li>
<li>Est. Hashrate <span class="hashrate">{hashrate_str}</span></li>
<li>Bitaxes Online <span>{stats['connected_miners']}</span></li>
<li>Main Pool <br><span class="pool" style="float:none;">{config['host']}:{config['port']}</span></li>
<li>Active Worker <br><span class="wallet" style="float:none;">{current_active_user}</span></li>
<li>Total Shares <span>{stats['shares_submitted']}</span></li>
<li>Rejects <span class="error">{stats['pool_rejects']}</span></li>
<li>Errors <span class="error">{stats['pool_errors']}</span></li>
</ul>
</div>
<div class="card">
<h2>⚙️ Configuration</h2>
<form id="settings-form" method="POST" action="/update" onsubmit="return confirm('Save changes and disconnect all miners to apply?');">
<b>Main Pool</b>
<div class="input-group">
<div style="flex: 2;"><label>Host</label><input type="text" name="host" value="{config['host']}" required disabled></div>
<div><label>Port</label><input type="number" name="port" value="{config['port']}" required disabled></div>
</div>
<div class="input-group">
<div style="flex: 2;"><label>Wallet</label><input type="text" name="wallet" value="{config['wallet']}" required disabled></div>
<div><label>Worker</label><input type="text" name="worker" value="{config['worker']}" required disabled></div>
<div><label>Password</label><input type="text" name="pass" value="{config.get('pass', 'x')}" disabled></div>
</div>
<hr>
<b>Backup Pool</b>
<div class="input-group">
<div style="flex: 2;"><label>Host</label><input type="text" name="host2" value="{config.get('host2', '')}" disabled></div>
<div><label>Port</label><input type="number" name="port2" value="{config.get('port2', 3333)}" disabled></div>
</div>
<div class="input-group">
<div style="flex: 2;"><label>Wallet</label><input type="text" name="wallet2" value="{config.get('wallet2', '')}" disabled></div>
<div><label>Worker</label><input type="text" name="worker2" value="{config.get('worker2', '')}" disabled></div>
<div><label>Password</label><input type="text" name="pass2" value="{config.get('pass2', 'x')}" disabled></div>
</div>
<hr>
<b>Notifications</b>
<div>
<label>Discord Webhook URL</label>
<input type="text" name="discord_url" value="{config.get('discord_url', '')}" disabled>
</div>
<button type="button" id="btn-edit" class="btn-edit" onclick="enableEdit()">✏️ Edit Settings</button>
<button type="submit" id="btn-save" style="display: none;">💾 Save & Restart Miners</button>
</form>
</div>
<div class="card log-card">
<h2>📝 System Logs</h2>
<div id="log-content">{logs_html}</div>
</div>
</body>
</html>
"""
return web.Response(text=html, content_type='text/html')
async def start_web_server():
app = web.Application()
app.router.add_get('/', web_dashboard)
app.router.add_post('/update', update_config)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', WEB_PORT)
await site.start()
async def main():
await start_web_server()
await send_discord("🟢 **Proxy Started Successfully!** ระบบพร้อมรับการเชื่อมต่อจาก Bitaxe แล้ว")
server = await asyncio.start_server(handle_client, '0.0.0.0', LISTEN_PORT)
log(f"=== STRATUM PROXY ACTIVE (PORT {LISTEN_PORT}) | WEB UI (PORT {WEB_PORT}) ===")
async with server:
await server.serve_forever()
if __name__ == '__main__':
asyncio.run(main())