#!/usr/bin/env node /** * JesusOS MAIN | ORIGINAL Android Termux | BTC wallet->mining read-only audit * and explicitly approved public CKPool payout binding. * * Uses public xpub only. Private 24 words are NEVER requested, accessed, * printed, stored, copied or transmitted. Default --audit makes NO changes. * --bind ONLY creates a missing owner-only public mining settings file after * explicit typed owner consent. Existing files are NEVER overwritten. * No miner, reporter, HeavenCoin process, network client or wallet modified. * Only the optional --probe performs a Stratum subscription over the network. */ import fs from 'node:fs'; import path from 'node:path'; import net from 'node:net'; import {createInterface} from 'node:readline/promises'; import {HDKey} from '@scure/bip32'; import {bech32} from '@scure/base'; import {sha256} from '@noble/hashes/sha2.js'; import {ripemd160} from '@noble/hashes/legacy.js'; import {mnemonicToSeedSync} from '@scure/bip39'; const home=process.env.HOME||''; const w=path.join(home,'jesusos-sovereign-wallet'); const watch=path.join(w,'watch.json'); const mine=path.join(home,'jesusos-bitcoin-mining'); const config=path.join(mine,'jesusos-pool-settings.env'); const command=process.argv[2]||'--audit'; const host='stratum.ckpool.org',port=3333; function file(pathname,limit){ try{ const s=fs.lstatSync(pathname); if(s.isSymbolicLink()||!s.isFile()||s.size>limit||(s.mode&0o077)!==0) throw Error('UNSAFE_FILE_OR_PERMISSIONS'); return fs.readFileSync(pathname,'utf8'); }catch(e){if(e.code==='ENOENT')return null;throw e} } function dir(p,ownerOnly=false){ try{ const s=fs.lstatSync(p); return s.isDirectory()&&!s.isSymbolicLink()&& (ownerOnly?(s.mode&0o077)===0:(s.mode&0o022)===0); }catch(e){if(e.code==='ENOENT')return false;throw e} } function derived(pub,index){ const p=pub.derive('m/0/'+index).publicKey; if(!p||p.length!==33)throw Error('Invalid BIP84 public key'); return bech32.encode('bc',[0,...bech32.toWords(ripemd160(sha256(p)))]); } function getWallet(){ if(!dir(w,true))throw Error('OWNER_WALLET_DIR_NOT_READY'); const s=file(watch,8192); if(s===null)throw Error('PUBLIC_WALLET_NOT_SAVED'); const obj=JSON.parse(s); if(obj.schema!=='jesusos.btc.watchonly.bip84.v1'||obj.path!=="m/84'/0'/0'"|| obj.network!=='mainnet'||!Number.isInteger(obj.nextIndex)||obj.nextIndex<1|| typeof obj.accountXpub!=='string'||typeof obj.firstAddress!=='string') throw Error('PUBLIC_WALLET_MANIFEST_INVALID'); const pub=HDKey.fromExtendedKey(obj.accountXpub); if(pub.privateKey)throw Error('PRIVATE_KEY_IN_PUBLIC_FILE_REFUSED'); const check=derived(pub,0); if(check!==obj.firstAddress)throw Error('PUBLIC_XPUB_ADDRESS_MISMATCH'); if(obj.backupVerifiedAt!==undefined&&(!Number.isFinite(Date.parse(obj.backupVerifiedAt))||typeof obj.backupVerifiedAt!=='string')) throw Error('PAPER_VERIFICATION_RECORD_INVALID'); return {obj,address:check,paperBackupRecorded:typeof obj.backupVerifiedAt==='string'}; } function inspect(){ if(!dir(mine))return {state:'MINING_DIR_NOT_READY'}; const raw=file(config,8192); if(raw===null)return {state:'NO_POOL_SETTINGS_FILE'}; const pairs=new Map(); for(const line of raw.split(/\r?\n/)){ if(!line.trim())continue; const m=line.match(/^([A-Z_][A-Z0-9_]*)=([^\r\n]*)$/); if(!m)continue; if(pairs.has(m[1]))throw Error('DUPLICATE_POOL_KEYS'); pairs.set(m[1],m[2]); } return{state:'EXISTING_CONFIG_PRESERVED', host:pairs.get('STRATUM_HOST')||null, port:pairs.get('STRATUM_PORT')||null, worker:pairs.get('STRATUM_WORKER')||null}; } function masked(a){return a.slice(0,6)+'…'+a.slice(-6)} function report(wal,pool){ console.log('=== JESUSOS MAIN BTC OWNER WALLET TO MINING · READ ONLY STATUS ==='); console.log('Original public watch-only wallet: VERIFIED (BIP84 derivation).'); console.log('Original PUBLIC BTC address:',masked(wal.address)); console.log('Original paper backup locally recorded:',wal.paperBackupRecorded?'YES':'NO'); if(pool.state==='NO_POOL_SETTINGS_FILE'){ console.log('Original mining pool file: NOT CREATED.'); console.log('Pool payout address match: NOT CONFIGURED.'); }else if(pool.state==='MINING_DIR_NOT_READY'){ console.log('Original mining directory: NOT FOUND. No actions taken.'); }else{ console.log('Original mining settings: PRESENT (preserved).'); console.log('Pool endpoint:',pool.host?pool.host+':'+pool.port:'NOT READABLE'); console.log('Pool payout worker:',pool.worker?masked(pool.worker):'MISSING'); console.log('Worker exactly matches verified wallet:',pool.worker===wal.address?'YES':'NO'); console.log('Standard solo CKPool selected:',pool.host===host&&pool.port===String(port)?'YES':'NO'); } console.log('Device shares/pool authorization/block reward: NOT VERIFIED.'); console.log('Bitcoin funds/balance: NOT VERIFIED.'); console.log('Original miner/reporter/HeavenCoin: UNTOUCHED.'); console.log('No secret recovery words, keys, xpub, tokens or full public address transmitted.'); } function openAndSavePublic(wal){ // Refuse to change any existing config, including a dangling symlink. if(!dir(mine))throw Error('MINING_DIR_NOT_READY'); const state=inspect(); if(state.state!=='NO_POOL_SETTINGS_FILE')throw Error('EXISTING_POOL_SETTINGS_PRESERVED'); const content=['STRATUM_HOST='+host,'STRATUM_PORT='+port,'STRATUM_TLS=false', 'STRATUM_WORKER='+wal.address,''].join('\n'); // Android-compatible exclusive-create. Never use fs.linkSync or fs.renameSync. let fd,committed=false; try{ fd=fs.openSync(config,'wx',0o600); fs.writeFileSync(fd,content,'utf8'); fs.fsyncSync(fd);committed=true; }finally{ if(fd!==undefined){ if(!committed){ try{ const own=fs.fstatSync(fd),current=fs.lstatSync(config); if(own.dev===current.dev&&own.ino===current.ino)fs.unlinkSync(config); }catch{} } fs.closeSync(fd); } } return true; } async function bind(wal,pool){ if(pool.state==='MINING_DIR_NOT_READY'){ console.log('STOP: Mining directory missing; no changes.');return; } if(pool.state==='EXISTING_CONFIG_PRESERVED'){ if(pool.worker===wal.address)console.log('ALREADY MATCHED: verified wallet equals existing pool worker. No files changed.'); else console.log('STOP: Existing pool file differs from this public wallet. PRESERVED, never overwritten.'); return; } if(!wal.paperBackupRecorded){ console.log('BLOCKED: Wallet paper recovery verification not recorded. Do not bind an unbacked wallet.');return; } if(!process.stdin.isTTY||!process.stdout.isTTY){ console.log('STOP: Owner interaction in ORIGINAL Termux is required. Nothing changed.');return; } console.log('OPTIONAL: Configure new PUBLIC solo CKPool settings only. This never starts mining.'); console.log('Pool: '+host+':'+port+' (mainnet solo lottery; earning a BTC block with tablet CPU is extraordinarily unlikely).'); console.log('Payout worker:',masked(wal.address)); console.log('No mining will start and no existing files will be overwritten.'); const rl=createInterface({input:process.stdin,output:process.stdout}); let reply=''; try{reply=(await rl.question('Approve writing this one missing public settings file? Type YES, otherwise skip: ')).trim().toUpperCase()} finally{rl.close()} if(reply!=='YES'){console.log('SKIPPED BY OWNER. Nothing changed.');return} openAndSavePublic(wal); console.log('SUCCESS: Saved original PUBLIC pool payout settings (0600).'); console.log('Verified worker equals original watch-only wallet first receiving address.'); console.log('No hashing, network connection, token rotation or funds transferred.'); } async function preflight(wal,pool){ if(pool.state!=='EXISTING_CONFIG_PRESERVED'||pool.worker!==wal.address||pool.host!==host||pool.port!==String(port)){ console.log('PRECHECK BLOCKED: verified wallet does not exactly match active original CKPool settings.');return } if(!process.stdin.isTTY){console.log('PRECHECK BLOCKED: original owner terminal required.');return} const rl=createInterface({input:process.stdin,output:process.stdout});let allow=''; try{allow=(await rl.question('Open public solo CKPool network subscription to check endpoint? Type YES: ')).trim().toUpperCase()} finally{rl.close()} if(allow!=='YES'){console.log('No network test requested.');return} const res=await new Promise(resolve=>{ let done=false;const socket=net.createConnection({host,port}); const finish=x=>{if(done)return;done=true;clearTimeout(timer);socket.destroy();resolve(x)}; const timer=setTimeout(()=>finish('TIMEOUT_NO_PROOF'),7000); let buffer=''; socket.on('connect',()=>socket.write(JSON.stringify({id:1,method:'mining.subscribe',params:['JesusOS-PublicPreflight/1.0']})+'\n')); socket.on('data',b=>{buffer+=b.toString('utf8');if(buffer.length>16384)return finish('OVERSIZE_RESPONSE'); const at=buffer.indexOf('\n');if(at<0)return; try{const packet=JSON.parse(buffer.slice(0,at));finish(packet.id===1&&Array.isArray(packet.result)?'SUBSCRIPTION_CONFIRMED':'RESPONSE_NOT_CONFIRMED')}catch{finish('INVALID_POOL_RESPONSE')} }); socket.on('error',e=>finish('CONNECTION_FAILED_'+(e.code||'UNKNOWN'))); socket.on('close',()=>finish('CLOSED_BEFORE_HANDSHAKE')); }); console.log('Public Stratum subscription result:',res); console.log('Subscription alone is NOT miner authorization, share acceptance or payment.'); } try{ if(!['--audit','--bind','--probe','--selftest'].includes(command))throw Error('Unknown command: use --audit, --bind, --probe or --selftest.'); if(command==='--selftest'){ const publicTest='abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; const bytes=mnemonicToSeedSync(publicTest); let account; try{account=HDKey.fromMasterSeed(bytes).derive("m/84'/0'/0'").publicExtendedKey} finally{bytes.fill(0)} const m=HDKey.fromExtendedKey(account); if(m.privateKey||derived(m,0)!=='bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu') throw Error('Official BIP84 public derivation test vector failed'); console.log('PASS: official public BIP84 receive-address vector. No wallet or pool files touched.'); }else{ const wallet=getWallet(),pool=inspect(); report(wallet,pool); if(command==='--bind')await bind(wallet,pool); if(command==='--probe')await preflight(wallet,pool); } }catch(e){ console.error('JesusOS wallet->mining STOPPED:',e instanceof Error?e.message:'UNKNOWN'); process.exitCode=2; }