v1.48.0: auditoría en frío, parche 1 — guarda de red única, secretos en todos los campos, garantías sin comprobar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
// Versión de la app: la usan el pie de página y la cabecera del informe
|
||||
// de seguimiento. Una sola constante para que no se desalineen.
|
||||
const VERSION_APP = "1.47.1";
|
||||
const VERSION_APP = "1.48.0";
|
||||
|
||||
// Detecta pantalla estrecha (móvil) y se reajusta al rotar/redimensionar.
|
||||
// Reutilizable para adaptar cualquier vista a móvil sin media queries CSS.
|
||||
|
||||
+10
-2
@@ -17,6 +17,8 @@
|
||||
// CompactSeedQR: 16 o 32 bytes en binario (llegan como caracteres de control).
|
||||
if ((s.length === 16 || s.length === 32) && /[\u0000-\u0008\u000e-\u001f\u007f-ÿ]/.test(s)) return true;
|
||||
// Clave privada extendida (xprv, yprv, zprv, tprv…) o clave privada WIF.
|
||||
// Semilla con numeración o separadores raros («1. abandon 2. ability…»).
|
||||
if (contieneSemilla(s)) return true;
|
||||
if (/[xyztuvXYZUV]prv[1-9A-HJ-NP-Za-km-z]{100,}/.test(t)) return true;
|
||||
if (/^[5KLc9][1-9A-HJ-NP-Za-km-z]{50,51}$/.test(t)) return true;
|
||||
return false;
|
||||
@@ -52,8 +54,14 @@
|
||||
const xp = t.match(new RegExp(`^(?:\\[([0-9a-fA-F]{8})((?:/\\d+[h']?)*)\\])?(${QR_XPUB})$`));
|
||||
if (xp) return { tipo: "xpub", valor: xp[3], huella: xp[1] ? xp[1].toLowerCase() : null, ruta: xp[2] ? "m" + xp[2] : null };
|
||||
// Descriptor con una xpub dentro: wpkh([…]xpub…/0/*)
|
||||
const desc = t.match(new RegExp(`^(?:wpkh|sh|pkh|tr|wsh)\\(.*?(${QR_XPUB})`));
|
||||
if (desc) return { tipo: "xpub", valor: desc[1], huella: null, ruta: null, descriptor: true };
|
||||
// v1.48.0 (auditoría A2-02): se entrega el descriptor ENTERO, no solo
|
||||
// la xpub de dentro. Antes se perdían el tipo de script, la rama, el
|
||||
// origen y la suma de verificación (que ya no se comprobaba). El campo
|
||||
// de la wallet sabe leer descriptores. Las líneas de comentario del
|
||||
// archivo de Sparrow («# Receive and change descriptor:») se quitan.
|
||||
const sinComentarios = t.split(/\r?\n/).map(l => l.trim()).filter(l => l && !l.startsWith("#")).join("\n");
|
||||
const desc = sinComentarios.match(new RegExp(`^(?:wpkh|sh|pkh|tr|wsh)\\(.*?(${QR_XPUB})`));
|
||||
if (desc) return { tipo: "xpub", valor: sinComentarios, xpub: desc[1], huella: null, ruta: null, descriptor: true };
|
||||
if (/^[0-9a-fA-F]{64}$/.test(t)) return { tipo: "txid", valor: t.toLowerCase() };
|
||||
if (/^0[1-3]000000[0-9a-fA-F]{100,}$/.test(t) && t.length % 2 === 0) return { tipo: "tx", valor: t.toLowerCase() };
|
||||
const dir = normalizarDireccionQR(t);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// ── Lista oficial de palabras BIP-39 (inglés) ───────────────────────
|
||||
// Solo para RECONOCER una semilla pegada por despiste y borrarla sin
|
||||
// procesarla (v1.48.0, auditoría A2-01). Txoko nunca usa semillas.
|
||||
// Copia de la lista oficial (bitcoin/bips, bip-0039/english.txt):
|
||||
// 2048 palabras, SHA-256 del archivo
|
||||
// 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda
|
||||
// (lo comprueba tests/test36.js). Las 4 primeras letras bastan para
|
||||
// distinguir cada palabra (así las escribe SeedSigner).
|
||||
const BIP39_PALABRAS = (
|
||||
"abandon ability able about above absent absorb abstract absurd abuse access accident account accuse " +
|
||||
"achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust " +
|
||||
"admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport " +
|
||||
"aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always " +
|
||||
"amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce " +
|
||||
"annual another answer antenna antique anxiety any apart apology appear apple approve april arch " +
|
||||
"arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist " +
|
||||
"artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract " +
|
||||
"auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful " +
|
||||
"awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely " +
|
||||
"bargain barrel base basic basket battle beach bean beauty because become beef before begin behave " +
|
||||
"behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind " +
|
||||
"biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse " +
|
||||
"blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom " +
|
||||
"bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk " +
|
||||
"broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet " +
|
||||
"bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus " +
|
||||
"cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital " +
|
||||
"captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch " +
|
||||
"category cattle caught cause caution cave ceiling celery cement census century cereal certain chair " +
|
||||
"chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken " +
|
||||
"chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city " +
|
||||
"civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock " +
|
||||
"clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin " +
|
||||
"collect color column combine come comfort comic common company concert conduct confirm congress " +
|
||||
"connect consider control convince cook cool copper copy coral core corn correct cost cotton couch " +
|
||||
"country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy " +
|
||||
"cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise " +
|
||||
"crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion " +
|
||||
"custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris " +
|
||||
"decade december decide decline decorate decrease deer defense define defy degree delay deliver " +
|
||||
"demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design " +
|
||||
"desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet " +
|
||||
"differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss " +
|
||||
"disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate " +
|
||||
"donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink " +
|
||||
"drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn " +
|
||||
"earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder " +
|
||||
"electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ " +
|
||||
"empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy " +
|
||||
"enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode " +
|
||||
"erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact " +
|
||||
"example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit " +
|
||||
"exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade " +
|
||||
"faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue " +
|
||||
"fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber " +
|
||||
"fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit " +
|
||||
"fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly " +
|
||||
"foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil " +
|
||||
"foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel " +
|
||||
"fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic " +
|
||||
"garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift " +
|
||||
"giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow " +
|
||||
"glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape " +
|
||||
"grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar " +
|
||||
"gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard " +
|
||||
"head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire " +
|
||||
"history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host " +
|
||||
"hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid " +
|
||||
"ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose " +
|
||||
"improve impulse inch include income increase index indicate indoor industry infant inflict inform " +
|
||||
"inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside " +
|
||||
"inspire install intact interest into invest invite involve iron island isolate issue item ivory " +
|
||||
"jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle " +
|
||||
"junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite " +
|
||||
"kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later " +
|
||||
"latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal " +
|
||||
"legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life " +
|
||||
"lift light like limb limit link lion liquid list little live lizard load loan lobster local lock " +
|
||||
"logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics " +
|
||||
"machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual " +
|
||||
"maple marble march margin marine market marriage mask mass master match material math matrix matter " +
|
||||
"maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu " +
|
||||
"mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum " +
|
||||
"minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment " +
|
||||
"monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse " +
|
||||
"move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth " +
|
||||
"naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve " +
|
||||
"nest net network neutral never news next nice night noble noise nominee noodle normal north nose " +
|
||||
"notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure " +
|
||||
"observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic " +
|
||||
"omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary " +
|
||||
"organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner " +
|
||||
"oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent " +
|
||||
"park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear " +
|
||||
"peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase " +
|
||||
"physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place " +
|
||||
"planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond " +
|
||||
"pony pool popular portion position possible post potato pottery poverty powder power practice praise " +
|
||||
"predict prefer prepare present pretty prevent price pride primary print priority prison private " +
|
||||
"prize problem process produce profit program project promote proof property prosper protect proud " +
|
||||
"provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push " +
|
||||
"put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack " +
|
||||
"radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor " +
|
||||
"ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse " +
|
||||
"region regret regular reject relax release relief rely remain remember remind remove render renew " +
|
||||
"rent reopen repair repeat replace report require rescue resemble resist resource response result " +
|
||||
"retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle " +
|
||||
"right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof " +
|
||||
"rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle " +
|
||||
"sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save " +
|
||||
"say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script " +
|
||||
"scrub sea search season seat second secret section security seed seek segment select sell seminar " +
|
||||
"senior sense sentence series service session settle setup seven shadow shaft shallow share shed " +
|
||||
"shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug " +
|
||||
"shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing " +
|
||||
"siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice " +
|
||||
"slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow " +
|
||||
"soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort " +
|
||||
"soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice " +
|
||||
"spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze " +
|
||||
"squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo " +
|
||||
"stick still sting stock stomach stone stool story stove strategy street strike strong struggle " +
|
||||
"student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit " +
|
||||
"summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect " +
|
||||
"sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup " +
|
||||
"system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten " +
|
||||
"tenant tennis tent term test text thank that theme then theory there they thing this thought three " +
|
||||
"thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast " +
|
||||
"tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top " +
|
||||
"topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic " +
|
||||
"tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip " +
|
||||
"trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn " +
|
||||
"turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover " +
|
||||
"under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil " +
|
||||
"update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant " +
|
||||
"vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture " +
|
||||
"venue verb verify version very vessel veteran viable vibrant vicious victory video view village " +
|
||||
"vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote " +
|
||||
"voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way " +
|
||||
"wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel " +
|
||||
"when where whip whisper wide width wife wild will win window wine wing wink winner winter wire " +
|
||||
"wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle " +
|
||||
"wrist write wrong yard year yellow you young youth zebra zero zone zoo "
|
||||
).trim().split(" ");
|
||||
const BIP39_SET = new Set(BIP39_PALABRAS);
|
||||
const BIP39_PREFIJOS = new Set(BIP39_PALABRAS.map(p => p.slice(0, 4)));
|
||||
const esPalabraBip39 = p => BIP39_SET.has(p) || (p.length === 4 && BIP39_PREFIJOS.has(p));
|
||||
|
||||
// ¿Hay una semilla en este texto? Doce o más palabras BIP-39 seguidas
|
||||
// (los números de la numeración «1. abandon 2. ability» no cortan la
|
||||
// racha). Un texto normal en castellano no las encadena; en inglés, doce
|
||||
// seguidas de la lista sin nada en medio es casi imposible por azar.
|
||||
function contieneSemilla(texto) {
|
||||
const fichas = String(texto ?? "").toLowerCase().split(/[^a-z0-9]+/).filter(f => f && !/^\d+$/.test(f));
|
||||
let racha = 0;
|
||||
for (const f of fichas) { racha = esPalabraBip39(f) ? racha + 1 : 0; if (racha >= 12) return true; }
|
||||
return false;
|
||||
}
|
||||
// ── fin BIP-39
|
||||
+11
-1
@@ -466,6 +466,16 @@
|
||||
if ([12, 15, 18, 21, 24].includes(pal.length) && pal.every(p => /^[a-z]{3,8}$/.test(p))) return true;
|
||||
return false;
|
||||
};
|
||||
// v1.48.0 (auditoría A2-01): una sola puerta para reconocer secretos en
|
||||
// cualquier campo de texto: clave privada (xprv…, WIF), semilla de 12–24
|
||||
// palabras BIP-39 (también abreviadas a 4 letras, como SeedSigner) y
|
||||
// SeedQR en dígitos. Antes cada campo tenía la suya o ninguna, y la del
|
||||
// campo de la wallet no reconocía las palabras.
|
||||
const esSecretoTexto = (texto) => {
|
||||
const s = String(texto ?? ""), t = s.trim();
|
||||
return contieneClavePrivada(s) || contieneSemilla(s)
|
||||
|| (/^\d+$/.test(t) && t.length >= 48 && t.length <= 96 && t.length % 4 === 0);
|
||||
};
|
||||
const MSG_CLAVE_PRIVADA = "⚠ ESO ES UN SECRETO: lo que has pegado contiene una clave privada o una semilla, y con ella se puede gastar el dinero de esa wallet. Txoko no la necesita ni la acepta: se ha borrado del campo, no se ha procesado y no se ha guardado en ninguna parte. Lo que hace falta es la parte pública: la xpub, o el descriptor sin claves privadas (en Bitcoin Core, listdescriptors sin «true»). Si ese texto ha pasado por sitios que no controlas (un chat, una web, la nube), quien lo viera puede gastar ese dinero.";
|
||||
const MSG_MULTIFIRMA = "Las wallets multifirma todavía no se pueden cargar: sus direcciones dependen de todas las claves a la vez, y la app solo sabe derivar wallets de una firma (wpkh, sh(wpkh) y pkh).";
|
||||
const MSG_TAPROOT = "Ese descriptor es Taproot (tr…, direcciones bc1p…) y todavía no se pueden derivar direcciones Taproot. No se ha cargado nada: calcularlas a medias daría direcciones que no son las tuyas.";
|
||||
@@ -554,7 +564,7 @@
|
||||
const analizarEntradaWallet = async (texto, redApp) => {
|
||||
const t = String(texto ?? "").trim();
|
||||
if (!t) throw errorWallet("Pega una xpub o un descriptor.");
|
||||
if (contieneClavePrivada(t)) throw errorWallet(MSG_CLAVE_PRIVADA, { secreto: true });
|
||||
if (esSecretoTexto(t)) throw errorWallet(MSG_CLAVE_PRIVADA, { secreto: true });
|
||||
|
||||
if (!/[()]/.test(t)) {
|
||||
if (!/^[xyzuvtXYZUV]pub[1-9A-HJ-NP-Za-km-z]{100,}$/.test(t)) throw errorWallet("Introduce una xpub/zpub válida o un descriptor: wpkh(…), sh(wpkh(…)) o pkh(…).");
|
||||
|
||||
@@ -1331,11 +1331,14 @@
|
||||
penalty });
|
||||
if (reused) score -= penalty;
|
||||
const address = addr.address || "";
|
||||
const isTaproot = address.startsWith("bc1p");
|
||||
const isNative = address.startsWith("bc1q");
|
||||
const isLegacy = address.startsWith("1");
|
||||
// v1.48.0 (auditoría A3-05): también las de las redes de pruebas. Antes
|
||||
// una tb1q… de signet caía en «De script (3…)» y se penalizaba con 15.
|
||||
const pre = (address.match(/^(bc1|tb1|bcrt1)/i) || [""])[0].toLowerCase();
|
||||
const isTaproot = !!pre && /^(bc1|tb1|bcrt1)p/i.test(address);
|
||||
const isNative = !!pre && /^(bc1|tb1|bcrt1)q/i.test(address);
|
||||
const isLegacy = /^[1mn]/.test(address);
|
||||
const scriptScore = isTaproot ? 0 : isNative ? 5 : isLegacy ? 20 : 15;
|
||||
checks.push({ id:"script_type", label:"Formato de la dirección", certainty:"CERTEZA", pass:isTaproot||isNative, detail: isTaproot ? "Taproot (bc1p…): el formato más reciente." : isNative ? "SegWit (bc1q…): el formato más común hoy." : isLegacy ? "Antigua (1…): cada vez menos usada, así que destaca más." : "De script (3…): formato intermedio, frecuente en monederos y multifirmas antiguos.", penalty:scriptScore });
|
||||
checks.push({ id:"script_type", label:"Formato de la dirección", certainty:"CERTEZA", pass:isTaproot||isNative, detail: isTaproot ? `Taproot (${pre||"bc1"}p…): el formato más reciente.` : isNative ? `SegWit (${pre||"bc1"}q…): el formato más común hoy.` : isLegacy ? `Antigua (${address[0]}…): cada vez menos usada, así que destaca más.` : `De script (${address[0]||"3"}…): formato intermedio, frecuente en monederos y multifirmas antiguos.`, penalty:scriptScore });
|
||||
score -= scriptScore;
|
||||
if (!utxosConocidas) checks.push({ id:"utxo_count", label:"Monedas sin gastar: no disponible", certainty:null, pass:true, informational:true, detail:"Tu nodo no ha dado la lista de monedas sin gastar de esta dirección y el historial recibido no basta para reconstruirla. No se cuentan, en vez de dar un cero que no se ha comprobado.", penalty:0 });
|
||||
else {
|
||||
|
||||
+58
-4
@@ -2,7 +2,46 @@
|
||||
// Si Fulcrum/Mempool está ocupado (reindexando, mempool llena), la petición
|
||||
// se cancela pasados timeoutMs en lugar de quedarse colgada para siempre.
|
||||
const FETCH_TIMEOUT_MS = 8000;
|
||||
// v1.48.0: TODA petición de la app pasa por aquí (es el único fetch), así
|
||||
// que la guarda de red vive aquí y no en cada pantalla. Antes estaba en
|
||||
// apiGetJson y el mapa de UTXOs, que llamaba a fetchWithTimeout directo,
|
||||
// mandaba direcciones de mainnet a la signet (auditoría A5-01).
|
||||
// - En signet, una dirección de mainnet no sale nunca.
|
||||
// - En signet, un txid solo sale si tu nodo de MAINNET dice que no lo
|
||||
// conoce (404). Preguntar a tu propio nodo no filtra nada; si lo conoce,
|
||||
// es de mainnet y no se manda (A1-01). Si no se puede preguntar, tampoco.
|
||||
const MSG_TX_MAINNET_EN_SIGNET = "no enviado: esa transacción es de mainnet (tu nodo la conoce) y estás en modo signet (cámbialo en ⚙ Ajustes)";
|
||||
const txidEnRuta = url => { const m = /\/tx\/([0-9a-fA-F]{64})(?=[/?#]|$)/.exec(String(url || "")); return m ? m[1].toLowerCase() : null; };
|
||||
const TXID_RED = new Map(); // txid → "mainnet" | "otra" (lo que dijo tu nodo de mainnet)
|
||||
function errorBloqueado(msg) { const e = new Error(msg); e.bloqueado = true; return e; }
|
||||
async function guardaDeRed(url) {
|
||||
if (!RED.signet) return;
|
||||
if (datoDeMainnet(url)) throw errorBloqueado(MSG_MAINNET_EN_SIGNET);
|
||||
const txid = txidEnRuta(url);
|
||||
if (!txid) return;
|
||||
const main = String(RED.urlMain || "").replace(/\/$/, "");
|
||||
// Sin nodo de mainnet no hay nada propio que proteger ni a quién preguntar.
|
||||
// Y una consulta a la API de mainnet de tu nodo no se comprueba contra
|
||||
// sí misma. Ojo: la signet por Tor cuelga del MISMO nodo
|
||||
// (https://tu-nodo:4083/signet-tor), así que no basta con mirar el host.
|
||||
if (!main || String(url).startsWith(main + "/api/")) return;
|
||||
let red = TXID_RED.get(txid);
|
||||
if (!red) {
|
||||
let res;
|
||||
try { res = await fetchCrudo(`${main}/api/tx/${txid}/status`); }
|
||||
catch (e) { throw errorBloqueado(`no enviado: estás en modo signet y no se ha podido comprobar en tu nodo de mainnet que esa transacción no sea de mainnet (${e.message || "sin respuesta"})`); }
|
||||
if (res.ok) red = "mainnet";
|
||||
else if (res.status === 404) red = "otra";
|
||||
else throw errorBloqueado(`no enviado: estás en modo signet y tu nodo de mainnet no ha podido decir si esa transacción es de mainnet (HTTP ${res.status})`);
|
||||
TXID_RED.set(txid, red);
|
||||
}
|
||||
if (red === "mainnet") throw errorBloqueado(MSG_TX_MAINNET_EN_SIGNET);
|
||||
}
|
||||
async function fetchWithTimeout(url, timeoutMs) {
|
||||
await guardaDeRed(url);
|
||||
return fetchCrudo(url, timeoutMs);
|
||||
}
|
||||
async function fetchCrudo(url, timeoutMs) {
|
||||
const ms = timeoutMs || FETCH_TIMEOUT_MS;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), ms);
|
||||
@@ -75,7 +114,7 @@
|
||||
}
|
||||
const MSG_MAINNET_EN_SIGNET = "no enviado: es una dirección de mainnet y estás en modo signet (cámbialo en ⚙ Ajustes)";
|
||||
async function apiGetJson(baseUrl, path) {
|
||||
if (RED.signet && datoDeMainnet(path)) { const e = new Error(MSG_MAINNET_EN_SIGNET); e.bloqueado = true; throw e; }
|
||||
if (RED.signet && datoDeMainnet(path)) throw errorBloqueado(MSG_MAINNET_EN_SIGNET);
|
||||
const key = baseUrl + path;
|
||||
const hit = apiCache.get(key);
|
||||
if (hit && (hit.ttl === Infinity || Date.now() - hit.at < hit.ttl)) return hit.data;
|
||||
@@ -107,10 +146,21 @@
|
||||
// como si fueran reales. Aquí se lleva la cuenta de qué partes del nodo
|
||||
// contestan y cuáles no, y el aviso global (EstadoNodoBanner) lo dice.
|
||||
// Un 4xx no cuenta como fallo: el nodo contestó ("no existe eso").
|
||||
const NODE_HEALTH = { base:null, oks:new Set(), fallos:new Map(), listeners:new Set() };
|
||||
const NODE_HEALTH = { base:null, oks:new Set(), fallos:new Map(), sustituidos:new Map(), listeners:new Set() };
|
||||
// v1.48.0 (auditoría A1-03): además de «el nodo no contesta», se apunta
|
||||
// cada consulta concreta cuyo dato se ha cambiado por uno de ejemplo, sea
|
||||
// cual sea el motivo, también un 4xx («no existe eso»). Antes un 403 o un
|
||||
// 404 enseñaba datos de demostración sin marcarlos como tales.
|
||||
const rutaExacta = path => String(path).split("?")[0];
|
||||
function marcarSustituido(base, path, motivo) {
|
||||
if (NODE_HEALTH.base !== base) { NODE_HEALTH.base = base; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map(); NODE_HEALTH.sustituidos = new Map(); }
|
||||
const k = rutaExacta(path), antes = NODE_HEALTH.sustituidos.get(k);
|
||||
if (motivo) NODE_HEALTH.sustituidos.set(k, motivo); else NODE_HEALTH.sustituidos.delete(k);
|
||||
if (antes !== (motivo || undefined)) NODE_HEALTH.listeners.forEach(l => l());
|
||||
}
|
||||
const claveRuta = path => String(path).split("?")[0].split("/").slice(0,3).join("/");
|
||||
function marcarNodo(base, path, error) {
|
||||
if (NODE_HEALTH.base !== base) { NODE_HEALTH.base = base; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map(); }
|
||||
if (NODE_HEALTH.base !== base) { NODE_HEALTH.base = base; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map(); NODE_HEALTH.sustituidos = new Map(); }
|
||||
const k = claveRuta(path);
|
||||
const antes = NODE_HEALTH.fallos.has(k) + ":" + NODE_HEALTH.oks.has(k);
|
||||
if (error) { NODE_HEALTH.fallos.set(k, error); NODE_HEALTH.oks.delete(k); }
|
||||
@@ -128,7 +178,8 @@
|
||||
const vigente = NODE_HEALTH.base === base;
|
||||
const fallos = vigente ? NODE_HEALTH.fallos : new Map();
|
||||
const oks = vigente ? NODE_HEALTH.oks : new Set();
|
||||
return { fallos, oks, esEjemplo: path => !base || fallos.has(claveRuta(path)) };
|
||||
const sustituidos = vigente ? NODE_HEALTH.sustituidos : new Map();
|
||||
return { fallos, oks, sustituidos, esEjemplo: path => !base || fallos.has(claveRuta(path)) || sustituidos.has(rutaExacta(path)) };
|
||||
}
|
||||
const esFalloDeNodo = e => !(e && e.bloqueado) && !/HTTP 4\d\d/.test((e && e.message) || "");
|
||||
|
||||
@@ -138,9 +189,12 @@
|
||||
try {
|
||||
const data = await apiGetJson(baseUrl, path);
|
||||
marcarNodo(baseUrl, path, null);
|
||||
marcarSustituido(baseUrl, path, null);
|
||||
return data;
|
||||
} catch (e) {
|
||||
if (esFalloDeNodo(e)) marcarNodo(baseUrl, path, (e && e.name === "AbortError") ? "sin respuesta (timeout)" : ((e && e.message) || "sin respuesta"));
|
||||
// Un null o una lista vacía no son datos de ejemplo: no se marcan.
|
||||
if (mockData != null && !(Array.isArray(mockData) && mockData.length === 0)) marcarSustituido(baseUrl, path, (e && e.message) || "sin respuesta");
|
||||
return mockData;
|
||||
}
|
||||
}, [baseUrl]);
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
// mempool.space no ve tu IP ni el origen del dashboard. Se puede escribir
|
||||
// otra dirección (tu propia Mempool de signet, o la pública si se quiere).
|
||||
const SIGNET_RUTA_TOR = "/signet-tor";
|
||||
const RED = { signet: false, publica: false, sinSistema: false };
|
||||
const RED = { signet: false, publica: false, sinSistema: false, urlMain: "" };
|
||||
const esMempoolPublica = u => /^https?:\/\/([a-z0-9-]+\.)*mempool\.space(\/|$)/i.test(String(u || ""));
|
||||
function signetPorDefecto(urlMain) {
|
||||
try { const u = new URL(String(urlMain || "").trim()); return /^https?:$/.test(u.protocol) ? u.origin + SIGNET_RUTA_TOR : ""; } catch { return ""; }
|
||||
@@ -171,6 +171,29 @@
|
||||
// una sola vez y arriba, y además avisa cuando HAY nodo pero no contesta.
|
||||
const DemoBanner = () => null;
|
||||
|
||||
// ── Secretos pegados en cualquier campo (v1.48.0, auditoría A2-01) ──
|
||||
// Todos los campos de texto pasan lo escrito por filtrarSecreto: si es
|
||||
// una semilla o una clave privada, el campo se queda vacío (no se guarda
|
||||
// ni se procesa) y sale este aviso arriba, sin repetir lo pegado.
|
||||
const AVISO_SECRETO = { activo: false, listeners: new Set() };
|
||||
function filtrarSecreto(v) {
|
||||
if (!esSecretoTexto(v)) return v;
|
||||
AVISO_SECRETO.activo = true;
|
||||
AVISO_SECRETO.listeners.forEach(l => { try { l(); } catch {} });
|
||||
return "";
|
||||
}
|
||||
function AvisoSecreto() {
|
||||
const [, forzar] = useState(0);
|
||||
useEffect(() => { const l = () => forzar(x => x + 1); AVISO_SECRETO.listeners.add(l); return () => { AVISO_SECRETO.listeners.delete(l); }; }, []);
|
||||
if (!AVISO_SECRETO.activo) return null;
|
||||
return (
|
||||
<div role="alert" style={{margin:"10px 12px 0",padding:"10px 12px",background:C.redMuted,border:`1px solid ${C.red}60`,borderRadius:6,fontSize:"0.68rem",color:C.t1,lineHeight:1.6}}>
|
||||
<strong style={{color:C.red}}>⚠ Eso era un secreto.</strong> Lo que has pegado o escrito parece una semilla o una clave privada, y con ella se puede gastar el dinero de esa wallet. Txoko nunca la necesita: se ha borrado del campo, no se ha procesado y no se ha guardado en ninguna parte. Si ese texto ha pasado por sitios que no controlas (un chat, una web, la nube), quien lo viera puede gastar ese dinero.
|
||||
<button onClick={()=>{ AVISO_SECRETO.activo = false; AVISO_SECRETO.listeners.forEach(l => l()); }} style={{display:"block",marginTop:6,background:"none",border:`1px solid ${C.red}60`,borderRadius:5,padding:"4px 12px",color:C.red,fontFamily:C.mono,fontSize:"0.64rem",cursor:"pointer"}}>Entendido</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EstadoNodoBanner({base, onAjustes}) {
|
||||
const h = useNodeHealth(base);
|
||||
const caja = (color, fondo, titulo, texto) => (
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
}
|
||||
function resumenQR(r) {
|
||||
if (!r) return "";
|
||||
if (r.tipo === "xpub" && r.descriptor) { const m = /^[a-z]+\(/.exec(r.valor); return `descriptor ${m ? m[0] + "…)" : ""} con ${r.xpub.slice(0, 12)}…${r.xpub.slice(-8)}${/#[a-z0-9]{8}\s*$/.test(r.valor) ? " · con suma de verificación" : ""}`; }
|
||||
if (r.tipo === "xpub") return `${r.valor.slice(0, 12)}…${r.valor.slice(-8)}${r.huella ? ` · huella ${r.huella}` : ""}${r.ruta ? ` · ${r.ruta}` : ""}`;
|
||||
if (r.tipo === "psbt") return `PSBT de ${r.valor.length.toLocaleString("es-ES")} caracteres`;
|
||||
if (r.tipo === "tx") return `transacción de ${(r.valor.length / 2).toLocaleString("es-ES")} bytes`;
|
||||
|
||||
+19
-9
@@ -262,9 +262,14 @@
|
||||
// No se pudo mirar. Se dice, no se supone.
|
||||
status = "warn";
|
||||
detail = `${inbound} conexiones entrantes. No se ha podido comprobar por qué red entran, así que no se puede decir si tu IP queda expuesta. Compruébalo con: bitcoin-cli getpeerinfo | jq -r '.[] | select(.inbound) | .network' | sort | uniq -c`;
|
||||
} else if (entrantesClearnet === 0 && !Array.isArray(clearnet)) {
|
||||
// v1.48.0 (auditoría A6-02): «no se sabe qué anuncia» ya no se
|
||||
// da por «no anuncia nada».
|
||||
status = "warn";
|
||||
detail = `${inbound} conexiones entrantes, todas por redes anónimas (${porRed}): ninguno de esos peers ve tu IP. Lo que no se ha podido comprobar es si tu nodo anuncia alguna dirección de clearnet; si la anuncia, cualquiera puede relacionar tu nodo con esa IP. Compruébalo en el nodo con: bitcoin-cli getnetworkinfo | jq '.localaddresses'`;
|
||||
} else if (entrantesClearnet === 0 && !anunciaIp) {
|
||||
status = "ok";
|
||||
detail = `${inbound} conexiones entrantes, todas por redes anónimas (${porRed}), y tu nodo no anuncia ninguna dirección de clearnet. Nadie ve tu IP: ni quien se conecta ni la red en general. Es la configuración que conviene tener, y además devuelves a la red lo que consumes.`;
|
||||
detail = `${inbound} conexiones entrantes, todas por redes anónimas (${porRed}), y tu nodo no anuncia ninguna dirección de clearnet: ninguno de esos peers ve tu IP ni la red la recibe de tu nodo. Esto mira las entrantes; por dónde salen las conexiones que abre tu nodo lo decide su configuración (onlynet). Es la configuración que conviene tener, y además devuelves a la red lo que consumes.`;
|
||||
} else if (entrantesClearnet === 0 && anunciaIp) {
|
||||
status = "warn";
|
||||
detail = `Las ${inbound} conexiones entrantes llegan por redes anónimas (${porRed}), pero tu nodo anuncia ${clearnet.length} dirección(es) de clearnet: ${clearnet.join(", ")}. Quien las lea puede relacionar tu nodo con esa IP aunque nadie se conecte por ahí. Revisa \`discover\`, \`externalip\` y \`listen\` en bitcoin.conf.`;
|
||||
@@ -360,11 +365,16 @@
|
||||
});
|
||||
}
|
||||
|
||||
// ── 7. Acceso solo via Tailscale ─────────────────────────────
|
||||
// ── 7. Quién puede abrir el dashboard ────────────────────────
|
||||
// v1.48.0 (auditoría A6-01): antes salía SIEMPRE en verde («solo es
|
||||
// accesible desde tu red Tailscale») sin comprobar nada. Desde el
|
||||
// navegador no se puede saber: depende del cortafuegos del nodo.
|
||||
const hostPagina = (()=>{ try { return location.hostname; } catch { return ""; } })();
|
||||
const porTailscale = /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+$/.test(hostPagina) || /\.ts\.net$/i.test(hostPagina);
|
||||
results.push({
|
||||
id:"tailscale", label:"Acceso via Tailscale",
|
||||
status:"ok",
|
||||
detail:"El dashboard solo es accesible desde tu red Tailscale. No hay autenticación adicional — Tailscale es el perímetro de seguridad.",
|
||||
id:"tailscale", label:"Quién más puede abrir el dashboard",
|
||||
status:"nd",
|
||||
detail:`${porTailscale ? `Ahora lo abres por Tailscale (${hostPagina}). ` : ""}Desde el navegador no se puede saber si alguien más puede abrirlo: depende de en qué interfaces escucha nginx y del cortafuegos del nodo. El dashboard no tiene contraseña, así que si el puerto queda abierto a tu red local o a internet, cualquiera de ahí puede abrirlo. Compruébalo en el nodo: sudo ufw status numbered (el puerto del dashboard solo debería estar permitido desde Tailscale, 100.64.0.0/10) y sudo ss -tlnp | grep nginx.`,
|
||||
});
|
||||
|
||||
setChecks(results);
|
||||
@@ -373,8 +383,8 @@
|
||||
|
||||
useEffect(()=>{ if(btcData||sysData) runChecks(); },[btcData,sysData]);
|
||||
|
||||
const statusColor = s => s==="ok"?C.green:s==="warn"?C.amber:C.red;
|
||||
const statusIcon = s => s==="ok"?"✓":s==="warn"?"⚠":"✗";
|
||||
const statusColor = s => s==="ok"?C.green:s==="warn"?C.amber:s==="nd"?C.t2:C.red;
|
||||
const statusIcon = s => s==="ok"?"✓":s==="warn"?"⚠":s==="nd"?"?":"✗";
|
||||
const overallStatus = checks
|
||||
? checks.some(c=>c.status==="error")?"error":checks.some(c=>c.status==="warn")?"warn":"ok"
|
||||
: null;
|
||||
@@ -386,7 +396,7 @@
|
||||
<span style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.2em",fontWeight:700}}>⚑ Seguridad del nodo</span>
|
||||
{overallStatus&&(
|
||||
<span style={{fontSize:"0.62rem",fontFamily:C.mono,color:statusColor(overallStatus),fontWeight:700}}>
|
||||
{overallStatus==="ok"?" — todo correcto":overallStatus==="warn"?" — revisar":" — error"}
|
||||
{overallStatus==="ok"?" — todo correcto":overallStatus==="warn"?" — revisar":" — error"}{checks.some(c=>c.status==="nd")?` · ${checks.filter(c=>c.status==="nd").length} sin comprobar`:""}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -411,7 +421,7 @@
|
||||
<div style={{fontSize:"0.65rem",color:C.t2,lineHeight:1.6}}>{check.detail}</div>
|
||||
</div>
|
||||
<Badge color={statusColor(check.status)}>
|
||||
{check.status==="ok"?"OK":check.status==="warn"?"REVISAR":"ERROR"}
|
||||
{check.status==="ok"?"OK":check.status==="warn"?"REVISAR":check.status==="nd"?"SIN COMPROBAR":"ERROR"}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
|
||||
+17
-2
@@ -4,8 +4,12 @@
|
||||
// confirmados en Bloques. Es una línea temporal con el ahora en el corte,
|
||||
// así que se cuenta como una sola historia: lo que viene, el momento
|
||||
// actual, y lo que ya pasó.
|
||||
// Qué series de esta pestaña son datos de ejemplo porque tu nodo no las
|
||||
// ha dado (v1.48.0, auditoría A1-03). Antes no se marcaba nada aquí.
|
||||
const SERIES_RED = [["/api/v1/fees/recommended","las comisiones"],["/api/mempool","la mempool"],["/api/v1/fees/mempool-blocks","los bloques proyectados"],["/api/v1/blocks","los últimos bloques"],["/api/v1/mining/blocks/fee-rates/1w","el historial de comisiones"]];
|
||||
function RedView({base}) {
|
||||
const {get}=useApi(base);
|
||||
const salud=useNodeHealth(base);
|
||||
const isMobile=useIsMobile();
|
||||
const [blocks,setBlocks]=useState([]);
|
||||
const [selected,setSelected]=useState(null);
|
||||
@@ -28,7 +32,14 @@
|
||||
get("/api/v1/mining/blocks/fee-rates/1w", MOCK_FEE_HISTORY).then(d=>setFeeHistory(d));
|
||||
},[base]);
|
||||
|
||||
const selectBlock=async(b)=>{ setSelected(b); setBlockTxs(null); const txs=await get(`/api/block/${b.id}/txs/0`,[MOCK_TX]); setBlockTxs(Array.isArray(txs)?txs:[txs]); };
|
||||
// v1.48.0: sin nodo, la transacción de ejemplo; con nodo, si no llegan, se
|
||||
// dice (antes salía la de ejemplo bajo un bloque real, A1-03). Y solo se
|
||||
// aplica la respuesta del último bloque pulsado (A6-05).
|
||||
const bloquePedido=useRef(null);
|
||||
const selectBlock=async(b)=>{ setSelected(b); setBlockTxs(null); bloquePedido.current=b.id;
|
||||
const txs=base?await get(`/api/block/${b.id}/txs/0`,null):[MOCK_TX];
|
||||
if(bloquePedido.current!==b.id) return;
|
||||
setBlockTxs(txs==null?"error":Array.isArray(txs)?txs:[txs]); };
|
||||
|
||||
// El detalle se dibuja al final de la lista, así que al pinchar en un
|
||||
// bloque de arriba se abría a quince filas de distancia y parecía que el
|
||||
@@ -70,6 +81,9 @@
|
||||
return (
|
||||
<div style={{display:"flex",flexDirection:"column",gap:12}}>
|
||||
{!base&&<DemoBanner/>}
|
||||
{base&&(()=>{ const ej=SERIES_RED.filter(([p])=>salud.esEjemplo(p)); if(!ej.length) return null;
|
||||
const motivos=[...new Set(ej.map(([p])=>salud.sustituidos.get(p)||salud.fallos.get(p.split("/").slice(0,3).join("/"))).filter(Boolean))];
|
||||
return <div style={{padding:"9px 12px",background:C.amberMuted,border:`1px solid ${C.amber}50`,borderRadius:6,fontSize:"0.66rem",color:C.t1,lineHeight:1.55}}><Badge color={C.amber}>EJEMPLO</Badge> Tu nodo no ha dado {ej.map(([,n])=>n).join(", ")}{motivos.length?` (${motivos.join("; ")})`:""}: lo que ves ahí son <strong>datos de ejemplo</strong>, no los de la red.</div>; })()}
|
||||
|
||||
{/* Comisiones — el contexto para decidir */}
|
||||
{fees&&(
|
||||
@@ -169,7 +183,8 @@
|
||||
</div>
|
||||
<div style={{fontSize:"0.62rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",marginBottom:8}}>Primeras Transacciones</div>
|
||||
{!blockTxs&&<Spinner/>}
|
||||
{blockTxs&&blockTxs.slice(0,5).map((tx,i)=>(
|
||||
{blockTxs==="error"&&<div style={{fontSize:"0.66rem",color:C.amber}}>Tu nodo no ha dado las transacciones de este bloque.</div>}
|
||||
{Array.isArray(blockTxs)&&blockTxs.slice(0,5).map((tx,i)=>(
|
||||
<div key={i} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 0",borderBottom:`1px solid ${C.border}`}}>
|
||||
<span style={{fontSize:"0.68rem",fontFamily:C.mono,color:C.blue}}><IdCopiable id={tx.txid} texto={fmt.hash(tx.txid)}/></span>
|
||||
<div style={{display:"flex",gap:6,alignItems:"center"}}><Badge color={C.amber}>{tx.fee} sat</Badge><Badge color={C.t3}>{tx.size}B</Badge><VerEnMempool base={base} tipo="tx" id={tx.txid} texto="↗"/></div>
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
{!base&&<DemoBanner/>}
|
||||
<SectionTitle accent={C.purple} icon="⌕">Explorar la cadena</SectionTitle>
|
||||
<div style={{display:"flex",gap:8}}>
|
||||
<input value={query} onChange={e=>setQuery(e.target.value)} onKeyDown={e=>e.key==="Enter"&&search()}
|
||||
<input value={query} onChange={e=>setQuery(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&search()}
|
||||
placeholder="txid · dirección · altura · block hash"
|
||||
style={{flex:1,background:C.bgCard,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"11px 14px",color:C.t1,fontFamily:C.mono,fontSize:"0.78rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.purple} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
@@ -147,7 +147,7 @@
|
||||
</div>
|
||||
<div style={{fontSize:"0.66rem",color:C.t2,marginBottom:10,lineHeight:1.5}}>Para comprobar que una transacción tuya ha llegado a la cadena: confirmaciones, bloque y comisión, preguntando solo a tu nodo.</div>
|
||||
<div style={{display:"flex",gap:8,marginBottom:err||result?"10px":"0"}}>
|
||||
<input value={txid} onChange={e=>setTxid(e.target.value)} onKeyDown={e=>e.key==="Enter"&&verify()}
|
||||
<input value={txid} onChange={e=>setTxid(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&verify()}
|
||||
placeholder="Pega aquí tu txid para verificar"
|
||||
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.green} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
@@ -374,7 +374,7 @@
|
||||
Las monedas sin gastar de una dirección (UTXOs), cada una con la banda de privacidad (alta, media o baja) de la transacción que la creó. Si la moneda la recibiste, esa banda refleja lo que hizo quien te pagó. Hasta {MAX_UTXOS} monedas; se analizan las 10 mayores, para no cargar tu nodo.
|
||||
</div>
|
||||
<div style={{display:"flex",gap:8,marginBottom:10}}>
|
||||
<input value={addr} onChange={e=>setAddr(e.target.value)} onKeyDown={e=>e.key==="Enter"&&fetchUtxos()}
|
||||
<input value={addr} onChange={e=>setAddr(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&fetchUtxos()}
|
||||
placeholder="Dirección Bitcoin (bc1q..., bc1p..., 1..., 3...)"
|
||||
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.purple} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
|
||||
@@ -879,7 +879,7 @@
|
||||
// clase de error en un informe pericial.
|
||||
const unspentFunds = unspentTerminals
|
||||
.filter(u => u.address && !u.truncated && !u.queryFailed && (u.tipo === "sin_gastar" || u.note === "UTXO sin gastar."))
|
||||
.map(u => ({ level:"HECHO", txid:u.txid, vout:u.vout, address:u.address, amount:u.amount, refs:[u.txid, u.address] }));
|
||||
.map(u => ({ level:"HECHO", txid:u.txid, vout:u.vout, address:u.address, amount:u.amount, comprobado:u.comprobado || null, refs:[u.txid, u.address] }));
|
||||
const truncatedBranches = unspentTerminals.filter(u => u.truncated);
|
||||
// Tres cosas distintas que antes iban juntas como «fallo de consulta»
|
||||
// (revisión de comunicación del 23-oct, hallazgo 1):
|
||||
@@ -1099,7 +1099,7 @@
|
||||
(rep.destinatarios || []).forEach(x => L.push(`- [INFERENCIA/${x.certainty}] ${x.address} — ${x.basis} [tx ${x.txid}]`));
|
||||
L.push("", "## Fondos localizados sin gastar", "");
|
||||
if (!unspentFunds.length) L.push("Ninguno en las ramas exploradas.");
|
||||
unspentFunds.forEach(u => L.push(`- [HECHO] ${u.address} — ${btcTxt(u.amount)} · ${salida(u.txid, u.vout)}`));
|
||||
unspentFunds.forEach(u => L.push(`- [HECHO] ${u.address} — ${btcTxt(u.amount)} · ${salida(u.txid, u.vout)}${u.comprobado ? ` · sin gastar al comprobarlo el ${new Date(u.comprobado*1000).toLocaleString("es-ES",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}` : ""}`));
|
||||
L.push("", "## Ramas sin seguir", "", "_Salidas que no se llegaron a seguir: lo que pasó con ese dinero no está en este informe._", "");
|
||||
if (!(rep.pendingBranches || []).length) L.push("Ninguna.");
|
||||
(rep.pendingBranches || []).forEach(b => L.push(`- [HECHO] ${b.address} — ${salida(b.txid, b.vout)}: ${btcTxt(b.amount)}; de lo seguido, ${btcTxt(b.seguido)} (reparto proporcional); ${b.estado}`));
|
||||
|
||||
@@ -339,7 +339,15 @@
|
||||
const o = per.txs.get(txid)?.vout?.[vout];
|
||||
if (!o) continue;
|
||||
const dirO = o.scriptpubkey_address || etiquetaSinDir(o);
|
||||
if (g.estado === "sin_gastar") unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, note:"Sin gastar.", tipo:"sin_gastar", comprobado:g.comprobado || null });
|
||||
// v1.48.0 (auditoría A6-03): si una comprobación POSTERIOR falló (la
|
||||
// vigilancia, por ejemplo), el «sin gastar» viejo ya no se da como
|
||||
// hecho: se dice cuándo se vio y que después no se pudo comprobar.
|
||||
if (g.estado === "sin_gastar" && g.ultimoFallo && g.ultimoFallo.fecha >= (g.comprobado || 0)) {
|
||||
const msg = `sin gastar en la comprobación del ${fechaHora(g.comprobado)}, pero la del ${fechaHora(g.ultimoFallo.fecha)} falló (${g.ultimoFallo.err || "sin respuesta"}): no se sabe si sigue sin gastar`;
|
||||
unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, queryFailed:true, tipo:"fallo", comprobado:g.comprobado || null, note:`No se pudo comprobar de nuevo: ${msg}.` });
|
||||
queryErrors.push({ txid, vout, address:dirO, message:msg, context:"comprobación de vigilancia" });
|
||||
}
|
||||
else if (g.estado === "sin_gastar") unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, note:"Sin gastar.", tipo:"sin_gastar", comprobado:g.comprobado || null });
|
||||
else if (g.estado === "no_localizada") unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, queryFailed:true, tipo:"no_localizada", paginas:g.paginas, note:`Se movió; no se ha encontrado a dónde (${g.paginas} página(s) revisada(s)).` });
|
||||
else if (g.estado === "incompleto") unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, queryFailed:true, tipo:"incompleto", paginas:g.paginas, totalPaginas:g.totalPaginas, note:`Búsqueda sin terminar: revisadas ${g.paginas}${g.totalPaginas ? ` de ${g.totalPaginas}` : ""} páginas del historial.` });
|
||||
else if (g.estado === "inconcluso") { unspentTerminals.push({ txid, vout, address:dirO, amount:o.value, queryFailed:true, tipo:"fallo", note:`No se pudo comprobar: ${g.err}` }); queryErrors.push({ txid, vout, address:dirO, message:g.err, context:"búsqueda del gasto" }); }
|
||||
|
||||
@@ -178,7 +178,7 @@
|
||||
style={{marginLeft:"auto",background:"none",border:"none",color:C.t3,cursor:"pointer",fontSize:"0.75rem"}}>✕</button>
|
||||
</div>
|
||||
<textarea value={m.nota||""} rows={2} placeholder="Nota (solo en este navegador)"
|
||||
onChange={e=>{const v=e.target.value; setMesa(ms=>({...ms,[txid]:{...ms[txid],nota:v}}));}}
|
||||
onChange={e=>{const v=filtrarSecreto(e.target.value); setMesa(ms=>({...ms,[txid]:{...ms[txid],nota:v}}));}}
|
||||
style={{width:"100%",boxSizing:"border-box",resize:"vertical",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:5,color:C.t1,fontSize:"0.7rem",padding:"6px 8px",fontFamily:C.sans}}/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -187,7 +187,7 @@
|
||||
<span style={{fontFamily:C.mono,fontSize:"0.58rem",padding:"1px 6px",borderRadius:3,color:k>=0?C.amber:C.t3,border:`1px solid ${k>=0?C.amber:C.t3}55`}}>{k<0?"fuera de este camino":k===0?"origen":`salto ${k}`}</span>
|
||||
<button onClick={()=>setMesa(ms=>{const n={...ms};delete n[txid];return n;})} title="Quitar de la mesa" style={{marginLeft:"auto",background:"none",border:"none",color:C.t3,cursor:"pointer",fontSize:"0.75rem"}}>✕</button>
|
||||
</div>
|
||||
<textarea value={m.nota||""} rows={2} placeholder="Nota" onChange={e=>{const v=e.target.value; setMesa(ms=>({...ms,[txid]:{...ms[txid],nota:v}}));}}
|
||||
<textarea value={m.nota||""} rows={2} placeholder="Nota" onChange={e=>{const v=filtrarSecreto(e.target.value); setMesa(ms=>({...ms,[txid]:{...ms[txid],nota:v}}));}}
|
||||
style={{width:"100%",boxSizing:"border-box",resize:"vertical",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:5,color:C.t1,fontSize:"0.7rem",padding:"6px 8px",fontFamily:C.sans}}/>
|
||||
</div>); })}
|
||||
{h("Salidas guardadas para revisar")}
|
||||
@@ -318,7 +318,16 @@
|
||||
nuevo = resultadoVigilancia(r, Math.floor(Date.now()/1000));
|
||||
if (r.estado === "gastada") { per.txs.set(r.tx.txid, r.tx); per.gastos.set(v.clave, {estado:"gastada", spendTxid:r.tx.txid, comprobado:nuevo.fecha}); }
|
||||
else if (r.estado === "no_localizada" || r.estado === "incompleto") anotar(v.clave, r);
|
||||
} catch(e) { nuevo = {fecha:Math.floor(Date.now()/1000), estado:"error", err:e.message}; }
|
||||
// v1.48.0 (A6-03): la comprobación buena nueva también llega al
|
||||
// informe, con su fecha (antes se quedaba solo en la vigilancia).
|
||||
else if (r.estado === "sin_gastar") per.gastos.set(v.clave, {estado:"sin_gastar", comprobado:nuevo.fecha});
|
||||
} catch(e) {
|
||||
nuevo = {fecha:Math.floor(Date.now()/1000), estado:"error", err:e.message};
|
||||
// …y el fallo también: el informe no puede seguir dando por hecho
|
||||
// el «sin gastar» de antes como si nada.
|
||||
const prev = per.gastos.get(v.clave);
|
||||
if (prev) per.gastos.set(v.clave, {...prev, ultimoFallo:{fecha:nuevo.fecha, err:e.message}});
|
||||
}
|
||||
const d = diffVigilancia(v, nuevo);
|
||||
nuevaVig[v.clave] = d.entrada; res[v.clave] = d;
|
||||
refrescar();
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
</div>
|
||||
{demo&&<div style={{padding:"9px 12px",background:C.amberMuted,border:`1px solid ${C.amber}55`,borderRadius:6,color:C.t1,fontSize:"0.7rem",lineHeight:1.55,marginBottom:8}}>Sin nodo se abre un ejemplo para ver cómo funciona.</div>}
|
||||
<div style={{display:"flex",gap:8,flexWrap:"wrap",opacity:demo?0.45:1}}>
|
||||
<input value={txid} onChange={e=>setTxid(e.target.value)} disabled={demo} placeholder={demo?"(no se usa en el ejemplo)":"txid de la transacción"}
|
||||
<input value={txid} onChange={e=>setTxid(filtrarSecreto(e.target.value))} disabled={demo} placeholder={demo?"(no se usa en el ejemplo)":"txid de la transacción"}
|
||||
style={{flex:"3 1 220px",minWidth:0,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none"}}/>
|
||||
{!demo&&<BotonQR campo="txid" color={C.purple} onLeido={v=>setTxid(v)}/>}
|
||||
</div>
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
{clusters.length > 0 && <div style={{ fontSize: "0.58rem", color: C.t3, marginTop: 4 }}>«grupo N» es el grupo de direcciones vinculadas N del informe de arriba; «suelta», una dirección que no está vinculada con otras.</div>}
|
||||
</div>)}
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(160px,1fr))", gap: 8, marginBottom: 8 }}>
|
||||
<input value={destino} onChange={e => { setDestino(e.target.value); setRes(null); }} placeholder="Dirección de destino" spellCheck={false} autoComplete="off" style={{ ...campo, gridColumn: "1 / -1" }} />
|
||||
<input value={destino} onChange={e => { setDestino(filtrarSecreto(e.target.value)); setRes(null); }} placeholder="Dirección de destino" spellCheck={false} autoComplete="off" style={{ ...campo, gridColumn: "1 / -1" }} />
|
||||
<input value={importeTxt} onChange={e => { setImporteTxt(e.target.value); setRes(null); }} placeholder="Importe en BTC (vacío = enviar todo)" inputMode="decimal" style={campo} />
|
||||
<input value={tarifaTxt} onChange={e => { setTarifaTxt(e.target.value); setRes(null); }} placeholder={`Tarifa sat/vB (vacío = la de tu nodo, o ${TARIFA_SIMULADOR_DEFECTO})`} inputMode="decimal" style={campo} />
|
||||
</div>
|
||||
|
||||
@@ -42,14 +42,14 @@
|
||||
// Un secreto pegado (xprv, WIF, semilla) no llega ni a quedarse en el
|
||||
// campo: se borra al pegarlo y el mensaje no lo repite (v1.44).
|
||||
const cambiarEntradaWallet = (v) => {
|
||||
if (contieneClavePrivada(v)) { setXpubInput(""); setXpubError(MSG_CLAVE_PRIVADA); return; }
|
||||
if (esSecretoTexto(v)) { setXpubInput(""); setXpubError(MSG_CLAVE_PRIVADA); return; }
|
||||
setXpubInput(v);
|
||||
if (xpubError === MSG_CLAVE_PRIVADA) setXpubError(null);
|
||||
};
|
||||
const loadWallet = async (scriptElegido) => {
|
||||
const texto = xpubInput.trim();
|
||||
if (!texto) return;
|
||||
if (contieneClavePrivada(texto)) { setXpubInput(""); setXpubError(MSG_CLAVE_PRIVADA); return; }
|
||||
if (esSecretoTexto(texto)) { setXpubInput(""); setXpubError(MSG_CLAVE_PRIVADA); return; }
|
||||
if (!paginaSegura) { setXpubError("Para cargar la wallet abre el dashboard por https (normalmente https://…:4081/dashboard). Por http el navegador no deja hacer la derivación."); return; }
|
||||
setXpubLoading(true); setXpubError(null); olvidarInforme();
|
||||
const elegido = typeof scriptElegido === "string" ? scriptElegido : null;
|
||||
@@ -116,7 +116,10 @@
|
||||
catch (e) { scanErrors.push({ addr:s.addr, branch:s.branch, message:e.message, phase:"estado de la dirección" }); return null; }
|
||||
}));
|
||||
infos.forEach((info, j) => {
|
||||
const txc = info?.chain_stats?.tx_count || 0;
|
||||
// v1.48.0 (auditoría A5-04): también cuenta lo que está en la
|
||||
// mempool. Antes una dirección con un pago pendiente y nada
|
||||
// confirmado se saltaba y la wallet salía «sin actividad».
|
||||
const txc = (info?.chain_stats?.tx_count || 0) + (info?.mempool_stats?.tx_count || 0);
|
||||
if (txc > 0) active.push({ ...slice[j], info });
|
||||
});
|
||||
if (i + BATCH < all.length) await new Promise(r => setTimeout(r, PAUSE));
|
||||
@@ -521,6 +524,7 @@
|
||||
{walletReport.alcance&&<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,marginTop:5}}>Alcance: {walletReport.alcance.recepcion} direcciones de recepción + {walletReport.alcance.cambio} de cambio · {TIPO_SCRIPT[walletReport.alcance.script]||walletReport.alcance.script}{walletReport.alcance.scriptSupuesto?" (supuesto)":""}{verifWallet==="si"?" · comprobado por ti":verifWallet==="no"?" · NO coincide con tu wallet":null}
|
||||
{!verifWallet&&<div style={{fontFamily:"inherit",color:C.amber,marginTop:3,lineHeight:1.5}}>Sin confirmar: la app no puede saber si estas son tus direcciones; solo tú puedes, comparando la {walletAddrs&&walletAddrs.receive.length?"recepción 0":"cambio 0"} con la de tu wallet (en Sparrow, la primera de la lista). <button onClick={()=>{if(verifRef.current){verifRef.current.scrollIntoView({behavior:"smooth",block:"center"});}}} style={{background:"none",border:"none",color:C.green,fontFamily:C.mono,fontSize:"inherit",cursor:"pointer",padding:0,textDecoration:"underline"}}>confirmar ↑</button></div>}
|
||||
</div>}
|
||||
{(()=>{ const n=(walletReport.history||[]).filter(t=>t.confirmed===false).length; return n>0&&<div style={{fontSize:"0.62rem",color:C.amber,marginTop:4}}>{n} transacci{n===1?"ón":"ones"} todavía sin confirmar (pendiente{n===1?"":"s"} en la mempool): cuentan en el análisis, pero pueden cambiar o no llegar a confirmarse.</div>; })()}
|
||||
<div style={{display:"flex",gap:16,marginTop:8}}>
|
||||
{[
|
||||
{label:"Transacciones",v:walletReport.totalTxs},
|
||||
@@ -665,7 +669,7 @@
|
||||
<Card>
|
||||
<div style={{fontSize:"0.62rem",color:C.t2,fontFamily:C.mono,marginBottom:10}}>ANALIZAR TRANSACCIÓN — introduce un txid</div>
|
||||
<div style={{display:"flex",gap:8}}>
|
||||
<input value={query} onChange={e=>setQuery(e.target.value)} onKeyDown={e=>e.key==="Enter"&&analyze()}
|
||||
<input value={query} onChange={e=>setQuery(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&analyze()}
|
||||
placeholder="txid de la transacción (64 letras y números)"
|
||||
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"11px 14px",color:C.t1,fontFamily:C.mono,fontSize:"0.78rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.purple} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
|
||||
@@ -122,7 +122,7 @@
|
||||
<div style={rotulo}>1 · La transacción en la que salió el dinero</div>
|
||||
<div style={{fontSize:"0.64rem",color:C.t2,lineHeight:1.5}}>Es la que movió el dinero fuera de tu wallet (el robo o la pérdida). Su txid está en el historial de tu wallet; en Sparrow, en Transactions.</div>
|
||||
<div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
|
||||
<input value={txidInput} onChange={e=>setTxidInput(e.target.value)} placeholder="txid (64 letras y números)" style={{...caja,flex:"3 1 220px"}}/>
|
||||
<input value={txidInput} onChange={e=>setTxidInput(filtrarSecreto(e.target.value))} placeholder="txid (64 letras y números)" style={{...caja,flex:"3 1 220px"}}/>
|
||||
<BotonQR campo="txid" color={C.red} onLeido={v=>setTxidInput(v)}/>
|
||||
</div>
|
||||
<button onClick={()=>verSalidas()} disabled={busy} style={{alignSelf:"flex-start",padding:"9px 18px",background:C.redMuted,border:`1px solid ${C.red}50`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>
|
||||
@@ -163,7 +163,7 @@
|
||||
<div style={rotulo}>Importe robado o perdido, en BTC <span style={{textTransform:"none"}}>(opcional: sirve para saber qué parte de él sigue en cada salto)</span></div>
|
||||
<input value={amountInput} onChange={e=>setAmountInput(e.target.value)} inputMode="decimal" placeholder="0,00000000" style={caja}/>
|
||||
<div style={rotulo}>Declaración del afectado <span style={{textTransform:"none"}}>(opcional)</span></div>
|
||||
<textarea value={declaracion} onChange={e=>setDeclaracion(e.target.value)} rows={3}
|
||||
<textarea value={declaracion} onChange={e=>setDeclaracion(filtrarSecreto(e.target.value))} rows={3}
|
||||
placeholder="Qué pasó, cuándo se notó, cómo pudo ocurrir. En el informe va aparte, como DECLARACIÓN, y nunca se mezcla con los hechos."
|
||||
style={{...caja,fontSize:"0.68rem",resize:"vertical"}}/>
|
||||
<button onClick={iniciar} style={{alignSelf:"flex-start",padding:"9px 18px",background:C.redMuted,border:`1px solid ${C.red}50`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>
|
||||
@@ -176,7 +176,7 @@
|
||||
<div style={{fontSize:"0.7rem",color:C.t1,lineHeight:1.6}}>
|
||||
Seguimiento en curso{demo?" (EJEMPLO)":""}: <span style={{fontFamily:C.mono}}>{abrevTxid(per.origen.txid)}</span>, salida {per.origen.vout} · {per.abiertas.size-1} salto(s) seguidos · {per.consultas} consulta(s) a tu nodo.
|
||||
</div>
|
||||
<textarea value={declaracion} onChange={e=>setDeclaracion(e.target.value)} rows={2}
|
||||
<textarea value={declaracion} onChange={e=>setDeclaracion(filtrarSecreto(e.target.value))} rows={2}
|
||||
placeholder="Declaración del afectado (opcional). En el informe va aparte, etiquetada como DECLARACIÓN."
|
||||
style={{...caja,fontSize:"0.68rem",resize:"vertical"}}/>
|
||||
<div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
// Sin diálogos nativos: cada paso delicado se confirma en línea.
|
||||
function vaciarEstadoEnMemoria() {
|
||||
try { apiCache.clear(); apiInflight.clear(); } catch {}
|
||||
NODE_HEALTH.base = null; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map();
|
||||
NODE_HEALTH.base = null; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map(); NODE_HEALTH.sustituidos = new Map();
|
||||
NODE_HEALTH.listeners.forEach(l => { try { l(); } catch {} });
|
||||
}
|
||||
const tamTxt = b => b < 1024 ? `${b} B` : `${(b/1024).toFixed(1).replace(".", ",")} KB`;
|
||||
|
||||
@@ -134,7 +134,7 @@
|
||||
<Card>
|
||||
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:14}}>Comprobar formato de dirección</div>
|
||||
<div style={{display:"flex",gap:8,marginBottom:12}}>
|
||||
<input value={addr} onChange={e=>setAddr(e.target.value)} onKeyDown={e=>e.key==="Enter"&&validate()}
|
||||
<input value={addr} onChange={e=>setAddr(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&validate()}
|
||||
placeholder="Pega una dirección Bitcoin para validar"
|
||||
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.blue} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
@@ -203,7 +203,7 @@
|
||||
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Detector OP_RETURN</div>
|
||||
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12}}>Indica si una transacción contiene datos arbitrarios (OP_RETURN) y su tamaño.</div>
|
||||
<div style={{display:"flex",gap:8,marginBottom:12}}>
|
||||
<input value={txid} onChange={e=>setTxid(e.target.value)} onKeyDown={e=>e.key==="Enter"&&decode()}
|
||||
<input value={txid} onChange={e=>setTxid(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&decode()}
|
||||
placeholder="txid de una transacción"
|
||||
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
||||
onFocus={e=>e.target.style.borderColor=C.blue} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12,lineHeight:1.6}}>
|
||||
Revisa una transacción <strong style={{color:C.t1}}>antes de firmarla</strong>, cuando todavía puedes cambiarla. Todo se analiza en tu navegador: el archivo no se envía a ningún sitio, ni siquiera a tu nodo.
|
||||
</div>
|
||||
<textarea value={input} onChange={e=>cambiarTexto(e.target.value)}
|
||||
<textarea value={input} onChange={e=>cambiarTexto(filtrarSecreto(e.target.value))}
|
||||
placeholder="Pega aquí la PSBT en base64 (cHNidP8BAH…) o en hexadecimal"
|
||||
rows={4}
|
||||
style={{width:"100%",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none",resize:"vertical",boxSizing:"border-box",marginBottom:8}}
|
||||
@@ -163,7 +163,7 @@
|
||||
Cuando el monedero de firma (SeedSigner, Coldcard, Jade…) te enseñe la PSBT firmada, léela aquí antes de llevarla a Sparrow. Txoko comprueba que gasta las mismas monedas y envía lo mismo a los mismos sitios que la que acabas de revisar.
|
||||
</div>
|
||||
<div style={{display:"flex",gap:8,alignItems:"stretch",flexWrap:"wrap"}}>
|
||||
<input value={texto} onChange={e=>desdeTexto(e.target.value)} placeholder="Pega la PSBT firmada o la transacción final"
|
||||
<input value={texto} onChange={e=>desdeTexto(filtrarSecreto(e.target.value))} placeholder="Pega la PSBT firmada o la transacción final"
|
||||
style={{flex:"1 1 200px",minWidth:0,background:C.bgCard,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"8px 10px",color:C.t1,fontFamily:C.mono,fontSize:"0.7rem",outline:"none"}}/>
|
||||
<BotonQR campo="firmada" color={C.blue} onLeido={v=>desdeTexto(v)}/>
|
||||
<label style={{padding:"8px 12px",background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.t2,fontFamily:C.mono,fontSize:"0.66rem",cursor:"pointer",display:"flex",alignItems:"center"}}>
|
||||
@@ -228,7 +228,7 @@
|
||||
<Card>
|
||||
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Comprobar transacción en crudo (hex)</div>
|
||||
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12}}>Una transacción «en crudo» es su texto hexadecimal completo. Esto la descodifica: entradas, salidas con sus importes, RBF, locktime y txid. No comprueba firmas, y sin consultar el nodo no sabe cuánto vale cada moneda que gasta. Todo ocurre en el navegador.</div>
|
||||
<textarea value={input} onChange={e=>{ setInput(e.target.value); setResult(null); setErr(null); }}
|
||||
<textarea value={input} onChange={e=>{ setInput(filtrarSecreto(e.target.value)); setResult(null); setErr(null); }}
|
||||
placeholder="0100000001..."
|
||||
rows={4}
|
||||
style={{width:"100%",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none",resize:"vertical",boxSizing:"border-box",marginBottom:8}}
|
||||
@@ -300,9 +300,9 @@
|
||||
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12}}>Comprueba solo que la firma de un mensaje tiene la forma esperada (unos 88 caracteres en base64). <strong style={{color:C.t1}}>No comprueba que la firma sea válida ni que la dirección sea de quien firma</strong>: eso exige verificarla criptográficamente, por ejemplo con <span style={{fontFamily:C.mono}}>verifymessage</span> de Bitcoin Core o con Sparrow.</div>
|
||||
<div style={{display:"flex",flexDirection:"column",gap:8,marginBottom:10}}>
|
||||
{[
|
||||
{label:"Dirección", value:addr, onChange:e=>setAddr(e.target.value), placeholder:"bc1q..."},
|
||||
{label:"Mensaje", value:msg, onChange:e=>setMsg(e.target.value), placeholder:"El mensaje que fue firmado"},
|
||||
{label:"Firma", value:sig, onChange:e=>setSig(e.target.value), placeholder:"Base64 de la firma..."},
|
||||
{label:"Dirección", value:addr, onChange:e=>setAddr(filtrarSecreto(e.target.value)), placeholder:"bc1q..."},
|
||||
{label:"Mensaje", value:msg, onChange:e=>setMsg(filtrarSecreto(e.target.value)), placeholder:"El mensaje que fue firmado"},
|
||||
{label:"Firma", value:sig, onChange:e=>setSig(filtrarSecreto(e.target.value)), placeholder:"Base64 de la firma..."},
|
||||
].map(f=>(
|
||||
<div key={f.label}>
|
||||
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",marginBottom:4}}>{f.label}</div>
|
||||
|
||||
+11
-4
@@ -6,7 +6,12 @@
|
||||
return {url:"",name:""};
|
||||
});
|
||||
const [themeId,setThemeId]=useState(()=>{ let t="cypherpunk"; t=ALMACEN.get("tema","cypherpunk")||"cypherpunk"; t=TEMA_RETIRADO[t]||t; return THEMES[t]?t:"cypherpunk"; });
|
||||
const [auditQuery,setAuditQuery]=useState("");
|
||||
// La consulta que se pasa a Auditoría va atada a la red en la que se pidió
|
||||
// (v1.48.0, auditoría A1-02): al cambiar de red, Auditoría se monta de
|
||||
// nuevo y analizaba sola la consulta de la otra red; un txid de mainnet
|
||||
// salía así hacia la signet.
|
||||
const [auditQuery,setAuditQuery]=useState({q:"",red:""});
|
||||
const redActualRef=useRef("");
|
||||
const [subAnalizar,setSubAnalizar]=useState("auditar");
|
||||
const [subMas,setSubMas]=useState("herramientas");
|
||||
const [walletSignal,setWalletSignal]=useState(0);
|
||||
@@ -17,7 +22,7 @@
|
||||
if (id==="wallet") { setSubAnalizar("auditar"); setWalletSignal(n=>n+1); id="analizar"; }
|
||||
if (id==="auditoria"||id==="lab") { setSubAnalizar(id==="lab"?"explorar":"auditar"); id="analizar"; }
|
||||
if (id==="tools"||id==="docs") { setSubMas(id==="docs"?"ayuda":"herramientas"); id="mas"; }
|
||||
if (q) setAuditQuery(q);
|
||||
if (q) setAuditQuery({q, red: redActualRef.current});
|
||||
setTab(id);
|
||||
try { window.scrollTo({top:0}); } catch {}
|
||||
};
|
||||
@@ -26,13 +31,14 @@
|
||||
setTheme(themeId);
|
||||
// La red activa decide a qué Mempool habla cada pestaña (v1.37.0).
|
||||
const act = configActiva(config);
|
||||
RED.signet = act.red === "signet"; RED.publica = act.publica; RED.sinSistema = act.sinSistema;
|
||||
RED.signet = act.red === "signet"; RED.publica = act.publica; RED.sinSistema = act.sinSistema; RED.urlMain = String(config.url || "").trim();
|
||||
WEB_MEMPOOL.web = act.web || ""; WEB_MEMPOOL.desactivado = !!act.sinEnlaces;
|
||||
// v1.39.1: al cambiar de red (o de nodo) las pestañas se montan de nuevo.
|
||||
// Antes Explorar seguía enseñando el resultado de la otra red (una tb1…
|
||||
// bajo «MAINNET», con un enlace a la Mempool equivocada), y lo mismo
|
||||
// podía pasar con una wallet cargada en Auditoría.
|
||||
const claveRed = `${act.red}|${act.url}`;
|
||||
redActualRef.current = claveRed;
|
||||
|
||||
// Exponer setTab globalmente para que LAB pueda navegar a AUDITORÍA
|
||||
useEffect(()=>{
|
||||
@@ -66,6 +72,7 @@
|
||||
</div>
|
||||
<div style={{padding:"18px 14px",maxWidth:860,margin:"0 auto",width:"100%",flex:1}}>
|
||||
{act.red==="signet"&&<AvisoSignet modo={act.modo} onAjustes={()=>setShowConfig(true)}/>}
|
||||
<AvisoSecreto/>
|
||||
<EstadoNodoBanner base={act.url} onAjustes={()=>setShowConfig(true)}/>
|
||||
{tab==="node" && (
|
||||
<div>
|
||||
@@ -80,7 +87,7 @@
|
||||
<Segmentos color={C.purple} valor={subAnalizar} onCambio={setSubAnalizar}
|
||||
opciones={[{id:"auditar",label:"Auditar privacidad"},{id:"explorar",label:"Explorar la cadena"}]}/>
|
||||
<div style={{display:subAnalizar==="explorar"?"block":"none"}}><Lab key={claveRed} base={act.url}/></div>
|
||||
<div style={{display:subAnalizar==="auditar"?"block":"none"}}><Auditoria key={claveRed} base={act.url} initialQuery={auditQuery} abrirWallet={walletSignal}/></div>
|
||||
<div style={{display:subAnalizar==="auditar"?"block":"none"}}><Auditoria key={claveRed} base={act.url} initialQuery={auditQuery.red===claveRed?auditQuery.q:""} abrirWallet={walletSignal}/></div>
|
||||
</div>
|
||||
{tab==="peritaje" && <SeguimientoFondos key={claveRed} base={act.url} onAuditar={q=>irA("auditoria",q)}/>}
|
||||
{tab==="mas" && (
|
||||
|
||||
Reference in New Issue
Block a user