#!/usr/bin/env node /** * JesusOS owner opt-in Bitcoin Stratum V1 SHA256d CPU worker. * Connects ONLY to the owner's LOCAL Stratum relay (loopback); NO wallet access. * --selftest: Bitcoin genesis header double-SHA-256 reference test, no network. * --diagnose (default): checks the local relay TCP port, does not hash. * --mine: opt-in capped hashing against genuine jobs from an authorized relay. * A valid share is NOT a payout. Phone CPU work is exceedingly unlikely to earn BTC. * Node 20+. Review source before running; Ctrl+C always stops. */ import net from 'node:net'; import readline from 'node:readline'; import {createHash,randomBytes} from 'node:crypto'; const args = new Set(process.argv.slice(2)); const worker = process.env.STRATUM_WORKER || ''; const host = '127.0.0.1'; const port = Number(process.env.LOCAL_STRATUM_PORT || 3335); const seconds = Number(process.env.JESUSOS_MINING_SECONDS || 90); const cap = Number(process.env.JESUSOS_HASHES_PER_SECOND || 10000); const date = () => new Date().toISOString(); const log = (event, extra = {}) => console.log(JSON.stringify({at:date(),event,...extra})); const sha256d = bytes => createHash('sha256').update(createHash('sha256').update(bytes).digest()).digest(); const isHex = (s,bytes) => typeof s==='string' && s.length===bytes*2 && /^[0-9a-f]*$/i.test(s); const fourReversed = hex => {if(!isHex(hex,4))throw Error('Invalid four-byte header field');return Buffer.from(hex,'hex').reverse();}; const wordSwap32 = hex => {if(!isHex(hex,32))throw Error('Invalid previous block hash'); const b=Buffer.from(hex,'hex');for(let i=0;i<32;i+=4)b.subarray(i,i+4).reverse();return b;}; // Bitcoin pool difficulty 1 (bdiff), not full-network difficulty. const DIFF1=BigInt('0x00000000ffff0000000000000000000000000000000000000000000000000000'); function targetForDifficulty(d){ if(typeof d!=='number'||!Number.isFinite(d)||d<=0||d>1e12)throw Error('Invalid pool share difficulty'); const scale=1000000000n; const scaled=BigInt(Math.max(1,Math.round(d*Number(scale)))); return (DIFF1*scale)/scaled; } const reversedHashNumber=b=>BigInt('0x'+Buffer.from(b).reverse().toString('hex')); function makeHeader(job,ex1,ex2){ const [id,prev,cb1,cb2,branches,version,bits,ntime] = job; if(typeof id!=='string'||id.length>256||!isHex(prev,32)||!isHex(version,4)||!isHex(bits,4)||!isHex(ntime,4)|| typeof cb1!=='string'||typeof cb2!=='string'||!/^([a-f0-9]{2})*$/i.test(cb1)||!/^([a-f0-9]{2})*$/i.test(cb2)|| cb1.length+cb2.length>8000||!Array.isArray(branches)||branches.length>64||!branches.every(s=>isHex(s,32))) throw Error('Invalid Stratum mining job'); const coinbase=Buffer.from(cb1+ex1+ex2+cb2,'hex'); let root=sha256d(coinbase); for(const branch of branches)root=sha256d(Buffer.concat([root,Buffer.from(branch,'hex')])); return Buffer.concat([fourReversed(version),wordSwap32(prev),root,fourReversed(ntime),fourReversed(bits),Buffer.alloc(4)]); } const genesisHeader=Buffer.from('01000000'+'00'.repeat(32)+'3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a'+'29ab5f49'+'ffff001d'+'1dac2b7c','hex'); const genesisHash=Buffer.from(sha256d(genesisHeader)).reverse().toString('hex'); if(args.has('--selftest')){ if(genesisHash!=='000000000019d6689c085ae165831e93'+'4ff763ae46a2a6c172b3f1b60a8ce26f')throw Error('Bitcoin double-SHA256 self-test failed'); log('selftest_pass',{genesisHash});process.exit(0); } if(args.has('--mine')===args.has('--diagnose')){ console.error('Choose exactly one: --diagnose (read-only) OR --mine (opt-in CPU work). --selftest available.');process.exit(2); } if(!Number.isInteger(port)||port<1||port>65535||!Number.isInteger(seconds)||seconds<5||seconds>300|| !Number.isInteger(cap)||cap<100||cap>100000|| (args.has('--mine')&&(!worker||worker.length>240||/[\r\n]/.test(worker)))){ console.error('Invalid LOCAL_STRATUM_PORT, JESUSOS_MINING_SECONDS (5..300), JESUSOS_HASHES_PER_SECOND (100..100000), or STRATUM_WORKER');process.exit(2); } const socket=net.connect({host,port}); socket.setTimeout(320000); const setupTimer=setTimeout(()=>{if(!done&&!authorized)finish('mining-setup-timeout',1);},20000); setupTimer.unref(); let done=false,subscribed=false,authorized=false,ex1='',ex2len=0; let noJobTimer=null; let pendingDifficulty=1,job=null,queuedJob=null,jobSerial=0,looping=false,nonce=0,shareSubmitted=0,accepted=0,rejected=0,hashes=0; let startedAt=0,periodHashes=0,periodAt=Date.now(),msgId=10; const inFlight=new Set(); function finish(reason,exitCode=0){if(done)return;done=true;if(noJobTimer)clearTimeout(noJobTimer);log('finished',{reason,hashes,shareSubmitted,accepted,rejected,elapsedSeconds:startedAt?Math.round((Date.now()-startedAt)/1000):0});socket.destroy();process.exitCode=exitCode;} function send(msg){if(done||socket.destroyed)return;socket.write(JSON.stringify(msg)+'\n');} function resetJob(params){ if(!subscribed||!authorized)return; if(noJobTimer){clearTimeout(noJobTimer);noJobTimer=null;} try{ if(!Array.isArray(params)||params.length<8)throw Error('Incomplete Stratum job'); const extranonce2=randomBytes(ex2len).toString('hex'); const header=makeHeader(params,ex1,extranonce2); const target=targetForDifficulty(pendingDifficulty); job={id:params[0],header,ntime:params[7],ex2:extranonce2,target,serial:++jobSerial};nonce=0; log('pool_job',{difficulty:pendingDifficulty,jobId:String(params[0]).slice(0,64)}); if(!looping)void hashLoop(); }catch(e){log('invalid_job',{error:e.message});finish('invalid-job',1)} } async function hashLoop(){ if(looping||!args.has('--mine'))return;looping=true; try{ while(!done&&Date.now()-startedAtsetTimeout(r,100));continue;} const current=job; const start=Date.now();let count=0; while(!done&¤t===job&&count0xffffffff){finish('nonce-space-exhausted');break;} current.header.writeUInt32LE(nonce,76); const result=sha256d(current.header); if(reversedHashNumber(result)<=current.target){ const n=nonce;const id=++msgId;inFlight.add(id); send({id,method:'mining.submit',params:[worker,current.id,current.ex2,current.ntime,n.toString(16).padStart(8,'0')]}); shareSubmitted++; log('share_submitted',{jobId:String(current.id).slice(0,64),nonce:n,shares:shareSubmitted}); } nonce++;hashes++;periodHashes++;count++; } const targetDelay=Math.ceil(1000*count/cap); await new Promise(r=>setTimeout(r,Math.max(1,targetDelay-(Date.now()-start)))); if(Date.now()-periodAt>=10000){const ms=Date.now()-periodAt;log('hashing',{hashes,hashRateEstimate:Math.round(periodHashes*1000/ms),sharesSubmitted:shareSubmitted,sharesAccepted:accepted,sharesRejected:rejected});periodAt=Date.now();periodHashes=0;} } // Let already-submitted shares receive the pool's response before teardown. // No additional hashes are attempted in this short acknowledgement window. if(!done){await new Promise(r=>setTimeout(r,1200));finish('time-cap');} }catch(e){log('hash_error',{message:e.message});finish('hash-error',1)} finally{looping=false;} } const lines=readline.createInterface({input:socket,crlfDelay:Infinity}); lines.on('line',line=>{ if(done)return; if(line.length>65536){finish('oversized-pool-response',1);return;} let m;try{m=JSON.parse(line)}catch{finish('invalid-pool-response',1);return;} if(m.id===1){ if(m.error||!Array.isArray(m.result)||!isHex(m.result[1],m.result[1]?.length/2)||!Number.isSafeInteger(m.result[2])||m.result[2]<1||m.result[2]>16){finish('subscribe-rejected',1);return;} ex1=m.result[1];ex2len=m.result[2];subscribed=true; log('subscribed',{extranonce2Bytes:ex2len}); if(args.has('--mine'))send({id:2,method:'mining.authorize',params:[worker,'x']}); else finish('read-only-connectivity-verified'); return; } if(m.id===2){if(m.result===true&&!m.error){authorized=true;startedAt=Date.now();log('pool_authorized',{seconds,hashRateCap:cap});noJobTimer=setTimeout(()=>{if(!done&&!job)finish('no-pool-job',1)},15000);noJobTimer.unref();if(queuedJob){const fresh=queuedJob;queuedJob=null;resetJob(fresh);}}else finish('pool-worker-not-authorized',1);return;} if(m.id!=null&&inFlight.delete(m.id)){ if(m.result===true&&!m.error){accepted++;log('share_accepted',{accepted});}else{rejected++;log('share_rejected',{rejected});} return; } if(m.method==='mining.set_difficulty'){try{pendingDifficulty=Number(m.params?.[0]);targetForDifficulty(pendingDifficulty);}catch{finish('invalid-difficulty',1);}return;} if(m.method==='mining.notify'){ if(!authorized){ // Pool may send the first job immediately before authorization response. if(Array.isArray(m.params))queuedJob=m.params;return; } resetJob(m.params);return; } if(m.method==='client.reconnect'){finish('pool-requested-reconnect',1);return;} }); socket.on('connect',()=>{ log('local_relay_connected',{host,port,mode:args.has('--mine')?'opt-in-cpu-work':'diagnose-only'}); send({id:1,method:'mining.subscribe',params:['JesusOS-Owner-CPU/1.0']}); }); socket.on('timeout',()=>finish('relay-idle-timeout',1)); socket.on('error',e=>{log('relay_error',{code:e.code||'unknown'});finish('relay-connection-error',1)}); socket.on('close',()=>finish('relay-disconnected',args.has('--mine')?1:0)); for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>finish('operator-stopped'));