v1.24.4: nunca «sin gastar» sin pruebas — el historial debe contener la tx que creó la salida y la salida debe estar en /utxo; scripthash al estilo Esplora (sin invertir)

This commit is contained in:
2026-10-13 18:28:43 +00:00
parent e31bf85cbc
commit 34b1a13e17
5 changed files with 168 additions and 59 deletions
+57 -15
View File
@@ -26,8 +26,15 @@
// 7. una salida sin dirección se trataba como «datos, no dinero»;
// 8. el reparto en el origen dividía por el total de la tx (20 % y no 100 %);
// 9. sin dirección no se buscaba el gasto: ahora se pregunta por scripthash
// (sha256 del script, bytes al revés) y, si el Mempool no lo permite,
// se para diciéndolo — nunca como «sin gastar».
// (sha256 del script, en el orden de Esplora) y, si el Mempool no lo
// permite, se para diciéndolo — nunca como «sin gastar».
//
// Visto en el nodo real con la v1.24.3:
// 10. la salida de Hal se dio por «sin gastar» con CERTEZA: el scripthash
// iba con los bytes al revés (estilo Electrum), el nodo devolvió un
// historial vacío y vacío se leyó como «sin gastar». Ahora el historial
// tiene que incluir la tx que creó la salida, y «sin gastar» se confirma
// con la lista de UTXO.
//
// Uso: node tests/test11.js
@@ -62,7 +69,8 @@ const T = new Function(preludio + src + `
paradaSalida: ${def("paradaSalida")}, etiquetaSinDir: ${def("etiquetaSinDir")},
pistasSalida: ${def("pistasSalida")}, salidasPorComprobar: ${def("salidasPorComprobar")},
repartoSalida: ${def("repartoSalida")}, scripthashDe: ${def("scripthashDe")},
findSpendingTx: ${def("findSpendingTx")}, esSalidaDeDatos: ${def("esSalidaDeDatos")} };`)();
estadoSalida: ${def("estadoSalida")}, resultadoVigilancia: ${def("resultadoVigilancia")},
diffVigilancia: ${def("diffVigilancia")}, esSalidaDeDatos: ${def("esSalidaDeDatos")} };`)();
let pass = 0, fail = 0;
function ok(nombre, f, extra) {
@@ -131,8 +139,10 @@ ok("7. ni la pista dice «datos»; nombra la clave pública", () => { const p =
ok("7. se puede comprobar quién la gastó", () => JSON.stringify(T.salidasPorComprobar(TX_A, new Map(), 0)) === "[0]", () => T.salidasPorComprobar(TX_A, new Map(), 0));
const r0 = T.repartoSalida ? T.repartoSalida(1000000000, TX_A, 0, true) : {};
ok("8. en el origen el reparto es el 100 % de la salida robada", () => r0.pct === 100 && r0.sats === 1000000000, r0);
const SH = require("crypto").createHash("sha256").update(Buffer.from(TX_A.vout[0].scriptpubkey, "hex")).digest().reverse().toString("hex");
ok("9. scripthash de la salida de Hal = sha256 del script, bytes al revés", () => T.scripthashDe(TX_A.vout[0].scriptpubkey) === SH, () => [T.scripthashDe && T.scripthashDe(TX_A.vout[0].scriptpubkey), SH]);
const SH = require("crypto").createHash("sha256").update(Buffer.from(TX_A.vout[0].scriptpubkey, "hex")).digest().toString("hex");
const SH_INVERTIDO = Buffer.from(SH, "hex").reverse().toString("hex");
ok("9. scripthash de la salida de Hal = sha256 del script, sin invertir (Esplora)", () => T.scripthashDe(TX_A.vout[0].scriptpubkey) === SH && SH === "799c48c4482e6a9726b0ee7f1609fb83c52a0d63b9c1d0b3fd8770f26e1c4677", () => [T.scripthashDe && T.scripthashDe(TX_A.vout[0].scriptpubkey), SH]);
ok("10. no usa el orden invertido (Electrum), que en el nodo da un historial vacío", () => T.scripthashDe(TX_A.vout[0].scriptpubkey) !== SH_INVERTIDO && SH_INVERTIDO === "77461c6ef27087fdb3d0c1b9630d2ac583fb09167feeb026976a2e48c4489c79");
ok("9. un gasto «no_buscable» para con honestidad, no como «sin gastar»", () => { const p = T.paradaSalida(TX_A, 0, { estado: "no_buscable", err: "x" }); return p?.motivo === "no_buscable" && /no quiere decir que siga sin gastar/.test(p.texto); });
ok("6. frase coherente: hay fallos CERTEZA", () => !/ninguno decisivo/.test(T.fraseBanda(A)), () => T.fraseBanda && [A.band, T.fraseBanda(A)]);
@@ -160,22 +170,54 @@ async function okAsync(nombre, f) {
if (!cond && info) console.log(` ${info}`);
cond ? pass++ : fail++;
}
// Un nodo simulado: rutas -> respuesta (o Error). Anota lo que se pide.
const nodo = (rutas) => { const pedidas = []; const f = async u => { pedidas.push(u); const r = rutas[u]; if (r instanceof Error) throw r; if (r === undefined) throw new Error("el nodo respondió HTTP 404"); return r; }; f.pedidas = pedidas; return f; };
const RAIZ = `/api/scripthash/${SH}`;
const SCRIPT_HAL = TX_A.vout[0].scriptpubkey;
(async () => {
console.log("\n=== Peritaje · buscar el gasto de una salida P2PK ===\n");
const pedidas = [];
const GASTO = { txid: "ab".repeat(32), vin: [{ txid: TX_A.txid, vout: 0 }] };
await okAsync("9. sin dirección pregunta por /api/scripthash/{hash}/txs y encuentra el gasto", async () => {
const r = await T.findSpendingTx(async u => { pedidas.push(u); return u === `/api/scripthash/${SH}/txs` ? [GASTO] : []; }, undefined, TX_A.txid, 0, 8, TX_A.vout[0].scriptpubkey);
return r?.txid === GASTO.txid && pedidas[0] === `/api/scripthash/${SH}/txs`;
console.log("\n=== Peritaje · ¿se gastó la salida de Hal? ===\n");
// Lo que el nodo real devolvió para el scripthash correcto: el gasto
// (bloque 92240) y la tx que creó la salida (bloque 170).
const EA44 = { txid: "ea44e97271691990157559d0bdd9959e02790c34db6c006d779e82fa5aee708e", vin: [{ txid: TX_A.txid, vout: 0 }], vout: [], status: { confirmed: true, block_height: 92240 } };
await okAsync("10. Hal: historial [ea44…, f4184…] → la gastó ea44e972…, se sigue el salto", async () => {
const g = nodo({ [`${RAIZ}/txs`]: [EA44, TX_A] });
const r = await T.estadoSalida(g, undefined, TX_A.txid, 0, 8, SCRIPT_HAL);
return r.estado === "gastada" && r.tx.txid === EA44.txid && g.pedidas[0] === `${RAIZ}/txs`;
});
await okAsync("10. historial vacío → sin conclusión, nunca «sin gastar»", async () => {
try { await T.estadoSalida(nodo({ [`${RAIZ}/txs`]: [], [`${RAIZ}/utxo`]: [] }), undefined, TX_A.txid, 0, 8, SCRIPT_HAL); return false; }
catch (e) { return e.codigo === "inconcluso" && /no incluye la transacción que creó/.test(e.message); }
});
await okAsync("10. historial sin la tx que creó la salida → sin conclusión", async () => {
try { await T.estadoSalida(nodo({ "/api/address/1Otra/txs": [{ txid: "dd".repeat(32), vin: [] }], "/api/address/1Otra/utxo": [] }), "1Otra", TX_A.txid, 0, 8); return false; }
catch (e) { return e.codigo === "inconcluso"; }
});
await okAsync("10. con la creación, sin gasto y fuera de la lista de UTXO → «gastada, no localizada» (dice cuántas páginas)", async () => {
const r = await T.estadoSalida(nodo({ [`${RAIZ}/txs`]: [TX_A], [`${RAIZ}/utxo`]: [] }), undefined, TX_A.txid, 0, 8, SCRIPT_HAL);
const p = T.paradaSalida(TX_A, 0, { estado: r.estado, paginas: r.paginas });
return r.estado === "no_localizada" && r.paginas === 1 && p?.motivo === "no_localizada" && /1 página/.test(p.texto) && !/sin gastar/.test(p.titulo);
});
await okAsync("10. «sin gastar» solo si la lista de UTXO la contiene", async () => {
const r = await T.estadoSalida(nodo({ [`${RAIZ}/txs`]: [TX_A], [`${RAIZ}/utxo`]: [{ txid: TX_A.txid, vout: 0, value: 1000000000 }] }), undefined, TX_A.txid, 0, 8, SCRIPT_HAL);
return r.estado === "sin_gastar";
});
await okAsync("10. si la lista de UTXO falla → sin conclusión, no «sin gastar» con CERTEZA", async () => {
try { await T.estadoSalida(nodo({ [`${RAIZ}/txs`]: [TX_A], [`${RAIZ}/utxo`]: new Error("tiempo agotado") }), undefined, TX_A.txid, 0, 8, SCRIPT_HAL); return false; }
catch (e) { return e.codigo === "inconcluso"; }
});
await okAsync("10. vigilancia: «gastada, no localizada» cuenta como movida, no como «sigue sin moverse»", async () => {
const n = T.resultadoVigilancia({ estado: "no_localizada", paginas: 9 }, 1);
const d = T.diffVigilancia({ checks: [{ fecha: 0, estado: "sin_gastar" }] }, n);
return n.estado === "no_localizada" && d.movida && !/sin moverse/.test(d.texto) && /9 página/.test(d.texto);
});
await okAsync("9. pagina con /txs/chain/{último}", async () => {
const pag1 = Array.from({ length: 25 }, (_, i) => ({ txid: "c" + i, vin: [] }));
const vistas = [];
const r = await T.findSpendingTx(async u => { vistas.push(u); return u.endsWith("/txs") ? pag1 : [GASTO]; }, undefined, TX_A.txid, 0, 8, TX_A.vout[0].scriptpubkey);
return r?.txid === GASTO.txid && vistas[1] === `/api/scripthash/${SH}/txs/chain/c24`;
const g = nodo({ [`${RAIZ}/txs`]: pag1, [`${RAIZ}/txs/chain/c24`]: [EA44, TX_A] });
const r = await T.estadoSalida(g, undefined, TX_A.txid, 0, 8, SCRIPT_HAL);
return r.estado === "gastada" && g.pedidas[1] === `${RAIZ}/txs/chain/c24`;
});
await okAsync("9. un 404 del Mempool da una parada honesta (no_buscable), no «sin gastar»", async () => {
try { await T.findSpendingTx(async () => { throw new Error("el nodo respondió HTTP 404"); }, undefined, TX_A.txid, 0, 8, TX_A.vout[0].scriptpubkey); return false; }
try { await T.estadoSalida(async () => { throw new Error("el nodo respondió HTTP 404"); }, undefined, TX_A.txid, 0, 8, SCRIPT_HAL); return false; }
catch (e) { return e.codigo === "no_buscable" && /pago directo a clave pública/.test(e.message) && /no permite buscar/.test(e.message); }
});
console.log(`\n${pass} correctos, ${fail} fallos`);