#!/usr/bin/env node /** JesusOS original Android mining reconciler v3, Node >=20. * First inventories existing Termux state without changing processes/files. * Then reuses an EXISTING configured pool; if missing, a single private * interactive opt-in can select public solo CKPool with the owner's address. * No wallet keys, seed phrases, mining reporter credentials or custody. * This tool NEVER touches other running Java/Node/HeavenCoin processes. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import path from 'node:path'; import http from 'node:http'; import net from 'node:net'; import crypto from 'node:crypto'; import {spawn} from 'node:child_process'; import readline from 'node:readline/promises'; const dir=path.join(process.env.HOME||'','jesusos-bitcoin-mining'); const base='https://jesusos.online'; const pinnedFile='jesusos-termux-pool-test-with-legacy-v2.pinned.sh'; const pinnedHash='c40082dec4003b4e78d1ae06ccc6bc2e1395681b40c9a777ea1a5b9f0f73427d'; const expectedAgent='e89784ae28eadfc95a7c24d188498ca5b5b84d5812bcb7cb7c44ca700c34a831'; const names=new Set(['STRATUM_HOST','STRATUM_POOL_HOST','STRATUM_PORT','STRATUM_POOL_PORT','STRATUM_TLS','STRATUM_WORKER','STRATUM_POOL_WORKER','STRATUM_PASSWORD']); const candidateScripts=new Set(['jesusos-stratum-proxy.mjs','jesusos-local-status.mjs','jesusos-auto-reporter.mjs','jesusos-mining-launch.mjs','jesusos-stratum-monitor.mjs','jesusos-original-pinned-stratum-proxy.mjs']); const sha=b=>crypto.createHash('sha256').update(b).digest('hex'); const entries=[]; function extract(o){ const p={}; for(const k of names){if(typeof o[k]==='string'&&o[k].trim())p[k]=o[k].trim();} return p; } function add(name,settings){if(Object.keys(settings).length)entries.push({name,settings});} function parsePairs(raw){ const o={}; for(const line of raw.split('\n')){ const m=line.match(/^\s*(?:export\s+)?(STRATUM_(?:POOL_)?(?:HOST|PORT|WORKER)|STRATUM_TLS|STRATUM_PASSWORD)\s*=\s*(.*?)\s*$/); if(!m)continue; let v=m[2]; if((v[0]==='"'&&v.at(-1)==='"')||(v[0]==="'"&&v.at(-1)==="'"))v=v.slice(1,-1); else v=v.replace(/\s+#.*$/,''); if(v.length<256)o[m[1]]=v; } return extract(o); } function looksLikeSecretOrPlaceholder(value){ return /(?:token|private|secret|api[_.-]?key|bearer|password|replace[_-]?me|placeholder)/i.test(value)|| /^jmr1_[a-f0-9]{64}$/i.test(value); } function get(o,k,alt){ const value=o[k]||o[alt]||''; return (k==='STRATUM_WORKER'&&looksLikeSecretOrPlaceholder(value))?'':value; } function normalized(o){ const raw=get(o,'STRATUM_HOST','STRATUM_POOL_HOST').trim(); if(!raw)return {error:'no configured pool hostname'}; let host='',port='',tls='',scheme=''; try{ const match=raw.match(/^(stratum\+(?:tcp|ssl|tls)|tcp|ssl|tls):\/\//i); if(match){ scheme=match[1].toLowerCase(); const u=new URL(raw); if(u.username||u.password||u.search||u.hash||(u.pathname&&u.pathname!=='/'))throw Error('credentials/path in pool URL are unsupported'); host=u.hostname;port=u.port; tls=scheme==='stratum+tcp'||scheme==='tcp'?'false':'true'; }else{ const m=raw.match(/^([a-z0-9.-]+)(?::(\d{1,5}))?\/?$/i); if(!m)throw Error('pool host format unrecognized; expected hostname or stratum+tcp://host:port'); host=m[1];port=m[2]||''; } if(!/^[a-z0-9][a-z0-9.-]{1,251}[a-z0-9]$/i.test(host)||!host.includes('.')||/\.\.|^-|-$/.test(host))throw Error('invalid pool DNS hostname'); const configuredPort=get(o,'STRATUM_PORT','STRATUM_POOL_PORT'); port=port||configuredPort||''; const p=Number(port); if(!port||!Number.isInteger(p)||p<1||p>65535) return {host,worker:get(o,'STRATUM_WORKER','STRATUM_POOL_WORKER'),tls,error:'missing or invalid real pool port'}; const configuredTls=o.STRATUM_TLS; tls=tls||(configuredTls==='true'||configuredTls==='false'?configuredTls:''); if(!tls)return {host,port:p,worker:get(o,'STRATUM_WORKER','STRATUM_POOL_WORKER'),error:'TLS mode missing for this pool endpoint'}; const worker=get(o,'STRATUM_WORKER','STRATUM_POOL_WORKER'); if(!worker)return {host,port:p,tls,error:'worker / payout identity not configured'}; if(worker.length>230||/\s/.test(worker)||looksLikeSecretOrPlaceholder(worker)||['test.worker','unit.test','example.worker'].includes(worker))throw Error('invalid/test/secret worker; refusing to mine with a token or placeholder'); if(host==='stratum.ckpool.org'&&!isBtcAddressFormat(worker.split('.')[0]))throw Error('solo CKPool requires an actual Bitcoin payout address as worker'); return {host,port:p,tls,worker,password:o.STRATUM_PASSWORD||'x'}; }catch(e){return {error:e.message||String(e)};} } function isBtcAddressFormat(a){ // This is a syntax prefilter, NOT proof that an address is owned or spendable. return /^(?:bc1[qp][a-z0-9]{11,87}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})$/.test(a)&& a!=='bc1q28kkr5hk4gnqe3evma6runjrd2pvqyp8fpwfzu'; } function redactedWorker(w){ if(!w)return 'none'; if(looksLikeSecretOrPlaceholder(w))return '[REJECTED: token-like placeholder; no value disclosed]'; return '[private; '+w.length+' characters; value never displayed]'; } async function available(port){ return new Promise(resolve=>{ const s=net.createServer();s.once('error',()=>resolve(false)); s.listen(port,'127.0.0.1',()=>s.close(()=>resolve(true))); }); } async function status(port){ return new Promise(resolve=>{ let settled=false; const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}; const req=http.get({hostname:'127.0.0.1',port,path:'/status',timeout:1500},res=>{ let body='';res.on('data',d=>{if(body.length<4096)body+=d}); res.on('end',()=>{ try{ const s=JSON.parse(body); done(s.schema==='jesusos.stratum.telemetry.v1' ?'STATUS reporting (miners='+s.minersConnected+', jobs='+s.jobs+', accepted='+s.sharesAccepted+')' :'HTTP '+res.statusCode+' (unrecognized schema)'); }catch{done('HTTP '+res.statusCode+' (no mining JSON)')} }); res.on('error',()=>done('status stream error')); res.on('close',()=>done('status stream closed')); }); const timer=setTimeout(()=>{req.destroy();done('status timed out')},2500); req.on('error',()=>done('no status response')); req.on('timeout',()=>{req.destroy();done('status timed out')}); }); } console.log('=== JesusOS ORIGINAL Termux mining inventory / recovery v3 ==='); console.log('Mode:',process.argv.includes('--audit')?'READ-ONLY AUDIT':'AUDIT FIRST; no mining until verified config'); if(!fs.existsSync(dir)){console.log('Original mining directory missing:',dir);process.exit(2)} const monitor=['jesusos-local-status.mjs','jesusos-auto-reporter.mjs','jesusos-stratum-proxy.mjs','jesusos-mining-reporter.mjs','jesusos-mining-launch.mjs','jesusos-original-pinned-stratum-proxy.mjs']; for(const name of monitor){ const f=path.join(dir,name); if(fs.existsSync(f)){ let note=''; if(name==='jesusos-mining-reporter.mjs'){ const hash=sha(fs.readFileSync(f)); note=hash===expectedAgent?' [UPGRADED SOURCE INSTALLED]':' [custom or legacy source]'; } console.log('INSTALLED:',name+note); } } add('THIS Termux shell environment',extract(process.env)); for(const f of ['jesusos-pool-settings.env','.env','.env.local','mining.env','pool.env','jesusos-mining.env','../.bashrc','../.profile','../.zshrc']){ const p=path.join(dir,f); try{ const st=fs.statSync(p);if(!st.isFile()||st.size>65536)continue; add('local config '+f,parsePairs(fs.readFileSync(p,'utf8'))); }catch{} } const running=[]; try{ for(const pid of fs.readdirSync('/proc')){ if(!/^\d+$/.test(pid))continue; try{ const args=fs.readFileSync('/proc/'+pid+'/cmdline','utf8').split('\0').filter(Boolean); const script=args.map(x=>path.basename(x)).find(x=>candidateScripts.has(x)); if(!script)continue; const cwd=fs.realpathSync('/proc/'+pid+'/cwd'); if(cwd!==fs.realpathSync(dir))continue; running.push({pid,script}); try{ const o={}; for(const kv of fs.readFileSync('/proc/'+pid+'/environ','utf8').split('\0')){ const i=kv.indexOf('='); if(i>0&&names.has(kv.slice(0,i)))o[kv.slice(0,i)]=kv.slice(i+1); } add('RUNNING '+script+' (PID '+pid+')',extract(o)); }catch{} }catch{} } }catch{} for(const p of running)console.log('RUNNING:',p.script,'PID',p.pid); console.log('RUNNING HeavenCoin: preserved (this tool never modifies any existing process)'); for(const p of [3334,3335,3340,3341,3345]){ const free=await available(p); const s=p===3340||p===3341||p===3345?await status(p):''; console.log('PORT',p,free?'free':'occupied',s); } if(!entries.length)console.log('CONFIG SOURCES: no known Stratum pool settings found in active shell, known files or accessible original processes'); let chosen=null; let partial=null; for(const entry of entries){ const n=normalized(entry.settings); console.log('CONFIG:',entry.name, 'host='+ (n.host||'[missing/invalid]'), 'worker='+redactedWorker(entry.settings.STRATUM_WORKER||entry.settings.STRATUM_POOL_WORKER||''), 'result='+ (n.error||'POOL SETTINGS COMPLETE')); if(!chosen&&!n.error)chosen={...n,source:entry.name}; if(!partial&&(n.host||get(entry.settings,'STRATUM_WORKER','STRATUM_POOL_WORKER')))partial={...n,source:entry.name}; } console.log('AUDIT RESULT:',chosen ?'Existing real-pool settings found (pool authorization NOT verified).' :'NO verified complete real-pool configuration recovered from this device scan.'); if(process.argv.includes('--audit')){ console.log('READ-ONLY audit complete; no files written and no processes stopped.'); process.exit(0); } if(!await available(3334)||!await available(3345)){ console.error('BLOCKED: dedicated test ports 3334 and/or 3345 are already in use. Existing services preserved.'); process.exit(4); } const rl=readline.createInterface({input:process.stdin,output:process.stdout}); let selected=chosen; try{ if(!selected){ if(!process.stdin.isTTY){ console.log('Inventory complete. Real-pool configuration still missing; rerun interactively in original Termux to configure only the missing fields.'); process.exit(0); } if(partial)console.log('Found incomplete pool settings:',partial.source,'— will try to preserve the existing choice.'); if(partial&&partial.host){ const reuse=(await rl.question('Continue your EXISTING pool '+partial.host+' rather than choosing a new pool? [yes/no]: ')).trim().toLowerCase(); if(reuse==='yes'){ const poolPort=partial.port||Number((await rl.question('Missing existing pool PORT (Enter to cancel): ')).trim()); let poolTls=partial.tls; if(!poolTls){ const v=(await rl.question('Does this existing pool port use TLS? [yes/no]: ')).trim().toLowerCase(); poolTls=v==='yes'?'true':v==='no'?'false':''; } const poolWorker=partial.worker||(await rl.question('Existing pool WORKER / public payout identity (Enter to cancel, never a private key): ')).trim(); const recovered=normalized({STRATUM_HOST:partial.host,STRATUM_PORT:String(poolPort),STRATUM_TLS:poolTls,STRATUM_WORKER:poolWorker,STRATUM_PASSWORD:'x'}); if(recovered.error){ console.error('Existing pool still incomplete:',recovered.error,'; stopping safely.'); process.exit(5); } selected={...recovered,source:'operator completion of '+partial.source}; } } if(!selected){ const response=(await rl.question('No complete usable pool config. Use official solo CKPool (stratum.ckpool.org:3333), preserving all existing services? [yes/no]: ')).trim().toLowerCase(); if(response!=='yes'){ console.log('Inventory completed; no mining or process changes.');process.exit(0); } let worker=''; for(const e of entries){ const value=get(e.settings,'STRATUM_WORKER','STRATUM_POOL_WORKER'); if(isBtcAddressFormat(value.split('.')[0])){worker=value;break} } if(!worker){ console.log('Solo CKPool pays only if this device actually finds a Bitcoin block. Tablet CPU mining is vastly too slow for realistic revenue.'); worker=(await rl.question('Enter YOUR existing Bitcoin RECEIVE address here in Termux (never a seed phrase or private key; Enter to stop): ')).trim(); } if(!isBtcAddressFormat(worker.split('.')[0])){ console.error('No valid-looking owner BTC payout address. No mining started; no third-party address substituted.'); process.exit(5); } selected={host:'stratum.ckpool.org',port:3333,tls:'false',worker,password:'x',source:'explicit owner CKPool selection'}; } } }finally{rl.close()} console.log('Selected:',selected.host+':'+selected.port,'TLS='+selected.tls,'worker='+redactedWorker(selected.worker),'source='+selected.source); const localSettings=path.join(dir,'jesusos-pool-settings.env'); if(!fs.existsSync(localSettings)&&process.stdin.isTTY){ const saveRl=readline.createInterface({input:process.stdin,output:process.stdout}); let save=''; try{save=(await saveRl.question('Save ONLY these public pool connection settings locally (mode 0600), to avoid another setup loop? [yes/no]: ')).trim().toLowerCase()} finally{saveRl.close()} if(save==='yes'){ const settings=[ 'STRATUM_HOST='+selected.host, 'STRATUM_PORT='+selected.port, 'STRATUM_TLS='+selected.tls, 'STRATUM_WORKER='+selected.worker, '' ].join('\n'); await fsp.writeFile(localSettings,settings,{mode:0o600,flag:'wx'}); console.log('Saved local non-secret pool and worker settings. No passwords, keys, or tokens stored.'); } } const dst=path.join(process.env.HOME,pinnedFile); let content; if(fs.existsSync(dst)&&sha(fs.readFileSync(dst))===pinnedHash)content=fs.readFileSync(dst); else{ const response=await fetch(base+'/jesusos-termux-pool-test-with-legacy-v2.txt', {redirect:'error',signal:AbortSignal.timeout(20000)}); if(!response.ok)throw Error('Verified JesusOS pool test not reachable, HTTP '+response.status); content=Buffer.from(await response.arrayBuffer()); if(sha(content)!==pinnedHash)throw Error('Pinned script SHA-256 mismatch. Refusing execution.'); await fsp.writeFile(dst,content,{mode:0o600}); await fsp.chmod(dst,0o600); } console.log('PINNED script SHA-256:',sha(content),'PASS'); console.log('Launching bounded original pool verification; status 3340 and HeavenCoin are NOT stopped.'); const child=spawn('bash',[dst],{cwd:dir,env:{...process.env, STRATUM_HOST:selected.host,STRATUM_PORT:String(selected.port), STRATUM_WORKER:selected.worker,STRATUM_TLS:selected.tls, STRATUM_PASSWORD:selected.password,JESUSOS_MINING_SECONDS:'90'}, stdio:'inherit'}); for(const sig of ['SIGINT','SIGTERM'])process.once(sig,()=>child.kill(sig)); const code=await new Promise(resolve=>child.on('exit',(c,s)=>resolve(c??(s?130:1)))); process.exitCode=code;