Files
txoko-dashboard/tests/test37.js
T

175 lines
13 KiB
JavaScript

// v1.48.1 — segundo parche de la auditoría en frío: validaciones de formato.
//
// · A2-03: un testigo final vacío ya no cuenta como «firma final puesta».
// · A2-04: claves BIP32 de profundidad 0 con padre o índice ≠ 0 (vectores
// inválidos oficiales de BIP32) se rechazan.
// · A2-05: importes de más de 21 millones de BTC en una PSBT se rechazan.
// · A2-06: witness_utxo con longitud de script en CompactSize de 3 bytes.
// · A2-07: BBQr comprimido con tope de 4 MB al descomprimir.
// · A3-06: direcciones bech32 con relleno inválido (BIP173) se rechazan.
// · A3-07: un «autoenvío» con una entrada sin dirección (P2PK) no se afirma.
// · A4-03: el reparto proporcional conserva la suma.
// · A4-07: las notas y declaraciones van como cita en el Markdown.
// · A1-04: «Borrar todo» no deja que lo que estaba en vuelo repueble la caché.
//
// Uso: node tests/test37.js
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 fn = (cabecera) => {
const s = lines.findIndex(l => l.startsWith(cabecera));
const e = lines.findIndex((l, i) => i > s && l === " }");
if (s === -1 || e === -1) { console.error(`No se localiza «${cabecera}»`); process.exit(1); }
return lines.slice(s, e + 1).join("\n");
};
let pass = 0, fail = 0;
const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c && x !== undefined) console.log(" " + x); c ? pass++ : fail++; };
// ── PSBT de prueba, construida aquí byte a byte ─────────────────────────
const hex = h => Uint8Array.from(h.match(/../g).map(x => parseInt(x, 16)));
const cat = (...a) => { const n = a.reduce((s, x) => s + x.length, 0), o = new Uint8Array(n); let p = 0; for (const x of a) { o.set(x, p); p += x.length; } return o; };
const cs = n => n < 0xfd ? Uint8Array.of(n) : n <= 0xffff ? Uint8Array.of(0xfd, n & 255, n >> 8) : (() => { throw new Error("cs"); })();
const u32 = n => Uint8Array.of(n & 255, (n >> 8) & 255, (n >> 16) & 255, (n >>> 24) & 255);
const u64 = n => { let v = BigInt(n); const o = new Uint8Array(8); for (let i = 0; i < 8; i++) { o[i] = Number(v & 255n); v >>= 8n; } return o; };
const par = (tipo, valor, clave = new Uint8Array(0)) => cat(cs(1 + clave.length), Uint8Array.of(tipo), clave, cs(valor.length), valor);
const SPK = hex("0014" + "11".repeat(20));
function psbt({ salidas = [[90000, SPK]], entrada = [] } = {}) {
const tx = cat(u32(2), cs(1), hex("22".repeat(32)), u32(0), cs(0), u32(0xfffffffd),
cs(salidas.length), ...salidas.flatMap(([v, s]) => [u64(v), cs(s.length), s]), u32(0));
return cat(hex("70736274ff"), par(0x00, tx), Uint8Array.of(0), ...entrada, Uint8Array.of(0), ...salidas.map(() => Uint8Array.of(0)));
}
const P = new Function(`const fmtBtc = s => (s / 1e8).toFixed(8) + " BTC";
${fn(" function sha256Bytes(")}
${cut("// ── Parser PSBT (BIP174)", "const PSBT_TIPOS")}
${fn(" function leerTxPrevia(")}
${cut("// ── ¿Lo firmado es lo auditado?", "// ── fin comparar")}
return { parsePsbt, compararFirmada };`)();
const rechaza = (f, re) => { try { f(); return false; } catch (e) { return re ? re.test(e.message) : true; } };
(async () => {
console.log("=== PSBT: firmas finales, importes y CompactSize (A2-03, A2-05, A2-06) ===\n");
{
const base = psbt();
const vacio = psbt({ entrada: [par(0x08, new Uint8Array(0))] });
ok("[A2-03] testigo final vacío → PSBT rechazada (antes: «todas las entradas terminadas»)", rechaza(() => P.parsePsbt(vacio), /firma final/));
const ceroElementos = psbt({ entrada: [par(0x08, Uint8Array.of(0))] });
ok("[A2-03] testigo final con 0 elementos → rechazado", rechaza(() => P.parsePsbt(ceroElementos), /firma final/));
const bueno = psbt({ entrada: [par(0x08, cat(Uint8Array.of(2), cs(71), new Uint8Array(71).fill(0x30), cs(33), Uint8Array.of(2, ...new Array(32).fill(7))))] });
const r = P.compararFirmada(P.parsePsbt(base), bueno);
ok("[A2-03] testigo final bien formado → «final»", r.igual && r.completa && r.firmas[0].estado === "final", JSON.stringify(r.firmas));
ok("[A2-05] salida de 9.007.199.254.740.993 sat → rechazada (antes perdía precisión)", rechaza(() => P.parsePsbt(psbt({ salidas: [[9007199254740993n, SPK]] })), /21 millones/));
ok("[A2-05] salida de 21 millones de BTC justos → se acepta", !rechaza(() => P.parsePsbt(psbt({ salidas: [[2100000000000000n, SPK]] }))));
const largo = new Uint8Array(253).fill(0x51);
const wu = psbt({ entrada: [par(0x01, cat(u64(2000), cs(253), largo))] });
ok("[A2-06] witness_utxo con script de 253 bytes (CompactSize fd fd 00) → se acepta", !rechaza(() => P.parsePsbt(wu)), (() => { try { P.parsePsbt(wu); } catch (e) { return e.message; } })());
const wuMal = psbt({ entrada: [par(0x01, cat(u64(2000), cs(253), largo.slice(1)))] });
ok("[A2-06] …y si la longitud no cuadra con el script, se rechaza", rechaza(() => P.parsePsbt(wuMal), /witness_utxo/));
}
console.log("\n=== BIP32: vectores inválidos oficiales (A2-04) ===\n");
{
const K = require("./extraer-cripto.js");
for (const [n, x] of [
["profundidad 0 con huella de padre ≠ 0", "xpub661no6RGEX3uJkY4bNnPcw4URcQTrSibUZ4NqJEw5eBkv7ovTwgiT91XX27VbEXGENhYRCf7hyEbWrR3FewATdCEebj6znwMfQkhRYHRLpJ"],
["profundidad 0 con índice de hijo ≠ 0", "xpub661MyMwAuDcm6CRQ5N4qiHKrJ39Xe1R1NyfouMKTTWcguwVcfrZJaNvhpebzGerh7gucBvzEQWRugZDuDXjNDRmXzSZe4c7mnTK97pTvGS8"],
]) {
let msg = null; try { await K.deriveAddresses(x, 1); } catch (e) { msg = e.message; }
ok(`[A2-04] ${n} → rechazada`, /no es válida/.test(msg || ""), msg);
msg = null; try { await K.analizarEntradaWallet(x, "bc"); } catch (e) { msg = e.message; }
ok(`[A2-04] …también al pegarla en el campo de la wallet`, /no es válida/.test(msg || ""), msg);
}
const buena = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8";
let r = null; try { r = await K.deriveAddresses(buena, 1); } catch (e) { r = e.message; }
ok("[A2-04] la maestra válida del vector 1 de BIP32 se sigue aceptando", r && r.receive && r.receive.length === 1, r);
}
console.log("\n=== BBQr con tope al descomprimir (A2-07) ===\n");
{
const Q = new Function(`${fn(" async function inflarCrudo(")} return { inflarCrudo };`)();
const zlib = require("zlib");
const bomba = zlib.deflateRawSync(Buffer.alloc(6000000));
ok("la prueba usa un contenido pequeño que se expande mucho", bomba.length < 10000, bomba.length);
let msg = null; try { await Q.inflarCrudo(new Uint8Array(bomba)); } catch (e) { msg = e.message; }
ok("[A2-07] más de 4 MB al descomprimir → se para y se dice", /4 MB/.test(msg || ""), msg);
const normal = zlib.deflateRawSync(Buffer.from("hola ".repeat(1000)));
const out = await Q.inflarCrudo(new Uint8Array(normal));
ok("[A2-07] un contenido normal se descomprime igual que antes", Buffer.from(out).toString() === "hola ".repeat(1000));
}
console.log("\n=== Direcciones bech32 con relleno inválido (A3-06) ===\n");
{
const S = new Function(`const C = {}; const ENTITY_INDEX = new Map(); const OFAC_SET = new Set();
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
${cut("// ── SIMULADOR DE GASTO", "// ── fin simulador")}
return { tipoDireccion };`)();
const mal = S.tipoDireccion("bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpk5k97m");
ok("[A3-06] la dirección del auditor (suma bien, relleno mal) → rechazada", !!mal.error && /relleno/.test(mal.error), JSON.stringify(mal));
const bien = S.tipoDireccion("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu");
ok("[A3-06] una dirección BIP84 real sigue valiendo", bien.tipo === "v0_p2wpkh", JSON.stringify(bien));
const tr = S.tipoDireccion("bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0");
ok("[A3-06] y una Taproot del vector de BIP350", tr.tipo === "v1_p2tr", JSON.stringify(tr));
}
console.log("\n=== Autoenvío con una entrada sin dirección (A3-07) ===\n");
{
const W = new Function(`const C = {}; const ENTITY_INDEX = new Map(); const OFAC_SET = new Set();
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
${cut("function detectWallets", "function analyzeAddress")}
return { buildWalletReport };`)();
const A = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu";
const tx = (ins, outs) => ({ txid: "ab".repeat(32), status: { confirmed: true, block_height: 900000, block_time: 1790000000 }, fee: 1000, weight: 800, version: 2, locktime: 0,
vin: ins.map((p, i) => ({ txid: (i + 1).toString(16).padStart(64, "0"), vout: 0, sequence: 0xfffffffd, prevout: p })),
vout: outs });
const conP2pk = tx([{ value: 20000, scriptpubkey_type: "v0_p2wpkh", scriptpubkey_address: A, scriptpubkey: "0014" + "11".repeat(20) },
{ value: 20000, scriptpubkey_type: "p2pk", scriptpubkey: "21" + "02".repeat(33) + "ac" }],
[{ value: 39000, scriptpubkey_type: "v0_p2wpkh", scriptpubkey_address: A, scriptpubkey: "0014" + "11".repeat(20) }]);
const r = W.buildWalletReport([{ addr: A }], [conP2pk], new Set([A]));
ok("[A3-07] una entrada P2PK ajena ya no permite afirmar «envío a ti mismo»", (r.autoenvios || []).length === 0, JSON.stringify(r.autoenvios));
const todoMio = tx([{ value: 20000, scriptpubkey_type: "v0_p2wpkh", scriptpubkey_address: A, scriptpubkey: "0014" + "11".repeat(20) }],
[{ value: 19000, scriptpubkey_type: "v0_p2wpkh", scriptpubkey_address: A, scriptpubkey: "0014" + "11".repeat(20) }, { value: 0, scriptpubkey_type: "op_return", scriptpubkey: "6a00" }]);
ok("[A3-07] …pero uno de verdad, aunque lleve un OP_RETURN, sí", (W.buildWalletReport([{ addr: A }], [todoMio], new Set([A])).autoenvios || []).length === 1);
}
console.log("\n=== Reparto que conserva la suma (A4-03) y notas como cita (A4-07) ===\n");
{
const R = new Function(`${fn(" function repartoSalida(")} return { repartoSalida };`)();
const t = { vin: [{ prevout: { value: 1001 } }, { prevout: { value: 1001 } }], vout: [{ value: 1001 }, { value: 1001 }] };
const suma = [0, 1].reduce((s, i) => s + R.repartoSalida(1001, t, i, false).sats, 0);
ok("[A4-03] 1.001 sat seguidos en dos mitades: se reparten 1.001, no 1.002", suma === 1001, suma);
const t3 = { vin: [{ prevout: { value: 3 } }], vout: [{ value: 1 }, { value: 1 }, { value: 1 }] };
ok("[A4-03] y el reparto es siempre el mismo (empates por orden)", [0, 1, 2].map(i => R.repartoSalida(2, t3, i, false).sats).join(",") === "1,1,0");
const conFee = { vin: [{ prevout: { value: 1000 } }], vout: [{ value: 600 }, { value: 300 }] };
const s2 = [0, 1].reduce((s, i) => s + R.repartoSalida(777, conFee, i, false).sats, 0);
ok("[A4-03] con comisión: lo repartido a las salidas no pasa de lo seguido", s2 <= 777 && s2 >= 777 - Math.ceil(777 * 100 / 1000), s2);
const F = new Function(`${cut("// ── FORMATO: lógica pura", "// ── fin formato")} return { citaMD };`)();
const c = F.citaMD("Normal\n\n## Conclusión verificada\n[HECHO] Una conclusión que no produjo el motor.");
ok("[A4-07] la nota del auditor queda entera dentro de una cita", c.split("\n").every(l => l.startsWith("> ")), c);
ok("[A4-07] y ni el «##» ni el «[HECHO]» funcionan como Markdown", !/^> ##/m.test(c) && /\\\[HECHO\\\]/.test(c), c);
}
console.log("\n=== «Borrar todo» y lo que está en vuelo (A1-04) ===\n");
{
let suelta;
const fetchFalso = () => new Promise(res => { suelta = () => res({ ok: true, status: 200, json: async () => ({ dato: 1 }), text: async () => "" }); });
const R = new Function("fetch", `const useState = v => [v, () => {}]; const useEffect = () => {}; const useCallback = f => f; const RED = { signet: false, urlMain: "" };
${cut("// ── fetch con timeout", " const fmt = {")}
return { apiGetJson, apiCache, apiInflight, API_GEN };`)(fetchFalso);
const p = R.apiGetJson("https://nodo", "/api/v1/fees/recommended");
await new Promise(r => setTimeout(r, 10));
R.API_GEN.n++; R.apiCache.clear(); R.apiInflight.clear(); // lo que hace «Borrar todo»
suelta(); await p;
ok("[A1-04] la respuesta que llega después de borrar no vuelve a la caché", R.apiCache.size === 0, R.apiCache.size);
const p2 = R.apiGetJson("https://nodo", "/api/v1/fees/recommended"); await new Promise(r => setTimeout(r, 10)); suelta(); await p2;
ok("[A1-04] y las consultas nuevas sí se guardan, como siempre", R.apiCache.size === 1);
}
console.log(`\n${pass} correctas, ${fail} fallidas`);
process.exit(fail ? 1 : 0);
})();