#!/usr/bin/env node /** * JesusOS ORIGINAL TERMUX MINING AGENT v1 (Node 20+). * Connects to the current JesusOS MAIN and original local Stratum relay. * No shell commands, no wallet keys, no arbitrary code from commands. * * Requires existing env: JESUSOS_MINING_REPORTER_TOKEN, STRATUM_WORKER, * optionally LOCAL_STRATUM_PORT (original proxy usually 3334). * * Run: * JESUSOS_DEVICE_ALLOW_MINING=1 node jesusos-mining-device-agent-v1.mjs --run * * This replaces the old READ-ONLY mining reporter, not the existing Stratum proxy. * It sends the same telemetry every 60s. It only accepts allowlisted bounded * 90-second mining tasks pre-authorized by JesusOS. Ctrl+C stops future work. * Running the agent does not assure mining income. */ import {createHash} from 'node:crypto'; import {mkdir,writeFile,readFile,rename} from 'node:fs/promises'; import {homedir} from 'node:os'; import {join} from 'node:path'; import {spawn} from 'node:child_process'; const args=new Set(process.argv.slice(2)); const base='https://jesusos.online'; const token=process.env.JESUSOS_MINING_REPORTER_TOKEN||''; const worker=process.env.STRATUM_WORKER||''; const allow=process.env.JESUSOS_DEVICE_ALLOW_MINING==='1'; const local=process.env.JESUSOS_LOCAL_STATUS_URL||'http://127.0.0.1:3340/status'; const minerSource=base+'/jesusos-owner-cpu-miner-v1.txt'; const expectHash='2cdc072de0f8915250651bca8aae2853136e244fe4373e4926455b2f16f554c4'; const agent='jesusos-cpu-mine-v1', action='bounded-cpu-stratum'; const installed=join(homedir(),'.local','share','jesusos','jesusos-owner-cpu-miner-v1.mjs'); const hash=b=>createHash('sha256').update(b).digest('hex'); const stamp=()=>new Date().toISOString(); const log=(kind,body={})=>console.log(JSON.stringify({at:stamp(),kind,...body})); const nap=ms=>new Promise(resolve=>setTimeout(resolve,ms)); const bearer={'Authorization':'Bearer '+token}; let stop=false,busy=false,seen=new Set(),child=null; if(args.has('--selftest')){ const value=Buffer.from('abc'); if(hash(value)!=='ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') throw Error('SHA256 selftest failure'); log('selftest_ok',{mode:'no-execution',authenticated:false}); process.exit(0); } if((args.size!==0)&&(!args.has('--run')||args.size!==1)){ console.error('Use --run (or no arguments from the existing launcher). Mining requires JESUSOS_DEVICE_ALLOW_MINING=1.'); process.exit(2); } if(!/^jmr1_[a-f0-9]{64}$/.test(token))throw Error('Existing JesusOS reporter credential is missing; no new account requested.'); if(!/^http:\/\/(localhost|127\.0\.0\.1):\d+\/status$/.test(local))throw Error('Refusing non-loopback Stratum status'); if(allow&&(!worker||worker.length>230||/[\r\n]/.test(worker)))throw Error('Existing STRATUM_WORKER required for opt-in mining'); const headers={'Content-Type':'application/json',...bearer}; async function fetchPinnedWorker(){ const response=await fetch(minerSource,{redirect:'error',cache:'no-store',signal:AbortSignal.timeout(7500)}); if(!response.ok)throw Error('Worker fetch HTTP '+response.status); const b=Buffer.from(await response.arrayBuffer()); if(b.length<1000||b.length>20000||hash(b)!==expectHash)throw Error('Verified Bitcoin worker fingerprint mismatch'); await mkdir(join(homedir(),'.local','share','jesusos'),{recursive:true,mode:0o700}); const tmp=installed+'.tmp.'+process.pid; await writeFile(tmp,b,{mode:0o600}); await rename(tmp,installed); if(hash(await readFile(installed))!==expectHash)throw Error('Worker local readback fingerprint mismatch'); log('worker_verified',{sha256:expectHash}); } function validCommand(c){ return c&&typeof c==='object'&&!Array.isArray(c)&& c.schema==='jesusos.bitcoin.device-command.v1'&& typeof c.id==='string'&&/^[1-9]\d{0,16}$/.test(c.id)&& c.action===action&&c.maxSeconds===90&&c.maxHashesPerSecond===5000&& typeof c.expiresAt==='string'&&Number.isFinite(Date.parse(c.expiresAt))&& Date.parse(c.expiresAt)>Date.now()&&Date.parse(c.expiresAt){ // Never pass reporter bearer credentials to a hashing process. const {JESUSOS_MINING_REPORTER_TOKEN:_privateReporter, JESUSOS_DEVICE_ALLOW_MINING:_privateAuthorization, ...safeEnvironment}=process.env; const env={...safeEnvironment,LOCAL_STRATUM_PORT:process.env.LOCAL_STRATUM_PORT||'3334', JESUSOS_MINING_SECONDS:String(c.maxSeconds), JESUSOS_HASHES_PER_SECOND:String(c.maxHashesPerSecond)}; const mine=spawn(process.execPath,[installed,'--mine'],{stdio:['ignore','pipe','pipe'],env}); child=mine; let err='',partial='',foundPoolJob=false,reportedFinished=null,timedOut=false,wasStopped=false; let observedHashes=0,observedShares=0; mine.stdout.setEncoding('utf8'); mine.stderr.setEncoding('utf8'); mine.stdout.on('data',d=>{ partial=(partial+d).slice(-25000); let pos; while((pos=partial.indexOf('\n'))>=0){ const line=partial.slice(0,pos);partial=partial.slice(pos+1); let event;try{event=JSON.parse(line)}catch{continue;} if(event?.event==='pool_job')foundPoolJob=true; if(event?.event==='finished'){ reportedFinished=event; if(Number.isSafeInteger(event.hashes)&&event.hashes>=0)observedHashes=event.hashes; if(Number.isSafeInteger(event.shareSubmitted)&&event.shareSubmitted>=0)observedShares=event.shareSubmitted; } } }); mine.stderr.on('data',d=>{err=(err+d).slice(-1000);}); const killer=setTimeout(()=>{timedOut=true;mine.kill('SIGTERM')},(c.maxSeconds+10)*1000); mine.on('error',e=>{clearTimeout(killer);child=null;resolve({success:false,detail:'worker process error: '+String(e.code||'unknown')});}); mine.on('close',code=>{clearTimeout(killer);child=null; // A successful process exit is NOT proof of shares or payout. The relay reports shares separately. wasStopped=stop; const validWork=foundPoolJob&&observedHashes>0&&code===0&&!timedOut&&!wasStopped; log('bounded_session_ended',{commandId:c.id,code,foundPoolJob,hashes:observedHashes, sharesSubmitted:observedShares,timedOut,operatorStopped:wasStopped, actualPoolBalanceVerified:false,actualPayoutVerified:false}); resolve({success:validWork,detail:validWork? 'CPU hashed '+observedHashes+' nonces and submitted '+observedShares+' shares; pool credit and BTC payout unverified': 'no confirmed bounded hashing completion ('+(timedOut?'time cap':wasStopped?'operator stopped': !foundPoolJob?'no pool job':observedHashes===0?'zero hashes':'worker exit '+String(code))+ '); '+err.slice(-80)}); }); }); } async function runCommand(c){ if(!allow||busy||stop||!validCommand(c)||seen.has(c.id)){ log('command_ignored',{reason:'not-consented-busy-invalid-or-duplicate'});return; } seen.add(c.id);busy=true; try{ // Validate pinned source EVERY commanded session: remote command may not choose a script. await fetchPinnedWorker(); await acknowledge(c,'started','bounded CPU session started, evidence pending'); const r=await mineChild(c); await acknowledge(c,r.success?'finished':'failed',r.detail); }catch(e){ log('command_failed',{reason:e.message}); try{await acknowledge(c,'failed','local device agent failed: '+e.message.slice(0,170));}catch{} }finally{busy=false;} } async function oneHeartbeat(){ const localResult=await fetch(local,{redirect:'error',cache:'no-store',signal:AbortSignal.timeout(3500)}); if(!localResult.ok)throw Error('Original local Stratum status HTTP '+localResult.status); const body=await localResult.text();if(body.length>8192)throw Error('Local status too large'); const status=JSON.parse(body); if(status.schema!=='jesusos.stratum.telemetry.v1')throw Error('Original Stratum relay schema mismatch'); const h={...headers,...(allow?{'X-JesusOS-Device-Capability':agent}:{})}; const r=await fetch(base+'/_api/bitcoin-mining-report',{ method:'POST',headers:h,body,redirect:'error',signal:AbortSignal.timeout(9000)}); if(!r.ok)throw Error('Original JesusOS telemetry POST HTTP '+r.status); const response=await r.json(); log('telemetry_uploaded',{miners:status.minersConnected,jobs:status.jobs, sharesSubmitted:status.sharesSubmitted,sharesAccepted:status.sharesAccepted, agentEligible:allow}); if(response.deviceCommand){ if(!allow){log('unconsented_command_refused');return;} void runCommand(response.deviceCommand); } } for(const sig of ['SIGINT','SIGTERM'])process.on(sig,()=>{ stop=true; if(child)child.kill('SIGTERM'); }); log('original_device_agent_start',{miningEnabled:allow,reportIntervalSeconds:60}); while(!stop){ try{await oneHeartbeat()}catch(e){log('report_or_command_error',{message:e.message})} if(!stop)await nap(60000); } log('original_device_agent_stopped');