#!/usr/bin/env node /** * JesusOS MAIN / original Android Termux: bind an OWNER-CONTROLLED public * Bitcoin receiving address to the existing, isolated mining connection. * * No private keys, no seeds, no new wallets, no automatic mining, no * reporter-token rotation. Never changes running services or HeavenCoin. * Public address only; validated with Base58Check, BIP173 and BIP350. */ import fs from 'node:fs'; import path from 'node:path'; import net from 'node:net'; import {createHash} from 'node:crypto'; import readline from 'node:readline/promises'; const HOME=process.env.HOME||''; const dir=path.join(HOME,'jesusos-bitcoin-mining'); const config=path.join(dir,'jesusos-pool-settings.env'); const hasher=x=>createHash('sha256').update(x).digest(); const hash2=x=>hasher(hasher(x)); const base58='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; const charset='qpzry9x8gf2tvdw0s3jn54khce6mua7l'; function validBase58(s){ if(s.length<26||s.length>35||!(s[0]==='1'||s[0]==='3'))return false; let v=0n; for(const c of s){const n=base58.indexOf(c);if(n<0)return false;v=v*58n+BigInt(n)} const nums=[]; while(v>0n){nums.unshift(Number(v&255n));v>>=8n} const n=s.match(/^1*/)[0].length; const raw=Buffer.from([...Array(n).fill(0),...nums]); return raw.length===25&&[0,5].includes(raw[0])&&hash2(raw.subarray(0,21)).subarray(0,4).equals(raw.subarray(21)); } function polymod(values){ let c=1; const generators=[0x3b6a57b2,0x26508e6d,0x1ea119fa,0x3d4233dd,0x2a1462b3]; for(const value of values){ const top=c>>>25; c=((c&0x1ffffff)<<5)^value; for(let i=0;i<5;i++)if((top>>i)&1)c^=generators[i]; } return c>>>0; } function fiveToEight(values){ let value=0,bits=0;const output=[]; for(const x of values){ if(x<0||x>31)return null; value=(value<<5)|x;bits+=5; while(bits>=8){bits-=8;output.push((value>>bits)&255)} } if(bits>=5||(value<<(8-bits)&255)!==0)return null; return output; } function validBech(s){ if(s.length<14||s.length>90||(s!==s.toLowerCase()&&s!==s.toUpperCase()))return false; s=s.toLowerCase(); const p=s.lastIndexOf('1'); if(s.slice(0,p)!=='bc'||p!==2)return false; const d=[]; for(const c of s.slice(p+1)){const n=charset.indexOf(c);if(n<0)return false;d.push(n)} if(d.length<7)return false; const c=polymod([3,3,0,2,3,...d]); const version=d[0]; const bytes=fiveToEight(d.slice(1,-6)); if(!bytes||version>16||bytes.length<2||bytes.length>40)return false; return version===0?(c===1&&(bytes.length===20||bytes.length===32)):c===0x2bc830a3; } function validAddress(s){return validBase58(s)||validBech(s)} function masked(a){return a.slice(0,5)+'…'+a.slice(-5)} function safeReadConfig(){ try{ const stat=fs.lstatSync(config); if(stat.isSymbolicLink()||!stat.isFile()||stat.size>8192)return {state:'uninspectable'}; const str=fs.readFileSync(config,'utf8'); const m=str.match(/^STRATUM_WORKER=([^\r\n]*)$/m); const host=str.match(/^STRATUM_HOST=([^\r\n]*)$/m); if(m&&validAddress(m[1])&&host?.[1]==='stratum.ckpool.org')return {state:'ready',address:m[1]}; return {state:'existing-other-config'}; }catch(e){if(e.code==='ENOENT')return {state:'missing'};return {state:'uninspectable'}} } async function subscribeOnly(){ return new Promise(resolve=>{ let settled=false; const done=o=>{if(settled)return;settled=true;clearTimeout(timer);s.destroy();resolve(o)}; const s=net.connect({host:'stratum.ckpool.org',port:3333}); const timer=setTimeout(()=>done('pool unreachable or timed out; settings still preserved'),6500); let buffer=''; s.on('connect',()=>s.write(JSON.stringify({id:1,method:'mining.subscribe',params:['JesusOS-ReadOnly-Preflight/1.0']})+'\n')); s.on('data',d=>{ buffer+=d.toString('utf8'); const i=buffer.indexOf('\n'); if(i>=0){ try{ const m=JSON.parse(buffer.slice(0,i)); done(m.id===1&&Array.isArray(m.result)?'CKPool live Stratum subscription confirmed':'pool response received, handshake not confirmed'); }catch{done('pool replied with invalid JSON')} }else if(buffer.length>8192)done('oversize pool response'); }); s.on('error',e=>done('cannot connect to real pool: '+(e.code||'unknown network error'))); s.on('close',()=>done('pool connection closed without result')); }); } const args=new Set(process.argv.slice(2)); if(args.has('--selftest')){ const cases=[ ['legacy-valid','1BoatSLRHtKNngkdXEeobR76b53LETtpyT',true], ['legacy-invalid','1BoatSLRHtKNngkdXEeobR76b53LETtpyU',false], ['segwit-valid','bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4',true], ['segwit-invalid','bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t3',false], ['taproot-valid','bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0',true], ['taproot-invalid','bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqh2y7hd',false], ['token-not-address','REPLACE_WITH_JESUSOS_MINING_REPORTER_TOKEN',false] ]; for(const [name,v,correct]of cases)if(validAddress(v)!==correct)throw Error('selftest FAIL: '+name); console.log('PASS: 7 wallet-address checks (Base58Check, BIP173, BIP350); no files changed'); process.exit(0); } console.log('=== JesusOS MAIN · original Termux owner BTC payout binding ==='); console.log('HeavenCoin, status port 3340, and old reporter are never modified.'); console.log('Bitcoin wallet private keys and recovery phrases must NEVER be entered.'); if(!fs.existsSync(dir)){console.error('Original mining directory not found. Nothing changed.');process.exit(2)} const state=safeReadConfig(); if(state.state==='ready'){ console.log('READY: original CKPool settings already exist; receiving address',masked(state.address)); console.log('No new wallet or config created. Owner custody is not independently verified.'); console.log('Run existing pinned mining reconciler only when you consent to CPU work.'); process.exit(0); } if(state.state!=='missing'){ console.log('BLOCKED: a different or unreadable original pool settings file already exists.'); console.log('We will not overwrite, rotate or replace the original configuration.'); process.exit(4); } if(args.has('--audit')){ console.log('MISSING: existing named pool settings. No file created.'); process.exit(0); } if(!process.stdin.isTTY){ console.log('No interactive terminal; no settings created. Run in the existing Termux session.'); process.exit(0); } const rl=readline.createInterface({input:process.stdin,output:process.stdout}); let address=''; try{ console.log('To receive any future mainnet BTC, the receiving address MUST belong to a wallet YOU control.'); console.log('Use the public Bitcoin mainnet RECEIVE address from your existing or trusted wallet app.'); console.log('If you have no wallet, press Enter. JesusOS does not invent keys or receive money on your behalf.'); address=(await rl.question('Paste your PUBLIC Bitcoin receive address (Enter cancels): ')).trim(); if(!address){console.log('No wallet address supplied. No files or processes changed.');process.exit(0)} if(!validAddress(address)){console.log('BLOCKED: invalid Bitcoin mainnet address checksum. Nothing saved.');process.exit(2)} console.log('Valid Bitcoin mainnet address checksum:',masked(address)); const own=(await rl.question('Can YOU recover and spend from the wallet controlling this address? Type YES: ')).trim(); if(own!=='YES'){console.log('No ownership confirmation. Nothing saved.');process.exit(0)} const consent=(await rl.question('Bind this address as the payout identity to official Solo CKPool stratum.ckpool.org:3333 (lottery mining, no guaranteed income)? Type YES: ')).trim(); if(consent!=='YES'){console.log('Solo pool not selected. Nothing saved.');process.exit(0)} }finally{rl.close()} const content=[ 'STRATUM_HOST=stratum.ckpool.org', 'STRATUM_PORT=3333', 'STRATUM_TLS=false', 'STRATUM_WORKER='+address, '' ].join('\n'); try{ const fd=fs.openSync(config,'wx',0o600); try{fs.writeFileSync(fd,content,{encoding:'utf8'});fs.fsyncSync(fd)} finally{fs.closeSync(fd)} }catch(e){ console.error(e.code==='EEXIST'?'Original settings appeared concurrently; NOTHING overwritten.':'Failed to create owner-only public settings file: '+e.code); process.exit(3); } console.log('SUCCESS: original pool settings created with permissions 0600 (public address only).'); console.log('No private keys, seeds, reporter tokens or wallet passwords stored.'); console.log('Real-pool read-only connection check:',await subscribeOnly()); console.log('Next: run the EXISTING jesusos-termux-mining-reconcile-v3.mjs to opt in to a bounded 90-second mining test.'); console.log('No mining started automatically. Zero BTC rewards asserted.');