#!/usr/bin/env node /** * JesusOS ORIGINAL Android Termux → real-time Bitcoin agent v8 (worker timing diagnostics) * * --audit: STRICTLY READ ONLY; no downloads, child processes or pool requests. * --selftest: local SHA256 / source-config sanity only. * --run: conscious owner opt-in to the original 2-hour bounded session. * --run-extended: explicit owner opt-in to an 8-hour monitored session. * * Keeps original 3340 status reporter, auto-reporter and HeavenCoin UNTOUCHED. * Only opens 127.0.0.1:3334 (pool relay) and 127.0.0.1:3345 (status). * Uses existing exact watch-only first address and existing 0600 pool config. * Uses a SHORT 16-character, owner-issued, single-use pairing code (10 min TTL). * The code is exchanged over JesusOS HTTPS for a private device credential, * held in memory only. No 69-character token copied, no wallet keys, and * original 3340 reporter is never touched. Explicit owner opt-in only. * Without an active dedicated device token, launch FAILS CLOSED: no * repeated local-only CPU mining test. A read-only JesusOS HTTPS pairing * check must succeed BEFORE starting any mining process. * Local port and signed-source preflight finishes BEFORE asking for or * consuming a one-use device code. Failure preserves existing pairing. * With device authorization, opted-in agent polls MAIN, receives up to one * bounded 90s 5000 H/s command per UTC hour, and uploads status/receipts. * Mining stops on Ctrl+C, process failure or at 2h (default) / 8h * (explicit extended session). Each CPU work order stays capped at * 90 seconds, 5,000 H/s and at most one work order per UTC hour. * No persistent token, hardware automation or payout promise. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import {spawn} from 'node:child_process'; import net from 'node:net'; const home=process.env.HOME||os.homedir(); const original=path.join(home,'jesusos-bitcoin-mining'); const watchDir=path.join(home,'jesusos-sovereign-wallet'); const cache=path.join(original,'.jesusos-live-pinned-v1'); const PINS={ proxy:{name:'jesusos-stratum-proxy-v1.txt',sha:'5fa74b2366c8ef8d4c7885c9885237fe0ea2d9db36821ce42a72edb9223c45a3'}, miner:{name:'jesusos-owner-cpu-miner-v1.txt',sha:'2cdc072de0f8915250651bca8aae2853136e244fe4373e4926455b2f16f554c4'}, agent:{name:'jesusos-mining-device-agent-v3.txt',sha:'c130f42553d26fbf3d0586dfaeae7e8a7ffcd86bafc0dedc3a3cd2d3f9d0eee4'} }; const sha=b=>crypto.createHash('sha256').update(b).digest('hex'); const timestamp=()=>new Date().toISOString(); const log=(event,more={})=>console.log(JSON.stringify({at:timestamp(),event,...more})); const tokenPattern=/^jmr1_[0-9a-f]{64}$/; const mainFile=path.join(original,'jesusos-pool-settings.env'); const watchFile=path.join(watchDir,'watch.json'); const safeDirectory=(d,onlyOwner=false)=>{ const s=fs.lstatSync(d); if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&(onlyOwner?0o077:0o022))!==0) throw Error('Unsafe or non-directory original workspace: '+path.basename(d)); }; function privateFile(filename,max=8192){ const s=fs.lstatSync(filename); if(!s.isFile()||s.isSymbolicLink()||(s.mode&0o077)!==0||s.size>max) throw Error('Original public-config file missing safe 0600 permissions or valid type: '+path.basename(filename)); return fs.readFileSync(filename,'utf8'); } function parsePool(text){ const fields=new Map(); for(const line of text.split(/\r?\n/)){ if(!line.trim()||line.startsWith('#'))continue; const m=line.match(/^([A-Z][A-Z0-9_]*)=([^\r\n]*)$/); if(!m||fields.has(m[1]))throw Error('Pool settings malformed or duplicated; no mining started.'); fields.set(m[1],m[2]); } const pool={ host:fields.get('STRATUM_HOST'),port:fields.get('STRATUM_PORT'), tls:fields.get('STRATUM_TLS'),worker:fields.get('STRATUM_WORKER') }; if(pool.host!=='stratum.ckpool.org'||pool.port!=='3333'||pool.tls!=='false'|| typeof pool.worker!=='string'||!/^bc1q[a-z0-9]{38,85}$/.test(pool.worker)) throw Error('Original public CKPool configuration does not meet pinned solo-mainnet requirements.'); return pool; } function validatePayout(){ safeDirectory(original); safeDirectory(watchDir,true); const settings=parsePool(privateFile(mainFile)); const data=JSON.parse(privateFile(watchFile,16384)); if(!data||data.schema!=='jesusos.btc.watchonly.bip84.v1'|| data.network!=='mainnet'||typeof data.firstAddress!=='string'|| typeof data.accountXpub!=='string'||!data.accountXpub.startsWith('xpub')) throw Error('Original watch-only manifest invalid. Original wallet never modified.'); if(settings.worker!==data.firstAddress) throw Error('Pool payout worker does NOT match original watch-only receive address. Refusing to mine.'); return settings; } async function canListen(port){ return new Promise(resolve=>{ const s=net.createServer(); s.on('error',()=>resolve(false)); s.listen(port,'127.0.0.1',()=>s.close(()=>resolve(true))); }); } function secretCheck(){ const direct=process.env.JESUSOS_MINING_DEVICE_TOKEN||''; if(direct&&!tokenPattern.test(direct))throw Error('Dedicated device token has invalid format; no mining started.'); return direct||null; } /** Private original Termux short-code prompt. Accept ONLY 16 owner-issued * uppercase base32 characters. No terminal echo. No shell command can be * interpreted as a pairing code. Ctrl+C cancels all operations. */ const pairCodePattern=/^[A-HJ-NP-Z2-9]{16}$/; async function readShortDevicePairCode(){ const input=process.stdin; if(!input.isTTY||!process.stdout.isTTY||typeof input.setRawMode!=='function') return null; process.stdout.write('PASTE 16-character JesusOS pairing CODE ONLY (not command, Enter=submit, Ctrl+C=cancel): '); const previousRaw=Boolean(input.isRaw); return new Promise((resolve,reject)=>{ let code='',finished=false; function cleanup(){ if(finished)return; finished=true; input.off('data',onData); try{input.setRawMode(previousRaw)}catch{} if(!previousRaw)input.pause(); process.stdout.write('\n'); } function onData(chunk){ for(const ch of String(chunk)){ if(ch==='\r'||ch==='\n'){ cleanup(); if(!pairCodePattern.test(code))reject(Error('Expected exactly 16 pairing-code letters/digits FROM JesusOS. Do NOT paste a shell command or the 69-character token here.')); else resolve(code); return; } if(ch==='\u0003'){cleanup();reject(Error('Operator cancelled pairing; no mining started.'));return} if(ch==='\u007f'||ch==='\b'){code=code.slice(0,-1);continue} if(ch==='\u001b'){cleanup();reject(Error('Unexpected terminal escape; pairing cancelled.'));return} if(ch===' '||ch==='-')continue; if(ch>='!'&&ch<='~'){ if(code.length>=24){ cleanup();reject(Error('This prompt takes ONLY the 16-character pairing code shown in JesusOS—not a shell command. Nothing started.'));return; } code+=ch.toUpperCase(); } } } try{input.setRawMode(true);input.setEncoding('utf8');input.on('data',onData);input.resume()} catch{cleanup();reject(Error('Private terminal input unavailable. No miner started.'))} }); } /** Claim a one-use high-entropy short code; only server returns device * credential over HTTPS, in memory. Old 3340 reporter remains valid. */ async function claimShortCode(code){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-short-claim.v1',code}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-short-claim',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(12000), headers:{'Content-Type':'application/json'},body }); }catch{throw Error('JesusOS pairing network unavailable. Nothing started. Generate a new short code and retry.')} if(!response.ok){ throw Error('Short pairing code was invalid, expired or already used (HTTP '+response.status+'). No mining started. Generate a new code in JesusOS.'); } let data; try{data=await response.json()}catch{throw Error('Unexpected pairing response; no mining started')} if(!data||data.schema!=='jesusos.bitcoin.device-short-claim.v1'|| data.authorized!==true||!tokenPattern.test(data.token)|| data.originalLegacyReporterUnchanged!==true||data.noWalletKeysUsed!==true|| data.bitcoinPayoutVerified!==false||data.scope!=='bounded-cpu-stratum') throw Error('Unexpected device authorization; no mining started'); log('owner_short_code_pairing_success',{legacyReporterPreserved:true,privateCredentialNotPrinted:true}); return data.token; } const mode=process.argv[2]||'--audit'; const activeMode=mode==='--run'||mode==='--run-extended'; const maxSessionHours=mode==='--run-extended'?8:2; if(mode==='--selftest'){ if(sha('abc')!=='ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') throw Error('SHA256 selftest failed.'); if(Object.values(PINS).length!==3||new Set(Object.values(PINS).map(x=>x.sha)).size!==3) throw Error('Pinned sources invalid.'); log('selftest_ok',{mode:'local-only',networkRequests:0,spawnedProcesses:0}); process.exit(0); } if(mode!=='--audit'&&!activeMode){ console.error('Use --audit, --selftest, --run (2h), or --run-extended (8h). Only explicit run modes can mine.'); process.exit(2); } let settings,token; try{ settings=validatePayout(); token=secretCheck(); // Prevent the device token from leaking into other spawned processes. delete process.env.JESUSOS_MINING_DEVICE_TOKEN; }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'Configuration invalid');process.exit(2)} const relayFree=await canListen(3334),statusFree=await canListen(3345); const report={ schema:'jesusos.bitcoin.termux-live-agent-readiness.v1', mode:mode==='--audit'?'READ_ONLY_AUDIT':'OPERATOR_OPT_IN', payoutMatchesOriginalWatchOnly:true, soloPool:'stratum.ckpool.org:3333', originalStatus3340:'UNTOUCHED', safeRelay3334Free:relayFree, safeStatus3345Free:statusFree, dedicatedDeviceCredentialProvided:!!token, sessionMaxHours:maxSessionHours, actualReporterCredentialValueNeverPrinted:true, agentMode:token?'existing-device-credential-present': activeMode?'pairing-after-local-and-source-preflight':'not-authorized-no-mining', actualMinerRunning:false, bitcoinPayoutVerified:false, heavenCoinTouched:false }; console.log('=== JesusOS ORIGINAL Bitcoin LIVE miner activation ==='); console.log(JSON.stringify(report,null,2)); if(mode==='--audit'){ console.log('READ ONLY audit completed. No mining, source downloads, process signals or wallet changes.'); process.exit(0); } async function verifyDedicatedDevicePairing(credential){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-pair-check.v1',action:'verify'}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-pair',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(9000), headers:{'Content-Type':'application/json','Authorization':'Bearer '+credential}, body }); }catch{throw Error('Original device pairing service unavailable; no mining started')} if(!response.ok)throw Error('Dedicated device not authorized by JesusOS (HTTP '+response.status+'); no mining started'); let v; try{v=await response.json()}catch{throw Error('Pairing response invalid; no mining started')} if(!v||v.schema!=='jesusos.bitcoin.device-pair-check.v1'||v.authorized!==true|| v.scope!=='bounded-cpu-stratum'||v.originalLegacyReporterUnchanged!==true|| v.physicalDeviceAttested!==false||v.actualHashesVerified!==false|| v.bitcoinPayoutVerified!==false||v.heavenCoinMinted!==false) throw Error('Unexpected pairing response; no mining started'); log('dedicated_device_pair_authorized',{oldReporterUnchanged:true,hardwareNotAttested:true,noPayoutInferred:true}); } if(!relayFree||!statusFree){ console.error('LIVE MINING REFUSED: reserved ports 3334 or 3345 occupied. Existing processes and unclaimed pairing code preserved. Inspect a prior V6 session before restarting.'); process.exit(3); } async function pinnedFile(entry){ await fsp.mkdir(cache,{recursive:true,mode:0o700}); safeDirectory(cache,true); const dest=path.join(cache,entry.name+'.mjs'); try{ const prior=await fsp.readFile(dest); const st=fs.lstatSync(dest); if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o077)!==0||sha(prior)!==entry.sha) throw Error('Pinned local cache file mismatch; original file preserved.'); return dest; }catch(e){if(e?.code!=='ENOENT')throw e} const response=await fetch('https://jesusos.online/'+entry.name,{ redirect:'error',signal:AbortSignal.timeout(12500),cache:'no-store' }); if(!response.ok)throw Error('Pinned original worker source unavailable: '+entry.name); const bytes=Buffer.from(await response.arrayBuffer()); if(bytes.length<1000||bytes.length>25000||sha(bytes)!==entry.sha) throw Error('Pinned source SHA-256 mismatch: '+entry.name+'; refusing execution.'); const tmp=dest+'.tmp.'+process.pid; await fsp.writeFile(tmp,bytes,{flag:'wx',mode:0o600}); if(sha(await fsp.readFile(tmp))!==entry.sha)throw Error('Temporary pinned source readback mismatch.'); await fsp.rename(tmp,dest); return dest; } let paths; try{ paths={ proxy:await pinnedFile(PINS.proxy), miner:await pinnedFile(PINS.miner), agent:await pinnedFile(PINS.agent) }; }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'source validation');process.exit(4)} // Local-only ports AND exact SHA-256 sources have been verified before // consuming the short code. Failed preflight must never revoke an earlier // device key or waste a one-use, ten-minute owner-issued pairing code. if(activeMode){ try{ if(!token){ const code=await readShortDevicePairCode(); if(!code)throw Error('No short pairing code entered. No mining started.'); token=await claimShortCode(code); } await verifyDedicatedDevicePairing(token); }catch(e){console.error('LIVE MINING REFUSED:',e instanceof Error?e.message:'Device pairing failed');process.exit(5)} } let stopping=false; const children=new Set(); const spawnChild=(name,filename,env)=>{ const proc=spawn(process.execPath,[filename,name==='agent'?'--run':'--mine'],{ env,stdio:['ignore','inherit','inherit'] }); children.add(proc); proc.on('error',e=>{log('child_error',{name,code:e.code||'unknown'});stop('child-error')}); proc.on('exit',(code,signal)=>{children.delete(proc); log('child_exited',{name,code,signal:signal||null}); if(!stopping&&name!=='miner')stop('child-exited'); }); return proc; }; function stop(reason){ if(stopping)return; stopping=true; log('live_agent_stopping',{reason,childProcesses:children.size, originalStatus3340:'preserved',heavenCoin:'preserved'}); for(const p of children){try{p.kill('SIGTERM')}catch{}} setTimeout(()=>{for(const p of children){try{p.kill('SIGKILL')}catch{}} process.exit(reason==='operator-signal'||reason==='planned-cap'?0:1) },4500).unref(); if(children.size===0)process.exit(reason==='operator-signal'||reason==='planned-cap'?0:1); } for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>stop('operator-signal')); const withoutToken={...process.env, STRATUM_HOST:settings.host,STRATUM_PORT:settings.port, STRATUM_TLS:settings.tls,STRATUM_WORKER:settings.worker, STRATUM_PASSWORD:'x', LOCAL_STRATUM_PORT:'3334',LOCAL_STRATUM_HOST:'127.0.0.1', STATUS_PORT:'3345',MAX_MINERS:'1'}; delete withoutToken.JESUSOS_MINING_REPORTER_TOKEN; delete withoutToken.JESUSOS_MINING_DEVICE_TOKEN; delete withoutToken.JESUSOS_DEVICE_ALLOW_MINING; const proxy=spawn(process.execPath,[paths.proxy],{env:withoutToken, stdio:['ignore','inherit','inherit']}); children.add(proxy); proxy.on('error',e=>{log('proxy_failed',{code:e.code||'unknown'});stop('proxy-error')}); proxy.on('exit',(code,signal)=>{children.delete(proxy); if(!stopping){log('proxy_exited',{code,signal:signal||null});stop('proxy-exited')} }); const localStatus='http://127.0.0.1:3345/status'; async function getStatus(){ const r=await fetch(localStatus,{headers:{Host:'127.0.0.1:3345'}, cache:'no-store',signal:AbortSignal.timeout(1500)}); if(!r.ok)throw Error('Original live relay status unavailable.'); const j=await r.json(); if(j.schema!=='jesusos.stratum.telemetry.v1')throw Error('Unexpected original status schema.'); return j; } let ready=false; for(let i=0;i<45&&!stopping;i++){ try{await getStatus();ready=true;break}catch{await new Promise(r=>setTimeout(r,250))} } if(!ready){ console.error('LIVE MINING REFUSED: verified relay not available; 3340 and HeavenCoin preserved.'); stop('relay-unavailable'); }else if(!stopping){ log('real_pool_relay_ready',{host:'127.0.0.1',port:3334, statusPort:3345,officialPool:'stratum.ckpool.org:3333', agentMode:'authenticated'}); const monitor=setInterval(async()=>{ if(stopping){clearInterval(monitor);return} try{ const s=await getStatus(); log('live_status',{connected:s.minersConnected,authorized:s.authorized, poolJobs:s.jobs,sharesSubmitted:s.sharesSubmitted, sharesAccepted:s.sharesAccepted,sharesRejected:s.sharesRejected, verifiedBitcoinPayout:false}); }catch{log('live_status_unavailable')} },10000); monitor.unref(); const agentEnvironment={...withoutToken, JESUSOS_VERIFIED_MINER_PATH:paths.miner, JESUSOS_MINING_REPORTER_TOKEN:token, JESUSOS_DEVICE_ALLOW_MINING:'1', JESUSOS_LOCAL_STATUS_URL:localStatus }; // Only the opt-in device agent sees the reporter bearer credential. const agent=spawn(process.execPath,[paths.agent,'--run'],{ env:agentEnvironment,stdio:['ignore','inherit','inherit'] }); children.add(agent); agent.on('error',e=>{log('device_agent_error',{code:e.code||'unknown'});stop('device-agent-error')}); agent.on('exit',(code,signal)=>{children.delete(agent); if(!stopping){log('device_agent_exited',{code,signal:signal||null});stop('device-agent-exited')} }); log('device_agent_enabled',{heartbeatSeconds:60,commandDurationCapSeconds:90, hashRateCap:5000,workOrdersPerUTCExpectedHour:1, reporterCredential:'dedicated-device-token-never-displayed', sessionMaxHours:maxSessionHours}); setTimeout(()=>stop('planned-cap'),maxSessionHours*60*60*1000).unref(); }