Repository navigation
Expand file tree
/
Copy pathproxy.py
More file actions
549 lines (500 loc) · 21 KB
/
Copy pathproxy.py
File metadata and controls
549 lines (500 loc) · 21 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
import asyncio
import base64
import ipaddress
import json
import time
import os
import socket
import secrets
from datetime import datetime
from collections import deque
from aiohttp import web
import dashboard as dashboard_view
CONFIG_FILE = 'config.json'
LISTEN_PORT = 3333
WEB_PORT = int(os.environ.get('WEB_PORT', '8080'))
WEB_HOST = os.environ.get('WEB_HOST', '0.0.0.0')
WEB_USERNAME = os.environ.get('WEB_USERNAME', 'admin')
WEB_PASSWORD = os.environ.get('WEB_PASSWORD', '')
WEB_ALLOWED_IPS = os.environ.get('WEB_ALLOWED_IPS', '')
CSRF_TOKEN = secrets.token_urlsafe(32)
MAX_STRATUM_LINE_BYTES = 1024 * 1024
MAIN_POOL_RETRY_SECONDS = 60
pool_retry_at = {}
last_connected_pool_index = None
def load_config():
default_config = {
"host": "xxx",
"port": 3440,
"wallet": "xxx",
"pass": "x",
"host2": "",
"port2": 3333,
"wallet2": "",
"pass2": "x",
"host3": "",
"port3": 3333,
"wallet3": "",
"pass3": "x"
}
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
raise ValueError('config root must be a JSON object')
loaded.pop('discord_url', None)
for key in ('worker', 'worker2', 'worker3', 'user', 'user2'):
loaded.pop(key, None)
default_config.update(loaded)
except (OSError, json.JSONDecodeError, ValueError) as exc:
raise RuntimeError(f'Unable to load {CONFIG_FILE}: {exc}') from exc
for key in ('port', 'port2', 'port3'):
try:
default_config[key] = int(default_config[key])
except (TypeError, ValueError) as exc:
raise RuntimeError(f'Invalid {key} in {CONFIG_FILE}') from exc
if not 1 <= default_config[key] <= 65535:
raise RuntimeError(f'Invalid {key} in {CONFIG_FILE}: must be 1-65535')
return default_config
config = load_config()
def save_config(data):
def parse_port(value, fallback):
try:
port = int(value) if value else fallback
except (TypeError, ValueError) as exc:
raise ValueError('Ports must be integers between 1 and 65535') from exc
if not 1 <= port <= 65535:
raise ValueError('Ports must be integers between 1 and 65535')
return port
host = data.get('host', '').strip()
wallet = data.get('wallet', '').strip()
if not host or not wallet:
raise ValueError('Main pool host and wallet are required')
updated = {}
for index in range(1, 4):
suffix = '' if index == 1 else str(index)
host_key = f'host{suffix}'
port_key = f'port{suffix}'
wallet_key = f'wallet{suffix}'
pass_key = 'pass' if index == 1 else f'pass{index}'
updated[host_key] = data.get(host_key, '').strip()
updated[port_key] = parse_port(
data.get(port_key), config.get(port_key, config['port'])
)
updated[wallet_key] = data.get(wallet_key, '').strip()
updated[pass_key] = data.get(pass_key) or config.get(pass_key, 'x')
config.update(updated)
config.pop('discord_url', None)
for key in ('worker', 'worker2', 'worker3', 'user', 'user2'):
config.pop(key, None)
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
pool_retry_at.clear()
global last_connected_pool_index
last_connected_pool_index = None
def configured_pools():
pools = []
for index in range(1, 4):
suffix = '' if index == 1 else str(index)
host = config.get(f'host{suffix}', '').strip()
if not host:
continue
pools.append({
'index': index,
'host': host,
'port': config.get(f'port{suffix}') or config['port'],
'wallet': config.get(f'wallet{suffix}') or config['wallet'],
'password': config.get('pass' if index == 1 else f'pass{index}', 'x')
})
return pools
def build_pool_username(pool_wallet, miner_username):
miner_username = miner_username if isinstance(miner_username, str) else ''
_, separator, miner_worker = miner_username.partition('.')
worker = miner_worker.strip() if separator else ''
return f'{pool_wallet}.{worker}' if worker else pool_wallet
stats = {
"start_time": time.time(),
"connected_miners": 0,
"shares_submitted": 0,
"pool_errors": 0,
"pool_rejects": 0
}
share_history = deque()
active_connections = set()
log_history = deque(maxlen=50)
def log(msg):
safe_msg = str(msg).replace('\r', '\\r').replace('\n', '\\n')
formatted_msg = f"[{datetime.now().strftime('%H:%M:%S')}] {safe_msg}"
print(formatted_msg, flush=True)
log_history.append(formatted_msg)
def validate_web_credentials():
if not WEB_USERNAME or ':' in WEB_USERNAME or len(WEB_PASSWORD) < 12:
raise RuntimeError('Set WEB_USERNAME and a WEB_PASSWORD with at least 12 characters')
try:
parse_allowed_networks(WEB_ALLOWED_IPS)
except ValueError as exc:
raise RuntimeError(f'Invalid WEB_ALLOWED_IPS: {exc}') from exc
def parse_allowed_networks(value):
networks = []
for item in value.split(','):
item = item.strip()
if item:
networks.append(ipaddress.ip_network(item, strict=False))
return networks
def client_ip_is_allowed(client_ip, networks):
if not networks:
return True
if not client_ip:
return False
try:
address = ipaddress.ip_address(client_ip)
except ValueError:
return False
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped:
address = address.ipv4_mapped
return any(address.version == network.version and address in network for network in networks)
@web.middleware
async def dashboard_security(request, handler):
validate_web_credentials()
allowed_networks = parse_allowed_networks(WEB_ALLOWED_IPS)
if not client_ip_is_allowed(request.remote, allowed_networks):
raise web.HTTPForbidden(text='Client IP is not allowed')
expected = 'Basic ' + base64.b64encode(
f'{WEB_USERNAME}:{WEB_PASSWORD}'.encode()
).decode()
supplied = request.headers.get('Authorization', '')
if not secrets.compare_digest(supplied, expected):
raise web.HTTPUnauthorized(headers={'WWW-Authenticate': 'Basic realm="Bitaxe Proxy"'})
if request.method == 'POST':
form = await request.post()
if not secrets.compare_digest(str(form.get('csrf_token', '')), CSRF_TOKEN):
raise web.HTTPForbidden(text='Invalid CSRF token')
response = await handler(request)
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Referrer-Policy'] = 'no-referrer'
response.headers['Cache-Control'] = 'no-store'
return response
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_wallet, target_pass,
connection_state, pending_shares):
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 len(line) > MAX_STRATUM_LINE_BYTES:
raise ValueError('Stratum message exceeds maximum size')
if not line.strip(): continue
try:
msg = json.loads(line)
if is_client:
method = msg.get('method')
if method in ['mining.authorize', 'mining.submit']:
params = msg.setdefault('params', [])
if not isinstance(params, list):
raise ValueError('Stratum params must be a list')
if method == 'mining.authorize':
miner_username = params[0] if params else ''
target_user = build_pool_username(target_wallet, miner_username)
connection_state['target_user'] = target_user
if params:
params[0] = target_user
else:
params.append(target_user)
while len(params) < 2:
params.append(target_pass)
params[1] = target_pass
else:
target_user = connection_state.get(
'target_user',
build_pool_username(target_wallet, '')
)
if params:
params[0] = target_user
else:
params.append(target_user)
request_id = msg.get('id')
if isinstance(request_id, (str, int)):
pending_shares[request_id] = (
time.time(), connection_state['difficulty']
)
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':
connection_state['difficulty'] = float(msg['params'][0])
log(f"📈 POOL SET DIFF: {connection_state['difficulty']}")
elif method == 'mining.notify':
job_id = msg['params'][0]
log(f"📋 NEW JOB: {str(job_id)[:8]}...")
response_id = msg.get('id')
pending_share = pending_shares.pop(response_id, None) \
if isinstance(response_id, (str, int)) else None
if pending_share is not None and 'result' in msg:
if msg.get('result') is True:
stats['shares_submitted'] += 1
share_history.append(pending_share)
log(f"✅ SHARE ACCEPTED: {client_ip}")
else:
stats['pool_rejects'] += 1
if msg.get('error'):
stats["pool_errors"] += 1
err_msg = msg['error']
log(f"⚠️ POOL ERROR: {err_msg}")
elif msg.get('result') is False and pending_share is None:
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)
if len(buffer) > MAX_STRATUM_LINE_BYTES:
raise ValueError('Stratum message exceeds maximum size')
await wr.drain()
except Exception as e:
log(f"⚠️ Relay closed for {client_ip}: {e}")
finally:
connection_state.setdefault('ended_by', 'client' if is_client else 'pool')
wr.close()
other_wr.close()
async def connect_upstream():
global last_connected_pool_index
pools = configured_pools()
if not pools:
raise ConnectionError('No pool hosts are configured')
now = time.monotonic()
available = [pool for pool in pools if pool_retry_at.get(pool['index'], 0) <= now]
if not available:
available = [min(pools, key=lambda pool: pool_retry_at.get(pool['index'], 0))]
failures = []
for pool in available:
index = pool['index']
try:
p_rd, p_wr = await asyncio.wait_for(
asyncio.open_connection(pool['host'], pool['port']), timeout=5
)
except Exception as exc:
pool_retry_at[index] = time.monotonic() + MAIN_POOL_RETRY_SECONDS
failures.append(f"Pool {index}: {exc}")
log(f"⚠️ POOL {index} FAILED: {exc}")
continue
apply_keepalive(p_wr)
pool_retry_at.pop(index, None)
last_connected_pool_index = index
log(f"✅ CONNECTED TO POOL {index}: {pool['host']}:{pool['port']}")
return p_rd, p_wr, pool['wallet'], pool['password'], index
raise ConnectionError('All configured pools failed: ' + '; '.join(failures))
async def monitor_primary_pool(client_writer, connection_state):
while not client_writer.is_closing():
retry_at = pool_retry_at.get(1, time.monotonic())
delay = retry_at - time.monotonic()
if delay > 0:
await asyncio.sleep(delay)
primary = next(
(pool for pool in configured_pools() if pool['index'] == 1), None
)
if primary is None:
return
try:
_, probe_writer = await asyncio.wait_for(
asyncio.open_connection(primary['host'], primary['port']), timeout=5
)
except Exception as exc:
pool_retry_at[1] = time.monotonic() + MAIN_POOL_RETRY_SECONDS
log(f'⚠️ PRIMARY POOL PROBE FAILED: {exc}')
continue
probe_writer.close()
await probe_writer.wait_closed()
if client_writer.is_closing():
return
pool_retry_at.pop(1, None)
connection_state['failback'] = True
log('✅ PRIMARY POOL IS AVAILABLE; reconnecting miner to pool 1')
client_writer.close()
return
async def handle_client(reader, writer):
peername = writer.get_extra_info('peername')
client_ip = peername[0] if peername else 'unknown'
active_connections.add(writer)
stats["connected_miners"] += 1
log(f"🔌 CONNECTED: {client_ip} (Total: {stats['connected_miners']})")
try:
try:
p_rd, p_wr, active_wallet, active_pass, selected_pool_index = await connect_upstream()
except Exception as exc:
log(f"❌ Unable to connect to a pool: {exc}")
writer.close()
return
apply_keepalive(p_wr)
connection_state = {
'difficulty': 1.0,
'target_user': build_pool_username(active_wallet, '')
}
pending_shares = {}
client_task = asyncio.create_task(pipe(
reader, p_wr, True, writer, client_ip, active_wallet, active_pass,
connection_state, pending_shares
))
pool_task = asyncio.create_task(pipe(
p_rd, writer, False, p_wr, client_ip, active_wallet, active_pass,
connection_state, pending_shares
))
tasks = {client_task, pool_task}
primary_monitor_task = None
if selected_pool_index != 1:
primary_monitor_task = asyncio.create_task(
monitor_primary_pool(writer, connection_state)
)
tasks.add(primary_monitor_task)
while True:
done, pending = await asyncio.wait(
tasks, return_when=asyncio.FIRST_COMPLETED
)
if (primary_monitor_task in done
and not connection_state.get('failback')):
tasks.discard(primary_monitor_task)
primary_monitor_task = None
continue
break
if connection_state.get('failback'):
p_wr.close()
writer.close()
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
await asyncio.gather(*done, return_exceptions=True)
if (connection_state.get('ended_by') == 'pool'
and not connection_state.get('failback')):
pool_retry_at[selected_pool_index] = time.monotonic() + MAIN_POOL_RETRY_SECONDS
log(f'⚠️ POOL {selected_pool_index} CONNECTION LOST; miners will try the next available pool')
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()
try:
save_config(data)
except (TypeError, ValueError) as exc:
raise web.HTTPBadRequest(text=str(exc)) from exc
log(f"⚙️ CONFIG SAVED. Disconnecting all miners to apply changes...")
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)
now = time.monotonic()
pools = configured_pools()
first_cooling = next(
(pool for pool in pools if pool_retry_at.get(pool['index'], 0) > now), None
)
if first_cooling:
cooldown_remaining = max(
0, int(pool_retry_at[first_cooling['index']] - now)
)
route_title = f"Pool {first_cooling['index']} cooling down"
route_message = f'Trying the next available pool · retry in {cooldown_remaining}s'
elif last_connected_pool_index:
route_title = f'Pool {last_connected_pool_index} was last selected'
route_message = 'New connections follow the configured priority order'
else:
route_title = 'Priority routing ready'
route_message = 'Pools are tried in order from 1 to 3'
pool_rows = []
for pool in pools:
index = pool['index']
retry_at = pool_retry_at.get(index, 0)
if retry_at > now:
badge_text = f'Retry in {int(retry_at - now)}s'
badge_class = 'retrying'
elif last_connected_pool_index == index:
badge_text = 'Last selected'
badge_class = 'selected'
else:
badge_text = f'Priority {index}'
badge_class = ''
pool_rows.append({
**pool,
'badge_text': badge_text,
'badge_class': badge_class,
})
pool_settings = []
for index in range(1, 4):
suffix = '' if index == 1 else str(index)
pool_settings.append({
'index': index,
'is_primary': index == 1,
'host_key': f'host{suffix}',
'host': config.get(f'host{suffix}', ''),
'port_key': f'port{suffix}',
'port': config.get(f'port{suffix}', config['port']),
'wallet_key': f'wallet{suffix}',
'wallet': config.get(f'wallet{suffix}', ''),
'pass_key': 'pass' if index == 1 else f'pass{index}',
'password': config.get('pass' if index == 1 else f'pass{index}', 'x'),
})
html = dashboard_view.render_dashboard({
'uptime': f'{hours}h {minutes:02}m {seconds:02}s',
'hashrate_str': get_hashrate(),
'stats': stats,
'csrf_token': CSRF_TOKEN,
'first_cooling': first_cooling,
'route_title': route_title,
'route_message': route_message,
'pool_rows': pool_rows,
'pool_settings': pool_settings,
'logs': list(log_history),
'listen_port': LISTEN_PORT,
'web_port': WEB_PORT,
'retry_seconds': MAIN_POOL_RETRY_SECONDS,
})
return web.Response(text=html, content_type='text/html')
async def start_web_server():
validate_web_credentials()
app = web.Application(middlewares=[dashboard_security])
app.router.add_static('/static/', dashboard_view.STATIC_DIR)
app.router.add_get('/', web_dashboard)
app.router.add_post('/update', update_config)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, WEB_HOST, WEB_PORT)
await site.start()
async def main():
await start_web_server()
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())