#!/usr/bin/env node /** * JesusOS Bitcoin Sovereign Wallet V3 — original Android Termux only. * BIP84 index-0 P2WPKH offline transaction planning and signing. * Depends on OWNER's existing original V1 watch-only public wallet and * 24-word PAPER recovery (never uploaded or written to any file). * * SECURITY LIMITATIONS: Unaudited local wallet. Test with tiny amounts only. * This is not a Bitcoin full node. Public Esplora services report UTXOs; they * may lie or omit data. Requires two services to agree on confirmed UTXO. * No application server, ChatGPT API, custody or private seed database. * All actions are separate opt-in commands. NO broadcast capability exists. */ 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 * as btc from '@scure/btc-signer'; import {bech32,bech32m,base58check} from '@scure/base'; import {sha256} from '@noble/hashes/sha2.js'; const HOME=process.env.HOME||''; const root=path.join(HOME,'jesusos-sovereign-wallet'); const walletFile=path.join(root,'watch.json'); const planFile=path.join(root,'btc-spend-plan-v3.json'); const signedFile=path.join(root,'btc-signed-transaction-v3.json'); const basePath="m/84'/0'/0'"; const services=['https://mempool.space','https://blockstream.info']; const MAX_SATS=21000000*100000000; const MAX_FEE=20000; const requireTty=()=>{if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error('Original interactive Termux TTY required.')}; const safe=(s)=>s.slice(0,7)+'…'+s.slice(-6); const simpleInt=(x,high=MAX_SATS)=>Number.isSafeInteger(x)&&x>=0&&x<=high; function isMainnet(s){ try{ if(typeof s!=='string'||s.length>90||s.length<26||/\s/.test(s))return false; if(s.toLowerCase().startsWith('bc1')){ if(s!==s.toLowerCase()&&s!==s.toUpperCase())return false; s=s.toLowerCase(); try{ const b=bech32.decode(s,90),pr=bech32.fromWords(b.words.slice(1)); if(b.prefix==='bc'&&b.words[0]===0&&(pr.length===20||pr.length===32))return true; }catch{} const b=bech32m.decode(s,90),pr=bech32m.fromWords(b.words.slice(1)); return b.prefix==='bc'&&b.words[0]>=1&&b.words[0]<=16&&pr.length>=2&&pr.length<=40; } const buf=base58check(sha256).decode(s); return buf.length===21&&(buf[0]===0||buf[0]===5); }catch{return false} } function ensureOriginalDir(){ if(!HOME||HOME==='/')throw Error('Cannot detect original Termux HOME'); const st=fs.lstatSync(root); if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)!==0)throw Error('Unsafe wallet directory or permissions'); } function safeJson(file){ ensureOriginalDir(); const stat=fs.lstatSync(file); if(stat.isSymbolicLink()||!stat.isFile()||stat.size>30000||(stat.mode&0o077)!==0)throw Error('Unsafe original wallet file'); return JSON.parse(fs.readFileSync(file,'utf8')); } function pubAddr(account,branch,index){ if(![0,1].includes(branch)||!simpleInt(index,99999))throw Error('Unexpected BIP84 address index'); const p=btc.p2wpkh(account.derive('m/'+branch+'/'+index).publicKey); return p.address; } function publicWallet(){ const m=safeJson(walletFile); if(m.schema!=='jesusos.btc.watchonly.bip84.v1'||m.path!==basePath||m.network!=='mainnet'||!simpleInt(m.nextIndex,99999))throw Error('Original wallet public manifest schema mismatch'); const key=HDKey.fromExtendedKey(m.accountXpub); if(key.privateKey||pubAddr(key,0,0)!==m.firstAddress)throw Error('Original public receiving wallet mismatch'); return {m,key}; } function writeNew(file,obj){ const json=JSON.stringify(obj,null,2)+'\n'; if(Buffer.byteLength(json)>30000)throw Error('Plan too large'); let fd; try{ fd=fs.openSync(file,fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_WRONLY|fs.constants.O_NOFOLLOW,0o600); fs.writeFileSync(fd,json);fs.fsyncSync(fd); }finally{if(fd!==undefined)fs.closeSync(fd)} } function prompt(text){ requireTty(); return new Promise(resolve=>{ const r=createInterface({input:process.stdin,output:process.stdout}); r.question(text).then(v=>{r.close();resolve(v.trim())},e=>{r.close();throw e}); }); } async function secretWords(){ requireTty(); const orig=spawnSync('stty',['-g'],{stdio:['inherit','pipe','pipe']}); if(orig.status!==0)throw Error('Could not protect private input'); const setting=orig.stdout.toString().trim(); if(spawnSync('stty',['-echo'],{stdio:'inherit'}).status!==0)throw Error('TTY hiding failed'); const restore=()=>spawnSync('stty',[setting],{stdio:'inherit'}); const stop=()=>{restore();process.stdout.write('\nPrivate input cancelled.\n');process.exit(130)}; process.once('SIGINT',stop);process.once('SIGTERM',stop); const r=createInterface({input:process.stdin,terminal:false}); try{ process.stdout.write('Enter 24 PRIVATE paper recovery words on one hidden line. NEVER share them: '); const phrase=await r.question(''); process.stdout.write('\n'); if(phrase.length>350)throw Error('Private recovery input too long'); return phrase; }finally{ r.close();restore();process.off('SIGINT',stop);process.off('SIGTERM',stop); } } function accountFromSeed(phrase){ const words=phrase.trim().toLowerCase().replace(/\s+/g,' '); if(words.split(' ').length!==24||!validateMnemonic(words,wordlist))throw Error('Invalid 24-word BIP39 recovery'); const seed=mnemonicToSeedSync(words); try{return HDKey.fromMasterSeed(seed).derive(basePath)} finally{seed.fill(0)} } async function getJson(url){ const response=await fetch(url,{headers:{Accept:'application/json'},signal:AbortSignal.timeout(9000),redirect:'error'}); if(!response.ok)throw Error('Read-only explorer HTTP '+response.status); const length=Number(response.headers.get('content-length')); if(Number.isFinite(length)&&length>100000)throw Error('Remote response unexpectedly large'); const body=await response.text(); if(body.length>100000)throw Error('Remote response unexpectedly large'); return JSON.parse(body); } function normalizeUtxos(list,height){ if(!Array.isArray(list)||list.length>1000||!simpleInt(height,15000000))throw Error('Invalid explorer UTXO data'); const result=new Map(); for(const u of list){ if(typeof u.txid!=='string'||!/^[0-9a-f]{64}$/.test(u.txid)||!simpleInt(u.vout,10000)|| !simpleInt(u.value)||!u.status||typeof u.status!=='object')throw Error('Explorer UTXO record malformed'); if(u.status.confirmed!==true||!simpleInt(u.status.block_height,height))continue; const confirmations=height-u.status.block_height+1; if(confirmations<6)continue; const key=u.txid+':'+u.vout; if(result.has(key))throw Error('Explorer duplicate outpoint'); result.set(key,{txid:u.txid,vout:u.vout,value:u.value,confirmations}); } return result; } function validatePlan(p,manifest,account){ if(p.schema!=='jesusos.bitcoin.spend.plan.v3'||p.network!=='bitcoin-mainnet')throw Error('Unexpected plan'); if(p.walletAddress!==manifest.firstAddress||p.inputAddress!==manifest.firstAddress)throw Error('Plan wallet changed'); if(!isMainnet(p.recipient)||p.recipient===manifest.firstAddress)throw Error('Invalid or identical destination'); if(p.changeAddress!==pubAddr(account,1,0)||p.changeIndex!==0)throw Error('Change must be original BIP84 internal index 0'); if(!/^[a-f0-9]{64}$/.test(p.txid)||!simpleInt(p.vout,10000)||!simpleInt(p.inputSats)||!simpleInt(p.sendSats)|| !simpleInt(p.feeSats,MAX_FEE)||!simpleInt(p.changeSats)||!simpleInt(p.confirmations,1000000))throw Error('Invalid unsigned plan amounts'); if(p.sendSats<1000||p.changeSats<546||p.confirmations<6||p.feeSats<1||p.feeSats>p.sendSats/10)throw Error('Unsafe BTC spend amounts or fee'); if(p.sendSats+p.changeSats+p.feeSats!==p.inputSats)throw Error('Plan accounting not balanced'); if(typeof p.createdAt!=='string'||!Number.isFinite(Date.parse(p.createdAt))|| Date.now()-Date.parse(p.createdAt)>3600000||Date.parse(p.createdAt)>Date.now()+60000)throw Error('Plan expired; regenerate with current network data'); return p; } async function prepare(){ requireTty(); if(fs.existsSync(planFile)||fs.existsSync(signedFile))throw Error('Prior spend plan or signed transaction exists. No overwrite; review or archive it first.'); const {m,key}=publicWallet(); if(!m.backupVerifiedAt)throw Error('Complete the V2 verified paper-backup check before any signing'); console.log('=== JesusOS BTC MAINNET · prepare ONE confirmed input; NO private keys ==='); console.log('Public explorers will see your Bitcoin receiving address. Continue only with consent.'); const approval=await prompt('Type CHECK to query two external public explorers: '); if(approval!=='CHECK'){console.log('No public address requests or changes.');return} const recipient=await prompt('Recipient PUBLIC Bitcoin mainnet address: '); if(!isMainnet(recipient)||recipient===m.firstAddress)throw Error('Invalid or self-send recipient; nothing changed'); const sendText=await prompt('Amount to send in SATOSHIS (minimum 1000): '); if(!/^[1-9][0-9]{0,14}$/.test(sendText))throw Error('Invalid send amount'); const amount=Number(sendText); if(!simpleInt(amount)||amount<1000)throw Error('Invalid BTC amount'); const rateText=await prompt('Fee rate, SAT/vbyte (integer 1–25; try 3 on test): '); if(!/^(?:[1-9]|1[0-9]|2[0-5])$/.test(rateText))throw Error('Fee rate outside 1–25 sats/vbyte'); const rate=Number(rateText); const remote=await Promise.all(services.map(async host=>{ const [utxos,tip]=await Promise.all([ getJson(host+'/api/address/'+encodeURIComponent(m.firstAddress)+'/utxo'), fetch(host+'/api/blocks/tip/height',{signal:AbortSignal.timeout(9000),redirect:'error'}).then(async r=>{ if(!r.ok)throw Error('Tip height check failed'); return Number((await r.text()).trim()); }) ]); return {host,utxos:normalizeUtxos(utxos,tip),tip}; })); if(Math.abs(remote[0].tip-remote[1].tip)>2)throw Error('Public explorers disagree on chain tip; plan refused'); const maxFee=160*rate; const changes=pubAddr(key,1,0); let selected; for(const [outpoint,a]of remote[0].utxos){ const b=remote[1].utxos.get(outpoint); if(!b||b.value!==a.value||Math.abs(a.confirmations-b.confirmations)>2)continue; const change=a.value-amount-maxFee; if(change<546||maxFee>MAX_FEE||maxFee>amount/10)continue; if(!selected||a.value160)throw Error('Signed transaction failed fee/accounting/sizing checks'); console.log('Signed BTC transaction ID: '+txn.id); console.log('Fee '+txn.fee+' sats; virtual size '+txn.vsize+' vbytes; actual fee rate '+(Number(txn.fee)/txn.vsize).toFixed(2)+' sats/vbyte.'); const now=await prompt('Type SAVE-SIGNED to write owner-only raw TX and public summary, otherwise discard: '); if(now!=='SAVE-SIGNED'){console.log('No transaction saved or broadcast.');return} const result={schema:'jesusos.bitcoin.signed.tx.v3',txid:txn.id,hex:txn.hex, inputAddress:m.firstAddress,recipient:plan.recipient,sendSats:plan.sendSats, changeAddress:plan.changeAddress,changeSats:plan.changeSats,feeSats:plan.feeSats, inputTxid:plan.txid,inputVout:plan.vout,createdAt:new Date().toISOString(), warning:'Signed raw Bitcoin mainnet transaction; broadcasting can irreversibly transfer funds. No seed stored.'}; writeNew(signedFile,result); console.log('SIGNED TRANSACTION STORED locally in '+signedFile); console.log('NO network contact or transaction broadcast by --sign.'); } async function broadcast(){ console.log('BROADCAST DISABLED: unaudited software must not auto-submit mainnet transactions.'); console.log('A separately reviewed, independently verified broadcast integration is required.'); } function selftest(){ const phrase='abandon '.repeat(23)+'art'; const acc=accountFromSeed(phrase),pub=HDKey.fromExtendedKey(acc.publicExtendedKey); if(!pubAddr(pub,0,0).startsWith('bc1q')||pubAddr(pub,1,0)===pubAddr(pub,0,0))throw Error('BIP84 derivation failure'); const key=acc.derive('m/0/0'),payment=btc.p2wpkh(key.publicKey); const tx=new btc.Transaction(); tx.addInput({txid:'01'.repeat(32),index:0,witnessUtxo:{script:payment.script,amount:100000n}}); tx.addOutputAddress(payment.address,90000n); if(tx.sign(key.privateKey)!==1)throw Error('Synthetic P2WPKH signing failed'); tx.finalize(); const again=btc.Transaction.fromRaw(Buffer.from(tx.hex,'hex')); if(again.id!==tx.id||!again.isFinal||tx.fee!==10000n||again.getOutputAddress(0)!==payment.address)throw Error('Synthetic final transaction mismatch'); console.log('PASS offline BIP84 Bitcoin P2WPKH signature/finalization and raw-tx decode; NO funds or network accessed.'); } const arg=process.argv[2]||'--help'; try{ if(arg==='--selftest')selftest(); else if(arg==='--audit'){ const wallet=publicWallet(); console.log('Original watch-only wallet present:',!!wallet); console.log('Bitcoin receive address index 0:',wallet.m.firstAddress); console.log('Bitcoin internal change address m/84\'/0\'/0\'/1/0:',pubAddr(wallet.key,1,0)); console.log('NOTE: Existing V1 public receive monitor does NOT watch change. Do not treat index-0 balance as total wallet funds.'); console.log('Signed transaction is never published or submitted by JesusOS V3.'); console.log('Unsigned spend plan:',fs.existsSync(planFile)?'present':'none'); console.log('Signed raw transaction:',fs.existsSync(signedFile)?'present (NOT automatically broadcast)':'none'); console.log('Never interprets self-reported telemetry or wallet files as earnings or confirmed BTC.'); }else if(arg==='--prepare')await prepare(); else if(arg==='--sign')await sign(); else if(arg==='--broadcast')await broadcast(); else console.log('JesusOS BTC V3: --selftest | --audit | --prepare | --sign. Broadcast is deliberately DISABLED.'); }catch(e){ console.error('JesusOS BTC V3 stopped safely: '+(e instanceof Error?e.message:'unknown error')); process.exitCode=2; }