#!/usr/bin/env node /** * JesusOS MAIN · Bitcoin paper recovery V8 — accessibility & diagnostics. * Original local Termux only, NEVER any network or background logging. * V8 fixes Android EACCES from filesystem hardlinks by exclusive-create save. * * Rationale: V2 silently rejected the complete 24-word line with one generic * BIP39 error. V8 accepts ONE secret word at a time (input always hidden), * checks each against the official English BIP39 list, shows visible progress, * and if all are real words but the checksum fails, lets the owner correct * individual numbered entries in memory without retyping all 24. * * It NEVER creates a new random wallet, accesses existing private keys, sends * seed words to anyone, writes words to disk, prints them, or replaces the * original public watch.json. BIP84 only. Not an audited spending wallet. */ import fs from 'node:fs'; import path from 'node:path'; import {spawnSync} from 'node:child_process'; import {createInterface} from 'node:readline/promises'; import {validateMnemonic,mnemonicToSeedSync} 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 dir=path.join(home,'jesusos-sovereign-wallet'); const watch=path.join(dir,'watch.json'); const basePath="m/84'/0'/0'"; const wordSet=new Set(wordlist); const mode=process.argv[2]||'--help'; function assertOriginal(){ if(!home||home==='/')throw Error('Original Termux HOME cannot be found.'); const s=fs.lstatSync(dir); if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&0o077)!==0) throw Error('Unsafe original wallet folder, not proceeding.'); if(fs.existsSync(watch)||isSymlinkOrDangling(watch)) throw Error('An original wallet manifest already exists. V8 will NEVER replace it.'); } function isSymlinkOrDangling(p){ try{return fs.lstatSync(p).isSymbolicLink()} catch(e){if(e.code==='ENOENT')return false;throw e} } function address(acc){ const pub=acc.derive('m/0/0').publicKey; if(!pub||pub.length!==33)throw Error('BIP84 public key unavailable'); return bech32.encode('bc',[0,...bech32.toWords(ripemd160(sha256(pub)))]); } function fromWords(words){ const phrase=words.join(' '); if(words.length!==24||!validateMnemonic(phrase,wordlist)) throw Error('24-word BIP39 checksum is invalid.'); const seed=mnemonicToSeedSync(phrase); try{ const account=HDKey.fromMasterSeed(seed).derive(basePath); return {xpub:account.publicExtendedKey,firstAddress:address(HDKey.fromExtendedKey(account.publicExtendedKey))}; }finally{seed.fill(0)} } function savePublic(obj){ assertOriginal(); // Android/Termux can reject hard links (EACCES). V8's fs.linkSync // failed AFTER the phrase and public address were correctly derived. // Use exclusive O_CREAT|O_EXCL ('wx') to create the FINAL public file // directly, WITHOUT hard links and WITHOUT ever replacing an existing // file or symlink. The file contains PUBLIC data only. let fd; let committed=false; const data=JSON.stringify(obj,null,2)+'\n'; try{ fd=fs.openSync(watch,'wx',0o600); fs.writeFileSync(fd,data,{encoding:'utf8'}); fs.fsyncSync(fd); committed=true; }finally{ if(fd!==undefined){ if(!committed){ // Roll back ONLY if watch.json is still the inode we created. // Never delete an unrelated/replaced existing user's wallet. try{ const own=fs.fstatSync(fd),current=fs.lstatSync(watch); if(own.dev===current.dev&&own.ino===current.ino)fs.unlinkSync(watch); }catch{} } fs.closeSync(fd); } } } function ttyControl(){ if(!process.stdin.isTTY||!process.stdout.isTTY) throw Error('Original interactive Termux terminal required; no recovery started.'); const start=spawnSync('stty',['-g'],{stdio:['inherit','pipe','pipe']}); if(start.status!==0)throw Error('Could not verify terminal privacy.'); const prior=start.stdout.toString().trim(); if(spawnSync('stty',['-echo'],{stdio:'inherit'}).status!==0) throw Error('Cannot hide your typing. Refusing recovery.'); let restored=false; const restore=()=>{ if(restored)return;restored=true; spawnSync('stty',[prior],{stdio:'inherit'}); }; const interrupt=()=>{restore();process.stdout.write('\nCANCELED. Secret words not saved.\n');process.exit(130)}; process.on('SIGINT',interrupt);process.on('SIGTERM',interrupt); return()=>{ restore(); process.off('SIGINT',interrupt);process.off('SIGTERM',interrupt); }; } async function recover(){ assertOriginal(); console.log('=== JESUSOS ORIGINAL BITCOIN PAPER RESTORE · ACCESSIBLE V8 ==='); console.log('You can use your 24 ORIGINAL handwritten words from the canceled wallet creator.'); console.log('DO NOT generate new words or send your existing words to ChatGPT / Floot / a web page.'); console.log('Unlike V2, enter ONE WORD at a time. Secret typing is ALWAYS HIDDEN.'); console.log('The terminal will show the word NUMBER and success/error status, never the word itself.'); console.log('If you enter a misspelled word, it will ask you to retry that number.'); console.log('If all words are valid but the checksum fails, you can correct a numbered word.'); console.log('This program DOES NOT clear your screen or modify mining / HeavenCoin.'); const restoreTTY=ttyControl(); const rl=createInterface({input:process.stdin,output:process.stdout,terminal:false}); const words=Array(24).fill(''); try{ let index=0; while(index<24){ const item=String(index+1).padStart(2,'0'); process.stdout.write('\n'); const raw=await rl.question('Word '+item+' of 24 (HIDDEN, Enter after this ONE word): '); process.stdout.write('\n'); const token=raw.trim().toLowerCase().normalize('NFKD'); if(['cancel','stop','exit'].includes(token)){ console.log('CANCELED BY OWNER. NO wallet file created.'); return; } if(!/^[a-z]+$/.test(token)||!wordSet.has(token)){ console.log('WORD '+item+' NOT RECOGNIZED in official BIP39 English wordlist. Nothing saved. Retry this SAME word.'); continue; } words[index]=token; index++; console.log('WORD '+item+' ACCEPTED (private; not displayed). '+index+' / 24 dictionary words collected.'); } let checks=0; while(!validateMnemonic(words.join(' '),wordlist)){ checks++; if(checks>16){ console.log('CHECKSUM UNRESOLVED after 16 corrections. NO wallet saved. Keep original paper safe.'); return; } console.log('\nALL 24 ENTERED WORDS ARE IN THE OFFICIAL BIP39 DICTIONARY.'); console.log('However their ORDER/CHECKSUM does not match. The original paper phrase may still be recoverable.'); console.log('Please compare your HANDWRITTEN numbered words with your original terminal display.'); console.log('DO NOT generate a new seed and DO NOT post any words here.'); const target=(await rl.question('Number to re-enter (1-24) or type CANCEL (input hidden): ')).trim().toLowerCase(); process.stdout.write('\n'); if(['cancel','stop','exit'].includes(target)){ console.log('CANCELED. No public wallet created. Original words remain on your paper.'); return; } if(!/^(?:[1-9]|1\d|2[0-4])$/.test(target)){ console.log('That is not a number 1-24. Try again. No files touched.'); continue; } const slot=Number(target)-1; const raw=await rl.question('Replacement word #'+String(slot+1).padStart(2,'0')+' (HIDDEN): '); process.stdout.write('\n'); const replacement=raw.trim().toLowerCase().normalize('NFKD'); if(!wordSet.has(replacement)){ console.log('Replacement not in BIP39 English wordlist. Original entry kept; no files changed.'); continue; } words[slot]=replacement; console.log('Word #'+String(slot+1).padStart(2,'0')+' replaced privately. Rechecking checksum.'); } const candidate=fromWords(words); const expected=process.argv[3]||''; if(expected){ if(!/^bc1q[a-z0-9]{20,80}$/.test(expected))throw Error('Expected PUBLIC address argument is not a mainnet bc1q address.'); if(candidate.firstAddress!==expected){ console.log('STOP: Derived public address does NOT match expected original PUBLIC address.'); console.log('NOTHING SAVED. Preserve original paper words; no new wallet generated.'); return; } console.log('PASS: Derived address matches expected original PUBLIC address.'); } console.log('\nPASS: all 24 words are dictionary-valid AND BIP39 checksum-valid.'); console.log('Bitcoin mainnet PUBLIC receiving address: '+candidate.firstAddress); console.log("Recovery path: BIP84 m/84'/0'/0'/0/0."); console.log('Compare this PUBLIC address with any original PUBLIC receiving-address record you may have.'); console.log('You are not proving this wallet once held BTC. No blockchain lookup is performed.'); console.log('Only PUBLIC xpub/address can be written after explicit approval.'); const ack=await rl.question('Type RESTORE to save this PUBLIC watch-only wallet (or CANCEL; input hidden): '); process.stdout.write('\n'); if(ack.trim().toUpperCase()!=='RESTORE'){ console.log('NO PUBLIC WALLET SAVED. Original paper words remain yours.'); return; } savePublic({ schema:'jesusos.btc.watchonly.bip84.v1',network:'mainnet',path:basePath, accountXpub:candidate.xpub,firstAddress:candidate.firstAddress, nextIndex:1,createdAt:new Date().toISOString(), backupVerifiedAt:new Date().toISOString(), restoreMode:'owner-entered-private-word-by-word-v8' }); console.log('SUCCESS: ORIGINAL PAPER RECOVERY SAVED (PUBLIC watch-only data ONLY).'); console.log('Your 24 words were not written to disk, uploaded, or printed by this tool.'); console.log('HeavenCoin, miner, reporter, port 3340 unchanged. NO BTC signed or sent.'); }finally{ words.fill(''); rl.close();restoreTTY(); } } function selftest(){ const known=Array(23).fill('abandon').concat(['art']); const candidate=fromWords(known); if(!candidate.firstAddress.startsWith('bc1q')||!wordSet.has('art')||wordSet.has('artt')) throw Error('BIP39 test failed.'); if(validateMnemonic(known.slice(0,23).concat(['zoo']).join(' '),wordlist)) throw Error('Bad checksum accepted.'); console.log('PASS V8 BIP39 24-word dictionary/checksum and BIP84 public derivation.'); console.log('Selftest creates no wallet and uses only a publicly known example phrase.'); } try{ if(mode==='--restore')await recover(); else if(mode==='--selftest')selftest(); else console.log('JesusOS Bitcoin private-paper recovery V8: --restore [optional known PUBLIC bc1q address] | --selftest'); }catch(e){ console.error('JesusOS original paper recovery V8 STOPPED: '+(e instanceof Error?e.message:'unknown error')); process.exitCode=2; }