#!/usr/bin/env node /** * JesusOS BTC wallet V2: OFFLINE owner backup verification and local recovery. * Works with V1 watch-only account on ORIGINAL Android Termux. * * Zero seed phrases/private keys written/uploaded; no requests, no keys in argv. * The 24 mnemonic words are requested with TTY echo disabled, used to prove * correspondence with the watch-only public xpub, and discarded. * Does NOT spend/sign/broadcast BTC. Never touches HeavenCoin or other processes. */ import fs from 'node:fs'; import path from 'node:path'; import {spawnSync} from 'node:child_process'; import {createInterface} from 'node:readline/promises'; import {mnemonicToSeedSync,validateMnemonic} from '@scure/bip39'; import {wordlist} from '@scure/bip39/wordlists/english.js'; import {HDKey} from '@scure/bip32'; import {bech32} from '@scure/base'; import {sha256} from '@noble/hashes/sha2.js'; import {ripemd160} from '@noble/hashes/legacy.js'; const home=process.env.HOME||''; const folder=path.join(home,'jesusos-sovereign-wallet'); const manifest=path.join(folder,'watch.json'); const pool=path.join(home,'jesusos-bitcoin-mining','jesusos-pool-settings.env'); const path84="m/84'/0'/0'"; const command=process.argv[2]||'--help'; function safeDir(){ if(!home||home==='/')throw Error('Original Termux HOME is missing.'); const s=fs.lstatSync(folder); if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&0o077)!==0)throw Error('Untrusted wallet folder or permissions.'); } function addr(account,index){ if(!Number.isSafeInteger(index)||index<0||index>999999)throw Error('Invalid address index.'); const child=account.derive('m/0/'+index); if(!child.publicKey||child.publicKey.length!==33)throw Error('Missing BIP84 key.'); return bech32.encode('bc',[0,...bech32.toWords(ripemd160(sha256(child.publicKey)))]); } function fromWords(words){ const normalized=words.trim().toLowerCase().replace(/\s+/g,' '); if(!validateMnemonic(normalized,wordlist)||normalized.split(' ').length!==24)throw Error('The 24 words are not a valid BIP39 English recovery phrase. No records changed.'); const seed=mnemonicToSeedSync(normalized); try{ const acc=HDKey.fromMasterSeed(seed).derive(path84); return {xpub:acc.publicExtendedKey,firstAddress:addr(HDKey.fromExtendedKey(acc.publicExtendedKey),0)}; }finally{seed.fill(0)} } function readPublic(){ safeDir(); const st=fs.lstatSync(manifest); if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)!==0||st.size>8192)throw Error('Public wallet manifest is not a safe private file.'); const d=JSON.parse(fs.readFileSync(manifest,'utf8')); if(d.schema!=='jesusos.btc.watchonly.bip84.v1'||d.network!=='mainnet'||d.path!==path84|| !Number.isSafeInteger(d.nextIndex)||d.nextIndex<1||d.nextIndex>999999)throw Error('Unexpected Bitcoin wallet manifest schema.'); const pub=HDKey.fromExtendedKey(d.accountXpub); if(pub.privateKey||addr(pub,0)!==d.firstAddress)throw Error('Public receiving address and xpub do not match.'); if(d.backupVerifiedAt&&(!Number.isFinite(Date.parse(d.backupVerifiedAt))||typeof d.backupVerifiedAt!=='string'))throw Error('Invalid backup verification timestamp.'); return {d,pub}; } function store(d,createOnly){ safeDir(); const temp=path.join(folder,'.jesusos-watch-'+process.pid+'-'+Date.now()+'.tmp'); let fd; try{ if(createOnly&&fs.existsSync(manifest))throw Error('Existing wallet manifest preserved. Refusing to overwrite.'); fd=fs.openSync(temp,'wx',0o600); fs.writeFileSync(fd,JSON.stringify(d,null,2)+'\n',{encoding:'utf8'}); fs.fsyncSync(fd); fs.closeSync(fd);fd=undefined; if(createOnly&&fs.existsSync(manifest))throw Error('Existing wallet appeared during recovery; refusing to overwrite.'); fs.renameSync(temp,manifest); }finally{ if(fd!==undefined)fs.closeSync(fd); try{fs.unlinkSync(temp)}catch{} } } async function promptVisible(label){ const rl=createInterface({input:process.stdin,output:process.stdout}); try{return (await rl.question(label)).trim()} finally{rl.close()} } async function hiddenWords(){ if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error('Original interactive Termux terminal required; no phrase accepted.'); const s=spawnSync('stty',['-g'],{stdio:['inherit','pipe','pipe']}); if(s.status!==0)throw Error('TTY cannot disable echo safely; refusing to read recovery words.'); const prior=s.stdout.toString().trim(); const hidden=spawnSync('stty',['-echo'],{stdio:'inherit'}); if(hidden.status!==0)throw Error('TTY echo protection unavailable.'); const restore=()=>spawnSync('stty',[prior],{stdio:'inherit'}); const onSignal=()=>{restore();process.stdout.write('\nCanceled; TTY restored.\n');process.exit(130)}; process.once('SIGINT',onSignal);process.once('SIGTERM',onSignal); const rl=createInterface({input:process.stdin,terminal:false}); try{ process.stdout.write('\nEnter all 24 words privately, IN ORDER, on ONE line. They will NOT appear on the screen.\n'); process.stdout.write('Secret words (input hidden; Enter when finished): '); const v=await rl.question(''); process.stdout.write('\n'); if(v.length>360)throw Error('Unexpectedly long recovery input.'); return v; }finally{ rl.close();restore(); process.off('SIGINT',onSignal);process.off('SIGTERM',onSignal); } } function walletStatus(){ console.log('=== JesusOS BTC owner wallet status (LOCAL) ==='); try{ const {d}=readPublic(); console.log('Original watch-only Bitcoin wallet: PRESENT'); console.log('BIP84 receiving address #0: '+d.firstAddress); console.log('Handwritten recovery verified against original account: '+(d.backupVerifiedAt?'YES (self-checked on this original device)':'NOT YET VERIFIED')); console.log('Backup check date: '+(d.backupVerifiedAt||'none')); console.log('Next public address index: '+d.nextIndex); const config=fs.existsSync(pool)?fs.readFileSync(pool,'utf8'):''; console.log('Original solo-pool public identity matches address #0: '+(config.includes('STRATUM_HOST=stratum.ckpool.org')&&config.includes('STRATUM_WORKER='+d.firstAddress)?'YES':'NO / not inspected')); console.log('Wallet sending/signing: NOT IMPLEMENTED. Bitcoin balance and payout: NOT VERIFIED.'); }catch(e){ if(e.code==='ENOENT')console.log('Original watch-only wallet: NOT CREATED / MANIFEST ABSENT.'); else{console.error('Original watch-only wallet requires review: '+e.message);process.exitCode=2} } } async function verify(){ console.log('=== JesusOS BTC 24-word OFFLINE paper-backup check ==='); const {d}=readPublic(); console.log('This check is local. No wallet account, ChatGPT API, or remote service is used.'); console.log('NEVER enter words in this chat, JesusOS web page, screenshot, browser, clipboard or file.'); console.log('Disable screen recording and use your original private Termux session.'); const phrase=await hiddenWords(); let candidate; try{candidate=fromWords(phrase)} catch{ console.error('The entered recovery phrase failed BIP39 validation. No wallet files changed. Recheck the paper words privately.'); process.exitCode=3;return; } if(candidate.xpub!==d.accountXpub||candidate.firstAddress!==d.firstAddress){ console.error('BACKUP MISMATCH. No wallet files changed. Do not direct payouts to this wallet until the paper backup is correct.'); process.exitCode=3;return; } // Re-read to detect accidental replacement while entering words. const fresh=readPublic().d; if(fresh.accountXpub!==d.accountXpub||fresh.firstAddress!==d.firstAddress)throw Error('Wallet changed during verification; refusing to save result.'); store({...fresh,backupVerifiedAt:new Date().toISOString()},false); console.log('PASS: complete 24-word paper backup mathematically regenerates the ORIGINAL BTC account and first receiving address.'); console.log('Only this on-device verification timestamp was saved. Phrase/private keys NOT stored.'); console.log('Wallet still cannot send/sign BTC; no funds, mining or wallet keys moved.'); } async function recover(){ console.log('=== JesusOS BTC restore watch-only receiving wallet from PAPER ==='); if(fs.existsSync(manifest))throw Error('Existing watch-only wallet preserved; do not restore over it.'); safeDir(); console.log('Recovery words will be entered privately in the original Termux TTY; no external service.'); const phrase=await hiddenWords(); let candidate; try{candidate=fromWords(phrase)} catch{console.error('BIP39 recovery phrase invalid; no wallet file created.');process.exitCode=3;return} const {xpub,firstAddress}=candidate; console.log('Recovered BTC mainnet PUBLIC address: '+firstAddress); console.log('This restore saves only public watch-only data. Signing/spending is still NOT implemented.'); const approve=await promptVisible('Type RESTORE if this matches your original public BTC receiving address (otherwise cancel): '); if(approve!=='RESTORE'){console.log('Restoration canceled; no wallet saved.');return} store({schema:'jesusos.btc.watchonly.bip84.v1',network:'mainnet',path:path84, accountXpub:xpub,firstAddress,nextIndex:1,createdAt:new Date().toISOString(), backupVerifiedAt:new Date().toISOString(),restoreMode:'owner-entered-offline-paper-backup'},true); console.log('RESTORED: original paper seed was converted to watch-only public BTC data locally.'); console.log('Recovery phrase NOT saved. No funds transferred and no new Bitcoin address secret generated.'); } function selftest(){ const known12='abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; const checkSeed=mnemonicToSeedSync(known12); let knownAddress; try{ const acct=HDKey.fromMasterSeed(checkSeed).derive(path84); knownAddress=addr(HDKey.fromExtendedKey(acct.publicExtendedKey),0); }finally{checkSeed.fill(0)} if(knownAddress!=='bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu')throw Error('Published BIP84 12-word vector failed'); const test='abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art'; const {xpub,firstAddress}=fromWords(test); if(!firstAddress.startsWith('bc1q')||xpub.slice(0,4)!=='xpub'||fromWords(test).firstAddress!==firstAddress)throw Error('BIP39/BIP84 mismatch'); try{fromWords(test.replace('art','wrong'));throw Error('invalid mnemonic incorrectly accepted')} catch(e){if(e.message==='invalid mnemonic incorrectly accepted')throw e} console.log('PASS: BIP39 24-word BIP84 deterministic derivation and invalid-phrase rejection.'); console.log('No wallet or recovery material saved by selftest.'); } if(command==='--selftest')selftest(); else if(command==='--audit')walletStatus(); else if(command==='--verify-backup')await verify(); else if(command==='--restore')await recover(); else console.log('JesusOS BTC wallet V2: --selftest | --audit | --verify-backup | --restore\nNo BTC sending, signing, transfers, keys stored, or external networks.');