|
| 1 | +const http = require('http'); |
| 2 | +const net = require('net'); |
| 3 | +const url = require('url'); |
| 4 | +const { WebSocketServer, WebSocket } = require('ws'); |
| 5 | + |
| 6 | +const PORT = process.env.PORT || 8080; |
| 7 | +const DEFAULT_POOL_HOST = process.env.DEFAULT_POOL_HOST || 'pool.supportxmr.com'; |
| 8 | +const DEFAULT_POOL_PORT = parseInt(process.env.DEFAULT_POOL_PORT || '3333', 10); |
| 9 | + |
| 10 | +// Fallback wallet address for anonymous / unconfigured clients |
| 11 | +const FALLBACK_WALLET = '44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otRmvJMbxJ445678'; |
| 12 | + |
| 13 | +let activeConnections = 0; |
| 14 | +let totalSharesSubmitted = 0; |
| 15 | +let totalSharesAccepted = 0; |
| 16 | + |
| 17 | +// HTTP Server for Health Checks & Diagnostics |
| 18 | +const server = http.createServer((req, res) => { |
| 19 | + const parsedUrl = url.parse(req.url, true); |
| 20 | + |
| 21 | + // Enable CORS |
| 22 | + res.setHeader('Access-Control-Allow-Origin', '*'); |
| 23 | + res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS'); |
| 24 | + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); |
| 25 | + |
| 26 | + if (req.method === 'OPTIONS') { |
| 27 | + res.writeHead(204); |
| 28 | + res.end(); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + if (parsedUrl.pathname === '/' || parsedUrl.pathname === '/health' || parsedUrl.pathname === '/status') { |
| 33 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 34 | + res.end(JSON.stringify({ |
| 35 | + status: 'online', |
| 36 | + service: 'crypto-stratum-ws-proxy', |
| 37 | + defaultPool: `${DEFAULT_POOL_HOST}:${DEFAULT_POOL_PORT}`, |
| 38 | + activeConnections, |
| 39 | + stats: { |
| 40 | + totalSharesSubmitted, |
| 41 | + totalSharesAccepted, |
| 42 | + uptimeSeconds: Math.floor(process.uptime()), |
| 43 | + }, |
| 44 | + time: new Date().toISOString() |
| 45 | + })); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + res.writeHead(404, { 'Content-Type': 'text/plain' }); |
| 50 | + res.end('Not Found'); |
| 51 | +}); |
| 52 | + |
| 53 | +// WebSocket Server attached to the HTTP server |
| 54 | +const wss = new WebSocketServer({ server }); |
| 55 | + |
| 56 | +wss.on('connection', (ws, req) => { |
| 57 | + activeConnections++; |
| 58 | + const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress; |
| 59 | + const parsedUrl = url.parse(req.url || '', true); |
| 60 | + |
| 61 | + // Allow client to request custom pool via query params, e.g. ?pool=zephyr.herominers.com:1123 |
| 62 | + let poolHost = DEFAULT_POOL_HOST; |
| 63 | + let poolPort = DEFAULT_POOL_PORT; |
| 64 | + |
| 65 | + if (parsedUrl.query && parsedUrl.query.pool) { |
| 66 | + const parts = (parsedUrl.query.pool).split(':'); |
| 67 | + if (parts[0]) poolHost = parts[0]; |
| 68 | + if (parts[1]) { |
| 69 | + const p = parseInt(parts[1], 10); |
| 70 | + if (!isNaN(p)) poolPort = p; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + console.log(`[WS] Client connected from ${clientIp} -> Connecting to Stratum Pool ${poolHost}:${poolPort}`); |
| 75 | + |
| 76 | + // Create TCP connection to the mining pool |
| 77 | + const tcpClient = new net.Socket(); |
| 78 | + tcpClient.setKeepAlive(true, 30000); |
| 79 | + tcpClient.setNoDelay(true); |
| 80 | + |
| 81 | + let tcpConnected = false; |
| 82 | + let lineBuffer = ''; |
| 83 | + |
| 84 | + tcpClient.connect(poolPort, poolHost, () => { |
| 85 | + tcpConnected = true; |
| 86 | + console.log(`[TCP] Connected to pool ${poolHost}:${poolPort}`); |
| 87 | + if (ws.readyState === WebSocket.OPEN) { |
| 88 | + ws.send(JSON.stringify({ |
| 89 | + type: 'PROXY_STATUS', |
| 90 | + status: 'CONNECTED', |
| 91 | + pool: `${poolHost}:${poolPort}` |
| 92 | + })); |
| 93 | + } |
| 94 | + }); |
| 95 | + |
| 96 | + // Handle incoming pool data (Line-delimited JSON-RPC) |
| 97 | + tcpClient.on('data', (chunk) => { |
| 98 | + lineBuffer += chunk.toString('utf8'); |
| 99 | + const lines = lineBuffer.split('\n'); |
| 100 | + lineBuffer = lines.pop(); // Keep partial line for next chunk |
| 101 | + |
| 102 | + for (const line of lines) { |
| 103 | + const trimmed = line.trim(); |
| 104 | + if (!trimmed) continue; |
| 105 | + |
| 106 | + try { |
| 107 | + const msg = JSON.parse(trimmed); |
| 108 | + |
| 109 | + // Track shares accepted by pool |
| 110 | + if (msg.result && msg.result.status === 'OK') { |
| 111 | + totalSharesAccepted++; |
| 112 | + } |
| 113 | + |
| 114 | + // Forward Stratum pool response to browser WebSocket |
| 115 | + if (ws.readyState === WebSocket.OPEN) { |
| 116 | + ws.send(trimmed); |
| 117 | + } |
| 118 | + } catch (err) { |
| 119 | + // Raw forwarding if not strict JSON |
| 120 | + if (ws.readyState === WebSocket.OPEN) { |
| 121 | + ws.send(trimmed); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + }); |
| 126 | + |
| 127 | + // Forward browser WebSocket messages to Stratum pool TCP socket |
| 128 | + ws.on('message', (data) => { |
| 129 | + try { |
| 130 | + const str = data.toString('utf8'); |
| 131 | + const parsed = JSON.parse(str); |
| 132 | + |
| 133 | + // Track submissions |
| 134 | + if (parsed.method === 'submit') { |
| 135 | + totalSharesSubmitted++; |
| 136 | + } |
| 137 | + |
| 138 | + // If client didn't supply wallet, fill in default fallback |
| 139 | + if (parsed.method === 'login' && (!parsed.params || !parsed.params.login || parsed.params.login === 'user')) { |
| 140 | + parsed.params = parsed.params || {}; |
| 141 | + parsed.params.login = FALLBACK_WALLET; |
| 142 | + parsed.params.pass = parsed.params.pass || 'x'; |
| 143 | + parsed.params.agent = 'NexusWasmMiner/1.0'; |
| 144 | + } |
| 145 | + |
| 146 | + const formatted = JSON.stringify(parsed) + '\n'; |
| 147 | + |
| 148 | + if (tcpConnected && !tcpClient.destroyed) { |
| 149 | + tcpClient.write(formatted); |
| 150 | + } else { |
| 151 | + // Buffer or wait for connect |
| 152 | + tcpClient.once('connect', () => { |
| 153 | + tcpClient.write(formatted); |
| 154 | + }); |
| 155 | + } |
| 156 | + } catch (e) { |
| 157 | + // Forward raw string with newline |
| 158 | + if (tcpConnected && !tcpClient.destroyed) { |
| 159 | + tcpClient.write(data.toString() + '\n'); |
| 160 | + } |
| 161 | + } |
| 162 | + }); |
| 163 | + |
| 164 | + tcpClient.on('error', (err) => { |
| 165 | + console.warn(`[TCP] Error on connection to ${poolHost}:${poolPort}:`, err.message); |
| 166 | + if (ws.readyState === WebSocket.OPEN) { |
| 167 | + ws.send(JSON.stringify({ |
| 168 | + type: 'PROXY_STATUS', |
| 169 | + status: 'POOL_ERROR', |
| 170 | + error: err.message |
| 171 | + })); |
| 172 | + } |
| 173 | + }); |
| 174 | + |
| 175 | + tcpClient.on('close', () => { |
| 176 | + console.log(`[TCP] Pool connection closed`); |
| 177 | + if (ws.readyState === WebSocket.OPEN) { |
| 178 | + ws.close(); |
| 179 | + } |
| 180 | + }); |
| 181 | + |
| 182 | + ws.on('close', () => { |
| 183 | + activeConnections = Math.max(0, activeConnections - 1); |
| 184 | + console.log(`[WS] Client disconnected`); |
| 185 | + if (!tcpClient.destroyed) { |
| 186 | + tcpClient.destroy(); |
| 187 | + } |
| 188 | + }); |
| 189 | + |
| 190 | + ws.on('error', (err) => { |
| 191 | + console.warn(`[WS] Client error:`, err.message); |
| 192 | + if (!tcpClient.destroyed) { |
| 193 | + tcpClient.destroy(); |
| 194 | + } |
| 195 | + }); |
| 196 | +}); |
| 197 | + |
| 198 | +server.listen(PORT, () => { |
| 199 | + console.log(`=======================================================`); |
| 200 | + console.log(`Crypto Stratum WS Proxy listening on port ${PORT}`); |
| 201 | + console.log(`Default Pool: ${DEFAULT_POOL_HOST}:${DEFAULT_POOL_PORT}`); |
| 202 | + console.log(`Health check: http://localhost:${PORT}/health`); |
| 203 | + console.log(`=======================================================`); |
| 204 | +}); |
0 commit comments