#!/usr/bin/env node /** * JesusOS ORIGINAL TERMUX MINING AGENT v3 — worker-level timing evidence (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 a dedicated owner-authorized device token passed internally as * JESUSOS_MINING_REPORTER_TOKEN, existing STRATUM_WORKER, and the original * launcher's JESUSOS_VERIFIED_MINER_PATH to a private hash-verified worker. * * Start ONLY via JesusOS's checksum-pinned, explicit owner-operated launcher. * Do not manually paste tokens into a shell command. * * Runs beside the old 3340 read-only mining reporter, NEVER replacing it. * It sends separate 3345 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 {lstat,readFile} 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 expectHash='2cdc072de0f8915250651bca8aae2853136e244fe4373e4926455b2f16f554c4'; const agent='jesusos-cpu-mine-v1', action='bounded-cpu-stratum'; const home=process.env.HOME||homedir(); const expectedWorker=join(home,'jesusos-bitcoin-mining','.jesusos-live-pinned-v1','jesusos-owner-cpu-miner-v1.txt.mjs'); const installed=process.env.JESUSOS_VERIFIED_MINER_PATH||''; 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('Original device-agent bearer credential missing; no mining started.'); 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 verifyPinnedWorker(){ if(installed!==expectedWorker)throw Error('Original verified worker path is absent or non-canonical. No mining started.'); const st=await lstat(installed); if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)!==0|| st.size<1000||st.size>20000) throw Error('Verified local worker is unsafe, not private, or unexpectedly sized.'); const bytes=await readFile(installed); if(hash(bytes)!==expectHash)throw Error('Original local miner SHA-256 fingerprint mismatch. No mining started.'); // This v2 agent never downloads, replaces or modifies the old installed // CPU miner in ~/.local/share/jesusos. The original launcher's pinned, // owner-private copy is the ONLY permitted command worker. log('worker_verified',{sha256:expectHash,source:'existing-private-launcher-cache', oldWorkerInstallationTouched:false}); } 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; // Capture the original SHA256d worker's own wall elapsed seconds and // exit reason, not an invented duration based on delayed HTTPS receipts. // This remains the device's claim, NOT a pool acceptance attestation. const workerSeconds=Number.isSafeInteger(reportedFinished?.elapsedSeconds)&& reportedFinished.elapsedSeconds>=0&&reportedFinished.elapsedSeconds<=600 ?reportedFinished.elapsedSeconds:null; const exit=typeof reportedFinished?.reason==='string'&& /^[a-z0-9-]{1,40}$/.test(reportedFinished.reason) ?reportedFinished.reason:'not-captured'; const diagnostic=' worker_elapsed_s='+(workerSeconds??'unknown')+ '; worker_exit='+exit+';'; log('bounded_session_ended',{commandId:c.id,code,foundPoolJob,hashes:observedHashes, sharesSubmitted:observedShares,workerElapsedSeconds:workerSeconds, workerExitReason:exit,timedOut,operatorStopped:wasStopped, actualPoolBalanceVerified:false,actualPayoutVerified:false}); resolve({success:validWork,detail:validWork? 'CPU hashed '+observedHashes+' nonces and submitted '+observedShares+' shares;'+diagnostic+' 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 verifyPinnedWorker(); await acknowledge(c,'started','worker SHA-256 verified; bounded CPU command prepared, actual hashes 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');