Files
txoko-dashboard/tests/test13.js
T

280 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Revisión externa (2026-10-14): casos de prueba derivados del informe de revisión v6/v7.
//
// Cada caso afirma el comportamiento CORRECTO y, contra la v1.24.7, FALLA (✗).
// Se extrae el motor del código de la app igual que test5, test6 y test8, así que
// no puede quedar desactualizado respecto al código que se despliega.
//
// Los identificadores [H-01], [W-02]... remiten a los hallazgos del informe.
// Si una corrección cambia el modelo de forma que el caso ya no tiene sentido
// (por ejemplo, otra política de derivación), conviene sustituir el caso, no
// borrarlo sin más.
//
// Uso: node tests/test13.js (TXOKO_HTML=ruta/dashboard.html para otra ruta)
const fs = require("fs");
const path = require("path");
const nodeCrypto = require("crypto");
const htmlPath = process.env.TXOKO_HTML || "el código de la app (src/)";
const lines = require("./fuente.js")().split("\n");
const cut = (desde, hasta) => {
const s = lines.findIndex(l => l.includes(desde));
const e = lines.findIndex((l, i) => i > s && l.includes(hasta));
if (s === -1 || e === -1) { console.error(`No se localiza ${desde} en el código de la app`); process.exit(1); }
return lines.slice(s, e).join("\n");
};
const preludio = `
const C = { green:"g", amber:"a", red:"r", t2:"t", blue:"b", purple:"p" };
const ENTITY_INDEX = new Map();
const OFAC_SET = new Set();
`;
const motor = cut("// ── FORMATO: lógica pura", "// ── fin formato") + "\n"
+ cut("function detectWallets", "function analyzeAddress") + "\n"
+ cut("function analyzeAddress", "// ── fetch con timeout") + "\n"
+ cut("function behavioralChangeGuess", "// Busca la tx que gasta un output concreto") + "\n"
+ cut("function detectPeelingChains", "// ── Motor de rastreo forense") + "\n"
+ cut("const ALMACEN_PREFIJO", "// ── fin almacén") + "\n"
+ cut("function parsePsbt", "// ── Auditoría de PSBT");
const E = new Function("crypto", preludio + motor + `
return { analyzeTx, analyzeAddress, guessChangeOutput, detectWallets, fraseBanda, roundness,
buildWalletReport, behavioralChangeGuess, combineChangeSignals, detectPeelingChains,
crearAlmacen, parsePsbt, analyzePsbt, ripemd160, deriveAddresses, B32 };`)(nodeCrypto.webcrypto);
let pass = 0, fail = 0;
function ok(nombre, cond, extra) {
console.log(` ${cond ? "✓" : "✗"} ${nombre}`);
if (!cond && extra) console.log(` ${extra}`);
cond ? pass++ : fail++;
}
const check = (r, id) => r.checks.find(c => c.id === id);
const IN = (v,t,a,extra={}) => ({ prevout:{ value:v, scriptpubkey_type:t, scriptpubkey_address:a }, txid:"aa", vout:0, sequence:0xffffffff, ...extra });
const OUT = (v,t,a,spk) => ({ value:v, scriptpubkey_type:t, scriptpubkey_address:a, scriptpubkey: spk || "0014"+"11".repeat(20) });
const OPRET = { value:0, scriptpubkey_type:"op_return", scriptpubkey:"6a0b"+"00".repeat(11), scriptpubkey_address:null };
const TX = (vin, vout, extra={}) => ({ txid:"ff".repeat(32), vin, vout, weight:800, fee:2000, locktime:0, status:{confirmed:true, block_height:955000}, ...extra });
const spk = n => "0014" + String(n).repeat(40).slice(0, 40); // scripts distintos por salida
const WP = "v0_p2wpkh", TR = "v1_p2tr";
// ───────────────────────────────────────────────────────────────────────────
console.log("=== A. Detector de cambio ===\n");
{
// [H-01] señales que apuntan a salidas distintas no dan un cambio PROBABLE
const r = E.guessChangeOutput(TX([IN(1000000,WP,"A")],[OUT(100000,WP,"B"),OUT(898765,TR,"C")]), false);
ok("[H-01] señales contradictorias: no se declara cambio PROBABLE con un índice", !(r.identifiable && r.certainty === "PROBABLE" && r.index != null),
`identifiable=${r.identifiable} index=${r.index} certainty=${r.certainty} señales=${r.signals}`);
}
{
// [H-02] dos salidas reutilizan una dirección de entrada: no se elige la primera con CERTEZA
const r = E.guessChangeOutput(TX([IN(1000000,WP,"A")],[OUT(456789,WP,"A",spk(1)),OUT(541976,WP,"A",spk(2))]), false);
ok("[H-02] dos salidas a la dirección de entrada: no hay CERTEZA con índice único", !(r.certainty === "CERTEZA" && r.index != null),
`index=${r.index} certainty=${r.certainty}`);
}
{
// [H-12] metamórfica: intercambiar el orden de dos salidas no cambia la identificación
const mk = vals => E.guessChangeOutput(TX([IN(1000000,WP,"A")], vals.map((v,i)=>OUT(v,WP,"X"+i,spk(i+1)))), false);
for (const [a,b] of [[300000,695000],[111777,880123]]) {
const r1 = mk([a,b]), r2 = mk([b,a]);
ok(`[H-12] salidas ${a}/${b}: el orden no decide si el cambio es identificable`, r1.identifiable === r2.identifiable,
`[${a},${b}] → ${r1.identifiable}/${r1.certainty}; [${b},${a}] → ${r2.identifiable}/${r2.certainty}`);
}
}
{
// [H-03] el cruce conductual no presupone dos salidas
const c = E.combineChangeSignals({ identifiable:true, index:2, certainty:"POSIBLE" }, { quiet:[2,1], fast:[0] });
ok("[H-03] índice 2 con otra salida también quieta: no «coincide» PROBABLE", c.agreement !== "coincide", `agreement=${c.agreement} certainty=${c.certainty}`);
}
{
// [H-05] sin información de gasto, una salida no es «quieta»
const b = E.behavioralChangeGuess(TX([IN(1000000,WP,"A")],[OUT(400000,WP,"B"),OUT(599000,WP,"C")]), new Map());
ok("[H-05] mapa de gasto vacío: ninguna salida cuenta como quieta", b.quiet.length === 0, `quiet=${JSON.stringify(b.quiet)}`);
}
{
// [H-06] peeling con cambios débiles y discrepantes no llega a CERTEZA
const n = txid => ({ txid, vinCount:1, voutCount:2, changeGuess:{ combined:{ index:0, certainty:"POSIBLE", agreement:"discrepa" } }, fingerprintComparison:{ changed:null } });
const nodes = new Map(["a","b","c"].map(x => [x, n(x)]));
const ch = E.detectPeelingChains(nodes, [{ fromTxid:"a", fromVout:0, toTxid:"b" }, { fromTxid:"b", fromVout:0, toTxid:"c" }]);
ok("[H-06] peeling con eslabones POSIBLE y discrepantes: no CERTEZA", ch.every(c => c.certainty !== "CERTEZA"), JSON.stringify(ch.map(c => c.certainty)));
}
{
// [H-07] CoinJoin genérico: con 5 salidas, 2 iguales no es el 50 %
const vin = [0,1,2,3,4].map(i => IN(100000,WP,"A"+i));
const vout = [10000,10000,12345,23456,443189].map((v,i) => OUT(v,WP,"B"+i,spk(i+1)));
const r = E.analyzeTx(TX(vin, vout, { weight:1500 }));
ok("[H-07] 5 salidas con solo 2 iguales (40 %): no es CoinJoin genérico", check(r,"coinjoin").pass === false, `coinjoin.pass=${check(r,"coinjoin").pass}`);
}
{
// [H-09] añadir un OP_RETURN no borra la señal de cifra redonda
const base = TX([IN(1000000,WP,"A")],[OUT(100000,WP,"B",spk(1)),OUT(898765,WP,"C",spk(2))]);
const r1 = E.analyzeTx(base), r2 = E.analyzeTx({ ...base, vout:[...base.vout, OPRET] });
ok("[H-09] con OP_RETURN la cifra redonda se sigue detectando", check(r1,"round_numbers").pass === check(r2,"round_numbers").pass,
`sin=${check(r1,"round_numbers").pass} con=${check(r2,"round_numbers").pass}`);
}
{
// [H-14] 1 entrada, 1 salida, RBF opt-in, sin locktime de altura: no se nombra Sparrow
const t = TX([IN(925000,WP,"A",{ sequence:0xfffffffc })],[OUT(924776,WP,"B")], { weight:440 });
const nombres = E.detectWallets(t).map(w => w.name);
ok("[H-14] 1-in/1-out con RBF opt-in: no se atribuye a Sparrow (BIP69 vacuo)", !nombres.includes("Sparrow"), `nombres=${JSON.stringify(nombres)}`);
}
{
// [H-15] pago pequeño, cambio grande: una entrada sobra
const r = E.analyzeTx(TX([IN(60000,WP,"A1"),IN(50000,WP,"A2")],[OUT(10000,WP,"P",spk(1)),OUT(99000,TR,"C",spk(2))], { weight:900, fee:1000 }));
ok("[H-15] entradas 60000+50000, salidas 10000+99000: se detecta la entrada de más", check(r,"unnecessary_input").pass === false, `pass=${check(r,"unnecessary_input").pass}`);
}
{
// [F-01] locktime lejos de la altura del bloque no cuenta como «altura actual»
const t = TX([IN(1000000,WP,"A",{ sequence:0xfffffffd })],[OUT(100000,WP,"B",spk(1)),OUT(898765,WP,"C",spk(2))], { locktime:600000, status:{ confirmed:true, block_height:955000 } });
const señales = E.detectWallets(t).flatMap(w => w.signals);
ok("[F-01] locktime 600000 en el bloque 955000: sin señal de «altura de bloque actual»", !señales.some(s => /altura de bloque/.test(s)), JSON.stringify(señales));
}
{
// [D-05] con un check propio fallido, la frase no dice «ningún fallo propio»
const t = TX([IN(925000,WP,"A",{ sequence:0xfffffffc })],[OUT(924776,WP,"B")], { weight:440 });
const r = E.analyzeTx(t);
const hayFallo = r.checks.some(c => !c.pass && !c.informational && !c.heredado);
ok("[D-05] hay un check propio fallido: la frase no dice «ningún fallo propio»", !(hayFallo && /ningún fallo propio/.test(E.fraseBanda(r))), E.fraseBanda(r));
}
// ───────────────────────────────────────────────────────────────────────────
console.log("\n=== B. Direcciones y wallet ===\n");
{
// [W-02] una recepción y un gasto no es reutilización
const a = E.analyzeAddress({ address:"bc1qtest", chain_stats:{ tx_count:2, funded_txo_count:1, spent_txo_count:1, funded_txo_sum:924776 }, utxos:[] });
ok("[W-02] una recepción y un gasto: no «dirección reutilizada»", a.checks.find(c => c.id === "addr_reuse").pass === true);
// [W-09] el titular no puede ser ALTA con un check propio fallido con CERTEZA
const falloCerteza = a.checks.some(c => !c.pass && !c.informational && c.certainty === "CERTEZA");
ok("[W-09] banda ALTA con un check fallido con CERTEZA: no se permite", !(a.band === "ALTA" && falloCerteza), `band=${a.band} score=${a.score}`);
}
{
// [W-04] actividad solo en mempool no es «dirección sin usar»
const a = E.analyzeAddress({ address:"bc1qtest", chain_stats:{ tx_count:0 }, mempool_stats:{ tx_count:1 }, utxos:[] });
ok("[W-04] solo actividad en mempool: no «sin usar»", !a.unused, `band=${a.band}`);
}
{
// [W-03] dos recepciones sin gasto es reutilización de destino
const t1 = TX([IN(11000,WP,"X")],[OUT(10000,WP,"A")], { txid:"11".repeat(32) });
const t2 = TX([IN(21000,WP,"Y")],[OUT(20000,WP,"A")], { txid:"22".repeat(32) });
const rep = E.buildWalletReport([{ addr:"A" }], [t1, t2], new Set(["A"]));
ok("[W-03] dos recepciones en la misma dirección propia: se detecta reutilización", rep.reusedAddrs.length === 1, `reusedAddrs=${rep.reusedAddrs.length}`);
}
{
// [W-08] wallet sin actividad no es banda ALTA
const rep = E.buildWalletReport([], [], new Set(["A","B"]));
ok("[W-08] cero direcciones activas y cero transacciones: la salud no es ALTA", rep.health.band !== "ALTA", `band=${rep.health.band}`);
}
// ───────────────────────────────────────────────────────────────────────────
console.log("\n=== C. PSBT ===\n");
const le = (n,b) => { const x = Buffer.alloc(8); x.writeBigUInt64LE(BigInt(n)); return x.slice(0,b); };
const vi = n => Buffer.from([n]);
const kv = (type,val,keydata=Buffer.alloc(0)) => { const key = Buffer.concat([Buffer.from([type]),keydata]); return Buffer.concat([vi(key.length),key,vi(val.length),val]); };
const SEP = Buffer.from([0]);
const wpkh = b => Buffer.concat([Buffer.from([0,0x14]), Buffer.alloc(20,b)]);
const p2tr = b => Buffer.concat([Buffer.from([0x51,0x20]), Buffer.alloc(32,b)]);
const spkb = s => Buffer.concat([vi(s.length), s]);
const utx = (outs, extra=Buffer.alloc(0)) => { const sq = Buffer.alloc(4); sq.writeUInt32LE(0xfffffffd);
return Buffer.concat([Buffer.from("02000000","hex"), vi(1), Buffer.alloc(32,0x11), Buffer.alloc(4), vi(0), sq, vi(outs.length), ...outs.map(o => Buffer.concat([le(o[0],8), spkb(o[1])])), Buffer.alloc(4), extra]); };
const mk = ({ outs, inVal, inScript=wpkh(1), globalExtra=[], inExtra=[], outMaps=null, txExtra }) =>
Buffer.concat([Buffer.from("70736274ff","hex"), kv(0,utx(outs,txExtra)), ...globalExtra, SEP,
kv(1, Buffer.concat([le(inVal,8), spkb(inScript)])), ...inExtra, SEP,
...(outMaps || outs.map(() => [])).flatMap(m => [...m, SEP])]);
const intenta = b => { try { const p = E.parsePsbt(new Uint8Array(b)); return { ok:true, a:E.analyzePsbt(p) }; } catch (e) { return { ok:false, err:e.message }; } };
{
const r = intenta(mk({ outs:[[90000,wpkh(2)]], inVal:100000, outMaps:[[kv(2,Buffer.alloc(0))]] }));
ok("[P-01] derivación de salida vacía: no se afirma «tu propia cartera»", !r.ok || !r.a.avisos.some(a => a.id === "autoenvio"), r.ok ? r.a.avisos.map(a=>a.id).join(",") : r.err);
}
{
const r = intenta(mk({ outs:[[60000,wpkh(2)],[39000,wpkh(3)]], inVal:100000, globalExtra:[kv(0xfb,Buffer.from([99,0,0,0]))] }));
ok("[P-02] PSBT con versión 99: se rechaza", !r.ok);
}
{
const r = intenta(mk({ outs:[[60000,wpkh(2)],[39000,wpkh(3)]], inVal:100000, txExtra:Buffer.from([0xaa,0xbb]) }));
ok("[P-02] bytes sobrantes dentro de la transacción interior: se rechaza", !r.ok);
}
{
const r = intenta(mk({ outs:[[20000,wpkh(2)],[3000,wpkh(3)]], inVal:10000 }));
ok("[P-05] comisión negativa: aviso o rechazo, nunca «sin problemas»", !r.ok || r.a.avisos.length > 0, r.ok ? `fee=${r.a.resumen.fee}` : r.err);
}
{
const r = intenta(mk({ outs:[[60000,p2tr(2)],[39000,p2tr(3)]], inVal:100000, inScript:p2tr(1), inExtra:[kv(0x13,Buffer.alloc(64,7))] }));
ok("[P-03] firma Taproot (0x13) presente: se cuenta", r.ok && r.a.resumen.firmasPresentes === 1, r.ok ? `firmas=${r.a.resumen.firmasPresentes}` : r.err);
}
// ───────────────────────────────────────────────────────────────────────────
console.log("\n=== D. Almacenamiento ===\n");
const backend = (init={}, limite=15) => { const m = new Map(Object.entries(init)); let falla = false;
return { m, getItem:k => m.get(k) ?? null, setItem:(k,v) => { if (falla || v.length > limite) throw new Error("quota"); m.set(k,v); },
removeItem:k => m.delete(k), key:i => [...m.keys()][i], get length() { return m.size; }, romper(){ falla = true; } }; };
{
const a = E.crearAlmacen(backend());
a.set("tema","old"); a.set("tema","nuevo".repeat(10));
ok("[S-01] escritura fallida por cuota: se lee el último valor", a.get("tema") === "nuevo".repeat(10), `get=${JSON.stringify(a.get("tema"))}`);
}
{
const b = backend({}, 1000); const a = E.crearAlmacen(b);
a.setModoMemoria(true, false); a.set("rastro-mesa", { n:"x".repeat(50) }); b.romper();
a.setModoMemoria(false);
ok("[S-02] salir del modo memoria con el backend roto: los datos no se pierden", a.get("rastro-mesa", null) !== null);
}
{
const b = backend({ "txoko-config":'{"url":"http://nodo","name":"larga larga larga larga"}' }, 20);
const a = E.crearAlmacen(b);
ok("[S-03] migración con cuota insuficiente: la clave antigua no se borra sin copia", a.get("config", null) !== null || b.m.has("txoko-config"));
}
{
const a = E.crearAlmacen(null); a.setModoMemoria(true, true);
ok("[S-05] sin backend, modo memoria activado: modoMemoria() es verdadero", a.modoMemoria() === true);
}
{
const v = E.crearAlmacen(null).validarImport({ app:"txoko", formato:1, datos:{ config:{ url:42 }, "peritaje-mesa":"wrong" } });
ok("[S-04] importación con tipos inválidos: se rechaza", v.ok === false);
}
// ───────────────────────────────────────────────────────────────────────────
console.log("\n=== E. Criptografía ===\n");
{
const hex = a => Buffer.from(a).toString("hex");
const casos = {
"56 bytes (abcdbcde…nopq, vector estándar)": "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"62 bytes (A–Za–z0–9, vector estándar)": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"55 bytes": "x".repeat(55), "57 bytes": "x".repeat(57), "63 bytes": "x".repeat(63),
};
for (const [nombre, s] of Object.entries(casos)) {
const ref = nodeCrypto.createHash("ripemd160").update(Buffer.from(s, "latin1")).digest("hex");
const mio = hex(E.ripemd160(Uint8Array.from(Buffer.from(s, "latin1"))));
ok(`[C-01] RIPEMD-160, ${nombre}`, mio === ref, `obtenido ${mio} esperado ${ref}`);
}
}
// ───────────────────────────────────────────────────────────────────────────
(async () => {
console.log("\n=== F. Derivación de direcciones ===\n");
// [W-01] vectores públicos del mnemónico «abandon»
const ypub = "ypub6Ww3ibxVfGzLrAH1PNcjyAWenMTbbAosGNB6VvmSEgytSER9azLDWCxoJwW7Ke7icmizBMXrzBx9979FfaHxHcrArf3zbeJJJUZPf663zsP";
const xpub = "xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj";
const zpub = "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs";
const d = async k => { try { return (await E.deriveAddresses(k, 1)).receive[0]; } catch (e) { return "ERROR " + e.message; } };
ok("[W-01] zpub (BIP84): P2WPKH", (await d(zpub)) === "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu");
const dy = await d(ypub);
ok("[W-01] ypub (BIP49): P2SH-P2WPKH (37VucY…), o rechazo explícito; nunca bc1q", /^3/.test(dy) || /^ERROR/.test(dy), dy);
// Ajuste en la v1.25 (Claude): una xpub no indica el tipo de dirección, así
// que la política es explícita: se deriva el tipo elegido y, si no se eligió,
// bc1q marcado como SUPUESTO (la pantalla lo dice y ofrece cambiarlo).
const rx = await E.deriveAddresses(xpub, 1);
ok("[W-01] xpub sin tipo elegido: bc1q marcado como supuesto, no silencioso", rx.scriptSupuesto === true && rx.script === "p2wpkh", JSON.stringify({ script:rx.script, sup:rx.scriptSupuesto }));
const rxl = await E.deriveAddresses(xpub, 1, "p2pkh");
ok("[W-01] xpub con legacy elegido: 1LqBGS… (vector BIP44)", rxl.receive[0] === "1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA", rxl.receive[0]);
ok("[W-01] ypub: exactamente 37VucY… (vector BIP49)", dy === "37VucYSaXLCAsxYyAPfbSi9eh4iEcbShgf", dy);
// [W-07] clave maestra (profundidad 0): vector 1 de BIP 32
const maestra = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8";
let valida = true;
try { await E.B32.decodeBase58Check(maestra); } catch { valida = false; }
if (!valida) console.log(" · [W-07] vector maestro no verificado (checksum): caso omitido");
// Ajuste en la v1.25 (Claude): se avisa en vez de rechazar, porque algunas
// wallets antiguas (Electrum) sí derivan m/0/i desde la clave maestra.
else { const rm = await E.deriveAddresses(maestra, 1); ok("[W-07] clave de profundidad 0: se avisa", rm.avisos.length > 0 && rm.profundidad === 0, JSON.stringify(rm.avisos)); }
console.log(`\nRESULTADO: ${pass} correctas, ${fail} incorrectas (contra la v1.24.7 se esperan fallos: cada ✗ es un hallazgo abierto)`);
process.exit(fail ? 1 : 0);
})();