v1.48.1: auditoría en frío, parche 3 — validaciones de formato, fuera el motor automático, transacciones reales como pruebas
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
@@ -11,6 +11,28 @@ y el versionado sigue [Versionado Semántico](https://semver.org/lang/es/):
|
|||||||
- **PARCHE** — arreglos de errores
|
- **PARCHE** — arreglos de errores
|
||||||
|
|
||||||
---
|
---
|
||||||
|
## [1.48.1] — 2026-10-25
|
||||||
|
|
||||||
|
Segundo parche de la **auditoría en frío**: validaciones de formato y limpieza. Casi nada se ve desde fuera; lo que cambia es que ciertos datos mal formados o malintencionados ya no pasan.
|
||||||
|
|
||||||
|
### Corregido
|
||||||
|
- **PSBT:** un testigo de firma final vacío contaba como «todas las entradas terminadas (firma final puesta)»; ahora el campo tiene que tener su estructura (A2-03). Un importe de más de 21 millones de BTC se aceptaba y perdía precisión; ahora se rechaza (A2-05). La longitud del script de `witness_utxo` se lee como CompactSize, como dice BIP174; antes un script de 253 bytes o más se daba por inválido (A2-06).
|
||||||
|
- **Claves extendidas:** una clave maestra (profundidad 0) con huella de padre o número de hijo se aceptaba; BIP32 la declara inválida y ahora se rechaza, al derivar y al pegarla en el campo de la wallet (A2-04).
|
||||||
|
- **BBQr comprimido:** se descomprime por trozos con un tope de 4 MB, el mismo que el del UR. Un QR pequeño muy comprimido podía colgar el navegador (A2-07).
|
||||||
|
- **Simulador:** las direcciones bech32 con relleno inválido (BIP173) se aceptaban como destino; ahora se rechazan (A3-06).
|
||||||
|
- **Informe de wallet:** una transacción con una entrada o salida con dinero y sin dirección (P2PK, script raro) podía salir como «envío a ti mismo»; ya no se afirma sin poder atribuir todas (A3-07).
|
||||||
|
- **Seguimiento:** el reparto proporcional redondeaba cada salida por su cuenta y podía repartir más de lo seguido (1.001 sat → 1.002). Ahora conserva la suma, con enteros grandes y siempre el mismo resultado (A4-03).
|
||||||
|
- **Informes en Markdown:** las notas y la declaración del afectado van como cita, línea a línea y con los signos de Markdown escapados. Una nota que empezara por «## Conclusión» parecía parte del informe (A4-07).
|
||||||
|
- **Explorar, búsqueda por altura de bloque:** no funcionaba (el nodo da el hash en texto y se leía como JSON) y con una altura inexistente pedía `/api/block/null`. Ahora encuentra el bloque y, si no existe, lo dice (A5-05).
|
||||||
|
- **«Borrar todo»:** una respuesta que llegaba después de borrar volvía a meterse en la caché en memoria (A1-04).
|
||||||
|
|
||||||
|
### Quitado
|
||||||
|
- **El motor de rastreo automático** (`initForensicTrace`, `advanceForensicHop`, `buildForensicGraph`, `finalizeForensicGraph`), unas 350 líneas que ninguna pantalla usaba desde que Seguimiento va salto a salto. Sus topes de nodos y de consultas no se cumplían (A4-04, A4-05). Se conservan las piezas que sí se usan o se prueban.
|
||||||
|
|
||||||
|
### Pruebas
|
||||||
|
- `tests/test37.js` (nuevo): un caso por arreglo, cada uno comprobado también sin el arreglo para ver que falla (con vectores oficiales de BIP32, BIP84 y BIP350).
|
||||||
|
- `tests/test38.js` (nuevo) y `tests/fixtures/contraste-25oct.json`: las transacciones reales del contraste con am-i-exposed y Blockchair (Whirlpool, JoinMarket/Stonewall, Taproot con OP_RETURN, pago simple, polvo, escrow de HodlHodl, barrido, Satoshi → Hal; se recalcula el txid para comprobar que los datos son los de la cadena). Lo que Txoko ya lee bien está protegido; lo que tiene que arreglar el **parche 2** se lista como pendiente.
|
||||||
|
|
||||||
## [1.48.0] — 2026-10-25
|
## [1.48.0] — 2026-10-25
|
||||||
|
|
||||||
Primer parche de la **auditoría en frío** del 25-oct (una IA externa revisó el código por tandas; cada hallazgo se comprobó contra el código antes de arreglarlo). Este va de redes, secretos y garantías que la app daba sin haberlas comprobado.
|
Primer parche de la **auditoría en frío** del 25-oct (una IA externa revisó el código por tandas; cada hallazgo se comprobó contra el código antes de arreglarlo). Este va de redes, secretos y garantías que la app daba sin haberlas comprobado.
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
// Versión de la app: la usan el pie de página y la cabecera del informe
|
// 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.
|
// de seguimiento. Una sola constante para que no se desalineen.
|
||||||
const VERSION_APP = "1.48.0";
|
const VERSION_APP = "1.48.1";
|
||||||
|
|
||||||
// Detecta pantalla estrecha (móvil) y se reajusta al rotar/redimensionar.
|
// Detecta pantalla estrecha (móvil) y se reajusta al rotar/redimensionar.
|
||||||
// Reutilizable para adaptar cualquier vista a móvil sin media queries CSS.
|
// Reutilizable para adaptar cualquier vista a móvil sin media queries CSS.
|
||||||
|
|||||||
@@ -221,5 +221,13 @@
|
|||||||
const partes = claves.map(k => ENTITY_FUENTES[k]).filter(Boolean).map(f => `${f.fuente}, en la app desde el ${fechaEntidad(f.incorporado)}`);
|
const partes = claves.map(k => ENTITY_FUENTES[k]).filter(Boolean).map(f => `${f.fuente}, en la app desde el ${fechaEntidad(f.incorporado)}`);
|
||||||
return partes.length ? `Fuente: ${partes.join("; ")}. Es una copia local que la app no actualiza sola: no se ha comprobado si sigue vigente.` : "Fuente: índice local de la app, sin fecha de comprobación.";
|
return partes.length ? `Fuente: ${partes.join("; ")}. Es una copia local que la app no actualiza sola: no se ha comprobado si sigue vigente.` : "Fuente: índice local de la app, sin fecha de comprobación.";
|
||||||
}
|
}
|
||||||
|
// Texto escrito por la persona (notas, declaraciones) dentro de un
|
||||||
|
// informe Markdown: siempre como cita, línea a línea, y con los signos que
|
||||||
|
// abrirían una sección, una lista, una tabla o un código escapados. Así
|
||||||
|
// una nota que empiece por «## Conclusión» no parece parte del informe
|
||||||
|
// (v1.48.1, auditoría A4-07).
|
||||||
|
const citaMD = texto => String(texto ?? "").replace(/\r\n?/g, "\n").split("\n")
|
||||||
|
.map(l => "> " + l.replace(/[\\`*_\[\]|<>]/g, c => "\\" + c).replace(/^(\s*)([#>+-])/, "$1\\$2").replace(/^(\s*)(\d+)\./, "$1$2\\."))
|
||||||
|
.join("\n");
|
||||||
// ── fin formato ─────────────────────────────────────────────────────────
|
// ── fin formato ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|||||||
+16
-2
@@ -295,9 +295,23 @@
|
|||||||
}
|
}
|
||||||
async function inflarCrudo(bytes) {
|
async function inflarCrudo(bytes) {
|
||||||
if (typeof DecompressionStream === "undefined") throw new Error("Este navegador no sabe descomprimir el BBQr. Prueba con otro o pide al monedero el QR sin comprimir.");
|
if (typeof DecompressionStream === "undefined") throw new Error("Este navegador no sabe descomprimir el BBQr. Prueba con otro o pide al monedero el QR sin comprimir.");
|
||||||
|
// v1.48.1 (auditoría A2-07): se descomprime por trozos con un tope de
|
||||||
|
// 4 MB, el mismo que el del UR. Antes se materializaba todo de golpe: un
|
||||||
|
// QR pequeño muy comprimido podía colgar el navegador.
|
||||||
|
const MAX = 4000000;
|
||||||
const ds = new DecompressionStream("deflate-raw");
|
const ds = new DecompressionStream("deflate-raw");
|
||||||
const buf = await new Response(new Blob([bytes]).stream().pipeThrough(ds)).arrayBuffer();
|
const lector = new Blob([bytes]).stream().pipeThrough(ds).getReader();
|
||||||
return new Uint8Array(buf);
|
const trozos = []; let total = 0;
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await lector.read();
|
||||||
|
if (done) break;
|
||||||
|
total += value.length;
|
||||||
|
if (total > MAX) { try { await lector.cancel(); } catch {} throw new Error("BBQr: al descomprimirlo supera los 4 MB; no se lee."); }
|
||||||
|
trozos.push(value);
|
||||||
|
}
|
||||||
|
const out = new Uint8Array(total); let o = 0;
|
||||||
|
for (const t of trozos) { out.set(t, o); o += t.length; }
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── El colector: recibe lo que lee la cámara, trozo a trozo ─────────────
|
// ── El colector: recibe lo que lee la cámara, trozo a trozo ─────────────
|
||||||
|
|||||||
@@ -345,6 +345,14 @@
|
|||||||
// que dice un descriptor y manda sobre el prefijo de la clave: en
|
// que dice un descriptor y manda sobre el prefijo de la clave: en
|
||||||
// wpkh(ypub…) gana wpkh. `ramas` dice qué ramas derivar ([0] recepción,
|
// wpkh(ypub…) gana wpkh. `ramas` dice qué ramas derivar ([0] recepción,
|
||||||
// [1] cambio, [0,1] las dos); sin él, las dos, como siempre.
|
// [1] cambio, [0,1] las dos); sin él, las dos, como siempre.
|
||||||
|
// v1.48.1 (auditoría A2-04): BIP32 declara inválida una clave maestra
|
||||||
|
// (profundidad 0) con huella del padre o índice distintos de cero. Antes
|
||||||
|
// se aceptaba y se derivaban direcciones de una clave mal formada.
|
||||||
|
function comprobarMetadatosBip32(raw, err) {
|
||||||
|
const ceros = a => a.every(b => b === 0);
|
||||||
|
if (raw[4] === 0 && (!ceros(Array.from(raw.slice(5, 9))) || !ceros(Array.from(raw.slice(9, 13)))))
|
||||||
|
throw err("Esta clave extendida no es válida: dice ser una clave maestra (profundidad 0) pero trae huella de padre o número de hijo. Suele ser una clave mal copiada o mal generada.");
|
||||||
|
}
|
||||||
const deriveAddresses = async (xpubStr, count=20, scriptElegido=null, opciones={}) => {
|
const deriveAddresses = async (xpubStr, count=20, scriptElegido=null, opciones={}) => {
|
||||||
// decodeBase58Check comprueba la suma de verificación: un carácter mal
|
// decodeBase58Check comprueba la suma de verificación: un carácter mal
|
||||||
// copiado se detecta aquí y no acaba generando direcciones ajenas.
|
// copiado se detecta aquí y no acaba generando direcciones ajenas.
|
||||||
@@ -357,6 +365,7 @@
|
|||||||
const version = Array.from(raw.slice(0,4)).map(b=>b.toString(16).padStart(2,"0")).join("");
|
const version = Array.from(raw.slice(0,4)).map(b=>b.toString(16).padStart(2,"0")).join("");
|
||||||
const info = XPUB_VERSIONS[version];
|
const info = XPUB_VERSIONS[version];
|
||||||
if (!info) throw new Error(`Formato de clave extendida no reconocido (versión ${version}).`);
|
if (!info) throw new Error(`Formato de clave extendida no reconocido (versión ${version}).`);
|
||||||
|
comprobarMetadatosBip32(raw, m => new Error(m));
|
||||||
if (info.multisig) throw new Error(`Una ${info.tipo} es la clave de un participante de una wallet multifirma. Las direcciones de una multifirma dependen de todas las claves a la vez, así que con esta sola no se pueden calcular.`);
|
if (info.multisig) throw new Error(`Una ${info.tipo} es la clave de un participante de una wallet multifirma. Las direcciones de una multifirma dependen de todas las claves a la vez, así que con esta sola no se pueden calcular.`);
|
||||||
// Tipo de dirección: el que indica el prefijo; si no indica ninguno
|
// Tipo de dirección: el que indica el prefijo; si no indica ninguno
|
||||||
// (xpub/tpub), el elegido; si no se eligió, SegWit nativa, y se marca
|
// (xpub/tpub), el elegido; si no se eligió, SegWit nativa, y se marca
|
||||||
@@ -499,6 +508,7 @@
|
|||||||
const info = XPUB_VERSIONS[version];
|
const info = XPUB_VERSIONS[version];
|
||||||
if (!info) throw errorWallet(`Formato de clave extendida no reconocido (versión ${version}).`);
|
if (!info) throw errorWallet(`Formato de clave extendida no reconocido (versión ${version}).`);
|
||||||
if (info.multisig) throw errorWallet(MSG_MULTIFIRMA, { clase: "multifirma" });
|
if (info.multisig) throw errorWallet(MSG_MULTIFIRMA, { clase: "multifirma" });
|
||||||
|
comprobarMetadatosBip32(raw, m => errorWallet(m));
|
||||||
return info;
|
return info;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -173,7 +173,14 @@
|
|||||||
// medio. Se paga una comisión por empeorar la propia privacidad.
|
// medio. Se paga una comisión por empeorar la propia privacidad.
|
||||||
const autoenvios = [];
|
const autoenvios = [];
|
||||||
for (const tx of txs) {
|
for (const tx of txs) {
|
||||||
const ins = (tx.vin || []).map(v => v.prevout?.scriptpubkey_address).filter(Boolean);
|
// v1.48.1 (auditoría A3-07): una entrada o una salida con dinero y sin
|
||||||
|
// dirección (P2PK, script raro) no se puede atribuir a la wallet, así
|
||||||
|
// que no se puede afirmar que sea un envío a uno mismo. Antes se
|
||||||
|
// descartaban y bastaba con que el resto fuera tuyo. (Los OP_RETURN,
|
||||||
|
// sin dinero, no cuentan.)
|
||||||
|
if ((tx.vin || []).some(v => !v.prevout?.scriptpubkey_address)) continue;
|
||||||
|
if ((tx.vout || []).some(v => (v.value || 0) > 0 && !v.scriptpubkey_address)) continue;
|
||||||
|
const ins = (tx.vin || []).map(v => v.prevout.scriptpubkey_address);
|
||||||
const outs = (tx.vout || []).map(v => v.scriptpubkey_address).filter(Boolean);
|
const outs = (tx.vout || []).map(v => v.scriptpubkey_address).filter(Boolean);
|
||||||
if (ins.length === 0 || outs.length === 0) continue;
|
if (ins.length === 0 || outs.length === 0) continue;
|
||||||
// Todas las entradas Y todas las salidas dentro del propio wallet.
|
// Todas las entradas Y todas las salidas dentro del propio wallet.
|
||||||
|
|||||||
@@ -59,6 +59,9 @@
|
|||||||
const version = datos[0];
|
const version = datos[0];
|
||||||
let acc = 0, bits = 0; const prog = [];
|
let acc = 0, bits = 0; const prog = [];
|
||||||
for (const d of datos.slice(1, -6)) { acc = (acc << 5) | d; bits += 5; while (bits >= 8) { bits -= 8; prog.push((acc >> bits) & 255); } }
|
for (const d of datos.slice(1, -6)) { acc = (acc << 5) | d; bits += 5; while (bits >= 8) { bits -= 8; prog.push((acc >> bits) & 255); } }
|
||||||
|
// v1.48.1 (auditoría A3-06): BIP173 obliga a rechazar el relleno
|
||||||
|
// inválido (5 bits o más sobrantes, o bits sobrantes que no son cero).
|
||||||
|
if (bits >= 5 || (acc & ((1 << bits) - 1)) !== 0) return { error: "La dirección no es válida (relleno incorrecto): suele ser un carácter mal copiado." };
|
||||||
if (version === 0 && variante === "bech32" && prog.length === 20) return { tipo: "v0_p2wpkh", scriptpubkey: "0014" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
if (version === 0 && variante === "bech32" && prog.length === 20) return { tipo: "v0_p2wpkh", scriptpubkey: "0014" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
||||||
if (version === 0 && variante === "bech32" && prog.length === 32) return { tipo: "v0_p2wsh", scriptpubkey: "0020" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
if (version === 0 && variante === "bech32" && prog.length === 32) return { tipo: "v0_p2wsh", scriptpubkey: "0020" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
||||||
if (version === 1 && variante === "bech32m" && prog.length === 32) return { tipo: "v1_p2tr", scriptpubkey: "5120" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
if (version === 1 && variante === "bech32m" && prog.length === 32) return { tipo: "v1_p2tr", scriptpubkey: "5120" + hex(prog), red: hrp === "bc" ? "bc" : "tb" };
|
||||||
|
|||||||
+7
-2
@@ -76,6 +76,10 @@
|
|||||||
// mismo a la vez generan UNA petición al nodo, no dos.
|
// mismo a la vez generan UNA petición al nodo, no dos.
|
||||||
const apiCache = new Map(); // clave -> { at, data, ttl }
|
const apiCache = new Map(); // clave -> { at, data, ttl }
|
||||||
const apiInflight = new Map(); // clave -> Promise en vuelo
|
const apiInflight = new Map(); // clave -> Promise en vuelo
|
||||||
|
// v1.48.1 (auditoría A1-04): «Borrar todo» sube la generación; una
|
||||||
|
// respuesta que llegue después de borrar ya no vuelve a meterse en la
|
||||||
|
// caché (antes se repoblaba con lo que estaba en vuelo).
|
||||||
|
const API_GEN = { n: 0 };
|
||||||
const API_CACHE_MAX = 400; // tope de entradas, para no crecer sin fin
|
const API_CACHE_MAX = 400; // tope de entradas, para no crecer sin fin
|
||||||
|
|
||||||
// Cuánto vale una respuesta depende de lo que sea. Una transacción ya
|
// Cuánto vale una respuesta depende de lo que sea. Una transacción ya
|
||||||
@@ -122,12 +126,13 @@
|
|||||||
const flying = apiInflight.get(key);
|
const flying = apiInflight.get(key);
|
||||||
if (flying) return flying; // ya hay una petición idéntica en curso
|
if (flying) return flying; // ya hay una petición idéntica en curso
|
||||||
|
|
||||||
|
const gen = API_GEN.n;
|
||||||
const p = (async () => {
|
const p = (async () => {
|
||||||
const res = await fetchWithTimeout(key);
|
const res = await fetchWithTimeout(key);
|
||||||
if (!res.ok) throw new Error(`el nodo respondió HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`el nodo respondió HTTP ${res.status}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const ttl = apiCacheTtl(path, data);
|
const ttl = apiCacheTtl(path, data);
|
||||||
if (ttl > 0) {
|
if (ttl > 0 && gen === API_GEN.n) {
|
||||||
// FIFO simple: al llenarse, cae la entrada más antigua.
|
// FIFO simple: al llenarse, cae la entrada más antigua.
|
||||||
if (apiCache.size >= API_CACHE_MAX) apiCache.delete(apiCache.keys().next().value);
|
if (apiCache.size >= API_CACHE_MAX) apiCache.delete(apiCache.keys().next().value);
|
||||||
apiCache.set(key, { at: Date.now(), data, ttl });
|
apiCache.set(key, { at: Date.now(), data, ttl });
|
||||||
@@ -136,7 +141,7 @@
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
apiInflight.set(key, p);
|
apiInflight.set(key, p);
|
||||||
try { return await p; } finally { apiInflight.delete(key); }
|
try { return await p; } finally { if (apiInflight.get(key) === p) apiInflight.delete(key); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Salud del nodo ──────────────────────────────────────────────────
|
// ── Salud del nodo ──────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -30,8 +30,15 @@
|
|||||||
else if(fallo && !/HTTP 404/.test(fallo.message)){ throw new Error(mensajeTxNoLlega(fallo)); }
|
else if(fallo && !/HTTP 404/.test(fallo.message)){ throw new Error(mensajeTxNoLlega(fallo)); }
|
||||||
else { const block=await getStrict(`/api/block/${q}`); setResult({type:"block",data:block}); }
|
else { const block=await getStrict(`/api/block/${q}`); setResult({type:"block",data:block}); }
|
||||||
} else if(/^\d+$/.test(q)&&parseInt(q)<1000000){
|
} else if(/^\d+$/.test(q)&&parseInt(q)<1000000){
|
||||||
const hash=await get(`/api/block-height/${q}`,null);
|
// v1.48.1 (auditoría A5-05): si esa altura no existe (o el nodo no
|
||||||
const block=await get(`/api/block/${hash}`,null);
|
// contesta) no se pide «/api/block/null»: se dice.
|
||||||
|
// Ojo: /block-height devuelve el hash en texto, no en JSON; leerlo
|
||||||
|
// como JSON fallaba siempre y la búsqueda por altura no funcionaba.
|
||||||
|
let hash=null;
|
||||||
|
try{ const r=await fetchWithTimeout(`${base}/api/block-height/${q}`); if(r.ok) hash=(await r.text()).trim(); else if(r.status!==404) throw new Error(`el nodo respondió HTTP ${r.status}`); }
|
||||||
|
catch(e){ throw new Error(`No se pudo consultar a tu nodo (${e.message}).`); }
|
||||||
|
if(typeof hash!=="string"||!/^[0-9a-f]{64}$/i.test(hash.trim())) throw new Error(`No hay ningún bloque a la altura ${q} (la cadena todavía no llega ahí).`);
|
||||||
|
const block=await getStrict(`/api/block/${hash.trim()}`);
|
||||||
setResult({type:"block",data:block});
|
setResult({type:"block",data:block});
|
||||||
} else {
|
} else {
|
||||||
// Las monedas sin gastar se piden en modo estricto: si /utxo falla
|
// Las monedas sin gastar se piden en modo estricto: si /utxo falla
|
||||||
|
|||||||
+10
-354
@@ -380,357 +380,13 @@
|
|||||||
return chains;
|
return chains;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Motor de rastreo forense ─────────────────────────────────────────
|
// ── Motor de rastreo forense (automático): retirado en v1.48.1 ──────
|
||||||
// Hacia adelante, salto a salto, desde {txid,vout}. Sigue TODOS los
|
// Recorría solo hasta 80 transacciones, con ráfagas de cientos de
|
||||||
// outputs de cada salto (no solo "el cambio"): un actor puede repartir
|
// consultas, y ninguna pantalla lo usaba desde que Seguimiento va salto
|
||||||
// los fondos en más de una rama, y cada rama se detiene de forma
|
// a salto con quien lo maneja (auditoría A4-04/A4-05: sus topes no se
|
||||||
// independiente (spec: "cualquiera detiene esa rama, no todo el
|
// cumplían). Seguimiento usa grafoDesdePeritaje (42-peritaje-logica.js).
|
||||||
// rastreo"). Qué output es "cambio" se calcula por señal
|
// Se conservan las piezas que sí se usan o se prueban (perfil de
|
||||||
// estructural+conductual y sirve para el informe (atribución, peeling
|
// dirección, señal conductual del cambio, cadenas de pelado…).
|
||||||
// chain), no para podar ramas.
|
|
||||||
//
|
|
||||||
// A demanda: el estado del rastreo (initForensicTrace) y el avance de
|
|
||||||
// un salto (advanceForensicHop) están separados a propósito, para que
|
|
||||||
// la UI pueda pausar entre saltos y sea el usuario quien decida cuándo
|
|
||||||
// seguir — en vez de que el motor drene el frontier entero sin
|
|
||||||
// vigilancia. buildForensicGraph, más abajo, es el caso trivial que los
|
|
||||||
// encadena en bucle (modo automático de una sola pasada).
|
|
||||||
//
|
|
||||||
// Crea el estado de un rastreo forense nuevo, sin ejecutar ningún salto
|
|
||||||
// todavía.
|
|
||||||
async function initForensicTrace({ get, getStrict, originTxid, originVout, amountStolen }) {
|
|
||||||
// Distinguir "txid inexistente" de "el nodo no respondió": culpar al
|
|
||||||
// txid cuando el fallo es del nodo manda al usuario a buscar un error
|
|
||||||
// que no existe.
|
|
||||||
let originTx;
|
|
||||||
try {
|
|
||||||
originTx = await getStrict(`/api/tx/${originTxid}`);
|
|
||||||
} catch (e) {
|
|
||||||
throw new Error(`No se pudo consultar la transacción de origen: ${e.message}. No es (necesariamente) un problema del txid — la petición al nodo falló.`);
|
|
||||||
}
|
|
||||||
if (!originTx) throw new Error("No se pudo obtener la transacción de origen. Comprueba el txid.");
|
|
||||||
const originOut = originTx.vout?.[originVout];
|
|
||||||
if (!originOut) throw new Error("El vout indicado no existe en la transacción de origen.");
|
|
||||||
const originFingerprint = detectWallets(originTx);
|
|
||||||
|
|
||||||
return {
|
|
||||||
get, getStrict, originTxid, originVout, amountStolen: amountStolen || null,
|
|
||||||
originTx, originOut, originFingerprint,
|
|
||||||
txCache: new Map([[originTxid, originTx]]),
|
|
||||||
nodes: new Map(), // txid -> ForensicNode
|
|
||||||
edges: [], // ForensicEdge[]
|
|
||||||
unspentTerminals: [], // ramas terminales: monedas sin gastar, sin dirección, truncadas o con consulta fallida
|
|
||||||
queryErrors: [], // consultas al nodo que fallaron — NUNCA se leen como "no hay nada"
|
|
||||||
frontier: [{ txid: originTxid, vout: originVout, amount: originOut.value, hop: 0, parentTxid: originTxid }],
|
|
||||||
enqueuedKeys: new Set(),
|
|
||||||
hop: 0, done: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ejecuta UN salto completo del rastreo: procesa TODO el frontier actual
|
|
||||||
// (mismo throttling por lotes de siempre — BATCH/PAUSE — dentro de ese
|
|
||||||
// salto) y deja preparado, sin arrancarlo, el frontier del salto
|
|
||||||
// siguiente. Muta `trace` en el sitio y lo devuelve. trace.done=true
|
|
||||||
// cuando ya no queda nada que explorar (o todo lo que queda se trunca
|
|
||||||
// por maxHops sin necesitar más peticiones).
|
|
||||||
async function advanceForensicHop(trace, opts) {
|
|
||||||
const maxHops = (opts && opts.maxHops) || 8;
|
|
||||||
const onProgress = opts && opts.onProgress;
|
|
||||||
// BATCH/PAUSE: mismo patrón de throttling que scanWallet, lotes con
|
|
||||||
// pausa, no ráfaga. MAX_NODES es una red de seguridad aparte de
|
|
||||||
// maxHops y del control manual del usuario: protege el nodo si un
|
|
||||||
// salto desemboca en una tx con muchísimos outputs (p.ej.
|
|
||||||
// consolidación de un servicio de pagos).
|
|
||||||
const BATCH = 5, PAUSE = 120, MAX_NODES = 80;
|
|
||||||
// Tope de ramificación por transacción: por encima de estas salidas
|
|
||||||
// distintas, la tx es un reparto masivo (dust attack, batch de exchange,
|
|
||||||
// airdrop) y se deja de seguir. Ver el comentario en el punto de uso —
|
|
||||||
// se aplica antes de perfilar direcciones, que es donde está el coste.
|
|
||||||
const MAX_FANOUT = 25;
|
|
||||||
// Cinturón de seguridad independiente del heurístico de perfil: una
|
|
||||||
// dirección con un volumen de transacciones así de alto es, con
|
|
||||||
// altísima probabilidad, infraestructura de un servicio (exchange,
|
|
||||||
// custodio, procesador de pagos) aunque el perfil no llegue a
|
|
||||||
// clasificarla "hot_wallet" (residual momentáneamente alto, etc.). Sin
|
|
||||||
// este tope, seguir esa dirección dispararía en estadoSalida una
|
|
||||||
// paginación de hasta 200 tx (8 páginas × 8s de timeout) buscando una
|
|
||||||
// aguja en un pajar de decenas de miles — coste real para el nodo del
|
|
||||||
// usuario sin ninguna posibilidad realista de encontrar el gasto. No
|
|
||||||
// cuesta peticiones extra: chain_stats.tx_count ya viene en el perfil
|
|
||||||
// que se pide de todos modos para cada dirección de salida nueva.
|
|
||||||
const LARGE_ADDR_TX_COUNT = 5000;
|
|
||||||
const { get, getStrict, originTxid, originFingerprint, nodes, edges, unspentTerminals, txCache, enqueuedKeys, queryErrors } = trace;
|
|
||||||
|
|
||||||
if (trace.frontier.length === 0) { trace.done = true; return trace; }
|
|
||||||
|
|
||||||
const hopFrontier = trace.frontier;
|
|
||||||
trace.frontier = []; // aquí se acumula el frontier del salto siguiente
|
|
||||||
|
|
||||||
for (let i = 0; i < hopFrontier.length; i += BATCH) {
|
|
||||||
const batch = hopFrontier.slice(i, i + BATCH);
|
|
||||||
if (onProgress) onProgress(`Salto ${trace.hop+1}: explorando rama ${Math.min(i+BATCH,hopFrontier.length)}/${hopFrontier.length} (${nodes.size} tx en el rastro)…`);
|
|
||||||
|
|
||||||
await Promise.all(batch.map(async (item) => {
|
|
||||||
const { txid, vout, amount, hop, parentTxid } = item;
|
|
||||||
const parentTx = txCache.get(txid);
|
|
||||||
const out = parentTx?.vout?.[vout];
|
|
||||||
const dirReal = out?.scriptpubkey_address || null;
|
|
||||||
// Sin dirección no es lo mismo que datos: una salida P2PK lleva
|
|
||||||
// dinero y su gasto se busca por el script (scripthash).
|
|
||||||
const addr = dirReal || etiquetaSinDir(out);
|
|
||||||
|
|
||||||
if (!out || esSalidaDeDatos(out)) {
|
|
||||||
unspentTerminals.push({ txid, vout, address:null, amount, note:"Salida de datos (OP_RETURN): no lleva dinero, no hay nada que seguir." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (hop >= maxHops) {
|
|
||||||
unspentTerminals.push({ txid, vout, address:addr, amount, note:"Límite de saltos alcanzado.", truncated:true, tipo:"tope" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// "No se pudo consultar" y "no hay gasto" son cosas distintas y se
|
|
||||||
// registran distinto. Solo la segunda es una conclusión.
|
|
||||||
let spendTx, est;
|
|
||||||
try {
|
|
||||||
est = await estadoSalida(getStrict, dirReal, txid, vout, undefined, out.scriptpubkey, { alturaCreacion: parentTx?.status?.block_height });
|
|
||||||
spendTx = est.tx || null;
|
|
||||||
} catch (e) {
|
|
||||||
queryErrors.push({ txid, vout, address:addr, message:e.message, context:"búsqueda del gasto" });
|
|
||||||
unspentTerminals.push({ txid, vout, address:addr, amount, queryFailed:true, tipo:"fallo",
|
|
||||||
note: (e.codigo === "no_buscable" || e.codigo === "inconcluso")
|
|
||||||
? `No se puede saber si se gastó: ${e.message}. No quiere decir que siga sin gastar.`
|
|
||||||
: `No se pudo comprobar si este output fue gastado: ${e.message}. La consulta al nodo falló — no es una conclusión sobre el estado de los fondos.` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (est.estado === "incompleto") {
|
|
||||||
unspentTerminals.push({ txid, vout, address:addr, amount, queryFailed:true, tipo:"incompleto", paginas:est.paginas, totalPaginas:est.totalPaginas, note:`Búsqueda sin terminar: ${est.texto}. No quiere decir que siga sin gastar.` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (est.estado === "no_localizada") {
|
|
||||||
unspentTerminals.push({ txid, vout, address:addr, amount, queryFailed:true, tipo:"no_localizada", paginas:est.paginas, note:`Se movió: ya no está entre las monedas sin gastar, pero no se ha encontrado en qué transacción (${est.paginas} página(s) revisada(s)).` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!spendTx) {
|
|
||||||
unspentTerminals.push({ txid, vout, address:addr, amount, note:"Sin gastar.", tipo:"sin_gastar" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
edges.push({
|
|
||||||
fromTxid: txid, fromVout: vout, toTxid: spendTx.txid,
|
|
||||||
toVin: (spendTx.vin||[]).findIndex(v=>v.txid===txid && v.vout===vout), amount,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (nodes.has(spendTx.txid)) return; // ya construido por otra rama — la arista basta (CIOH implícito)
|
|
||||||
txCache.set(spendTx.txid, spendTx);
|
|
||||||
|
|
||||||
const analysis = analyzeTx(spendTx);
|
|
||||||
const likelyCJ = analysis.checks.find(c=>c.id==="coinjoin")?.pass === true;
|
|
||||||
const { marcas: entityMarks } = marcasDeTx(spendTx, analysis);
|
|
||||||
const fingerprint = detectWallets(spendTx);
|
|
||||||
const structural = guessChangeOutput(spendTx, likelyCJ);
|
|
||||||
|
|
||||||
const inAddrs = [...new Set((spendTx.vin||[]).map(v=>v.prevout?.scriptpubkey_address).filter(Boolean))];
|
|
||||||
const outAddrs = [...new Set((spendTx.vout||[]).map(v=>v.scriptpubkey_address).filter(Boolean))];
|
|
||||||
|
|
||||||
// Tope de ramificación: una transacción que se abre en abanico
|
|
||||||
// (dust attack, batch de exchange, faucet, airdrop) no aporta nada
|
|
||||||
// forense rama a rama y sí machaca el nodo. El coste NO está solo en
|
|
||||||
// encolar: perfilar cada dirección de salida cuesta 2 peticiones, así
|
|
||||||
// que con cientos de salidas son miles de peticiones antes siquiera
|
|
||||||
// de llegar al frontier. Por eso se corta AQUÍ, antes de perfilar
|
|
||||||
// nada, y no más abajo junto a los demás stopReason. Mismo espíritu
|
|
||||||
// que LARGE_ADDR_TX_COUNT, aplicado a la anchura en vez de al fondo.
|
|
||||||
const fannedOut = outAddrs.length > MAX_FANOUT;
|
|
||||||
|
|
||||||
// Perfil + historial de las direcciones de salida — reutilizamos ese
|
|
||||||
// historial para la señal conductual (spendInfo) sin pedirlo dos veces.
|
|
||||||
const outAddrTxs = {};
|
|
||||||
const addressProfiles = {};
|
|
||||||
const historialCompleto = {}; // dirección → ¿la primera página trae TODO su historial?
|
|
||||||
await Promise.all((fannedOut ? [] : outAddrs).map(async a => {
|
|
||||||
let info = null, txs = [];
|
|
||||||
try {
|
|
||||||
[info, txs] = await Promise.all([
|
|
||||||
getStrict(`/api/address/${a}`),
|
|
||||||
getStrict(`/api/address/${a}/txs`),
|
|
||||||
]);
|
|
||||||
} catch (e) {
|
|
||||||
// Sin perfil no hay señal conductual NI cinturón de volumen
|
|
||||||
// para esta dirección: queda anotado para que el informe no
|
|
||||||
// presente su ausencia como si se hubiera comprobado.
|
|
||||||
queryErrors.push({ txid:spendTx.txid, address:a, message:e.message, context:"perfil de dirección" });
|
|
||||||
}
|
|
||||||
outAddrTxs[a] = txs || [];
|
|
||||||
// Solo se pide la primera página del historial. Si la dirección tiene
|
|
||||||
// más transacciones de las que trae, el gasto puede estar más allá:
|
|
||||||
// no encontrarlo no prueba nada (revisión H-05).
|
|
||||||
if (info) {
|
|
||||||
const total = (info.chain_stats?.tx_count || 0) + (info.mempool_stats?.tx_count || 0);
|
|
||||||
historialCompleto[a] = (txs||[]).length >= total;
|
|
||||||
}
|
|
||||||
if (info) addressProfiles[a] = addressProfile(a, info, txs||[]);
|
|
||||||
}));
|
|
||||||
|
|
||||||
const spendInfo = new Map();
|
|
||||||
(spendTx.vout||[]).forEach((v, i) => {
|
|
||||||
const a = v.scriptpubkey_address;
|
|
||||||
if (!a) return;
|
|
||||||
const txs = outAddrTxs[a] || [];
|
|
||||||
const spender = txs.find(t => (t.vin||[]).some(vin => vin.txid===spendTx.txid && vin.vout===i));
|
|
||||||
if (spender && spender.status?.block_height != null && spendTx.status?.block_height != null) {
|
|
||||||
spendInfo.set(i, { spent:true, blocksLater: spender.status.block_height - spendTx.status.block_height });
|
|
||||||
} else if (spender) {
|
|
||||||
spendInfo.set(i, { spent:true, blocksLater:null });
|
|
||||||
} else {
|
|
||||||
// Sin gastar solo si el historial estaba completo; si falló la
|
|
||||||
// consulta o venía cortado, el estado es desconocido.
|
|
||||||
spendInfo.set(i, { spent:false, blocksLater:null, comprobado: historialCompleto[a] === true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const behavioral = likelyCJ ? null : behavioralChangeGuess(spendTx, spendInfo);
|
|
||||||
const combined = behavioral ? combineChangeSignals(structural, behavioral) : null;
|
|
||||||
|
|
||||||
// Dilución: 3+ direcciones de entrada y el monto rastreado deja de
|
|
||||||
// ser una fracción identificable del total del salto.
|
|
||||||
const totalInHop = (spendTx.vin||[]).reduce((s,v)=>s+(v.prevout?.value||0),0);
|
|
||||||
const tracedShare = totalInHop > 0 ? amount / totalInHop : 1;
|
|
||||||
const diluted = inAddrs.length >= 3 && tracedShare < 0.5;
|
|
||||||
|
|
||||||
// Parada por custodio: entidad conocida (ENTITY_INDEX), perfil de
|
|
||||||
// hot wallet no indexado ("posible custodio no identificado"), o
|
|
||||||
// — cinturón de seguridad — volumen de tx tan alto que seguir esa
|
|
||||||
// dirección sería, con seguridad práctica, hammer al nodo sin
|
|
||||||
// esperanza real de encontrar el gasto (ver LARGE_ADDR_TX_COUNT).
|
|
||||||
// Se evalúa POR DIRECCIÓN: un pago normal junto a un depósito de
|
|
||||||
// exchange en la misma tx no se descarta solo porque su vecino
|
|
||||||
// sea un custodio — cada output es su propia rama.
|
|
||||||
const custodyByAddr = {};
|
|
||||||
for (const a of outAddrs) {
|
|
||||||
const hit = ENTITY_INDEX.get(a);
|
|
||||||
if (hit?.cat === "exchange") { custodyByAddr[a] = { addr:a, name:hit.name, known:true, byVolume:false }; continue; }
|
|
||||||
const prof = addressProfiles[a];
|
|
||||||
if (prof && prof.kind === "hot_wallet") { custodyByAddr[a] = { addr:a, name:null, known:false, byVolume:false }; continue; }
|
|
||||||
if (prof && prof.txCount >= LARGE_ADDR_TX_COUNT) { custodyByAddr[a] = { addr:a, name:null, known:false, byVolume:true, txCount:prof.txCount }; }
|
|
||||||
}
|
|
||||||
const custodyAddrs = outAddrs.filter(a => custodyByAddr[a]);
|
|
||||||
const custodyStop = custodyAddrs.length ? custodyByAddr[custodyAddrs[0]] : null;
|
|
||||||
|
|
||||||
let stopReason = null;
|
|
||||||
if (likelyCJ) stopReason = "mixer";
|
|
||||||
else if (diluted) stopReason = "dilution";
|
|
||||||
else if (fannedOut) stopReason = "fanOut";
|
|
||||||
else if (custodyStop) stopReason = "exchange";
|
|
||||||
else if (nodes.size + 1 >= MAX_NODES) stopReason = "nodeLimit";
|
|
||||||
|
|
||||||
const parentNode = parentTxid === originTxid ? { fingerprint: originFingerprint } : nodes.get(parentTxid);
|
|
||||||
const fingerprintComparison = parentNode ? compareFingerprints(parentNode.fingerprint, fingerprint) : null;
|
|
||||||
|
|
||||||
nodes.set(spendTx.txid, {
|
|
||||||
txid: spendTx.txid, hop: hop+1,
|
|
||||||
blockTime: spendTx.status?.block_time ?? null,
|
|
||||||
blockHeight: spendTx.status?.confirmed ? (spendTx.status.block_height ?? null) : null,
|
|
||||||
confirmed: !!spendTx.status?.confirmed,
|
|
||||||
vinCount: (spendTx.vin||[]).length, voutCount: (spendTx.vout||[]).length,
|
|
||||||
addresses: { in: inAddrs, out: outAddrs },
|
|
||||||
amountTraced: amount,
|
|
||||||
analysis, fingerprint, fingerprintComparison, entityMarks,
|
|
||||||
addressProfiles,
|
|
||||||
changeGuess: { structural, behavioral, combined },
|
|
||||||
changeAddress: structural.index != null ? (spendTx.vout[structural.index]?.scriptpubkey_address ?? null) : null,
|
|
||||||
diluted, tracedShare, custodyStop, custodyAddrs,
|
|
||||||
fanOut: fannedOut ? { outputs: outAddrs.length, limit: MAX_FANOUT } : null,
|
|
||||||
stopReason,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mixer/dilución/tope de nodos afectan a TODOS los outputs por
|
|
||||||
// igual (se originan en el lado de entrada de la tx, o son un
|
|
||||||
// límite global) — ahí sí se corta la transacción entera. Un
|
|
||||||
// custodio, en cambio, es propiedad de UNA dirección concreta:
|
|
||||||
// solo esa rama se corta, las demás siguen su curso normal.
|
|
||||||
const blockAllOutputs = stopReason === "mixer" || stopReason === "dilution" || stopReason === "nodeLimit" || stopReason === "fanOut";
|
|
||||||
if (!blockAllOutputs) {
|
|
||||||
spendTx.vout.forEach((v, i) => {
|
|
||||||
if (!v.value || v.value <= 0) return;
|
|
||||||
if (v.scriptpubkey_address && custodyByAddr[v.scriptpubkey_address]) return;
|
|
||||||
const key = `${spendTx.txid}:${i}`;
|
|
||||||
if (enqueuedKeys.has(key)) return;
|
|
||||||
enqueuedKeys.add(key);
|
|
||||||
trace.frontier.push({ txid: spendTx.txid, vout:i, amount:v.value, hop:hop+1, parentTxid: txid });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (i + BATCH < hopFrontier.length) await new Promise(r => setTimeout(r, PAUSE));
|
|
||||||
}
|
|
||||||
|
|
||||||
trace.hop += 1;
|
|
||||||
if (trace.frontier.length === 0) trace.done = true;
|
|
||||||
return trace;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensambla el ForensicGraph (forma que espera buildForensicReport) a
|
|
||||||
// partir de un `trace`, completo o parcial — se puede llamar en
|
|
||||||
// cualquier momento del rastreo a demanda, no solo al terminar.
|
|
||||||
function finalizeForensicGraph(trace) {
|
|
||||||
const { originTxid, originVout, originTx, originOut, originFingerprint, amountStolen, nodes, edges, unspentTerminals, txCache, queryErrors } = trace;
|
|
||||||
|
|
||||||
// CIOH: semilla = origen + toda dirección de entrada de cualquier
|
|
||||||
// salto (por construcción, llegó ahí siguiendo los fondos) + direcciones
|
|
||||||
// de salida que NO son la puerta de un custodio identificado (esas
|
|
||||||
// pertenecen al servicio, no al mismo actor rastreado). Exclusión por
|
|
||||||
// dirección, no por nodo entero — un pago normal junto a un depósito
|
|
||||||
// de exchange en la misma tx sí cuenta como del actor.
|
|
||||||
// Los CoinJoin quedan FUERA por completo, entradas y salidas. CIOH
|
|
||||||
// asume que quien gasta varios inputs juntos los controla, y un CoinJoin
|
|
||||||
// existe precisamente para romper esa suposición: es la excepción
|
|
||||||
// clásica a la heurística. Sus entradas y salidas son de participantes
|
|
||||||
// distintos, así que meterlas aquí produce un falso positivo garantizado
|
|
||||||
// y contradice la propia conclusión del informe ("no se puede atribuir
|
|
||||||
// con honestidad más allá de este punto").
|
|
||||||
const actorAddrSet = new Set([originOut.scriptpubkey_address].filter(Boolean));
|
|
||||||
const mixerTxids = new Set();
|
|
||||||
for (const n of nodes.values()) {
|
|
||||||
if (n.stopReason === "mixer") { mixerTxids.add(n.txid); continue; }
|
|
||||||
for (const a of n.addresses.in) actorAddrSet.add(a);
|
|
||||||
for (const a of n.addresses.out) { if (!n.custodyAddrs.includes(a)) actorAddrSet.add(a); }
|
|
||||||
}
|
|
||||||
// El union-find tampoco debe ver las transacciones de mezcla: agruparía
|
|
||||||
// por inputs comunes a gente que no tiene nada que ver entre sí.
|
|
||||||
const txsForCluster = [...txCache.values()].filter(t => !mixerTxids.has(t.txid));
|
|
||||||
const { clusters, linkReasons } = unionFindCluster(txsForCluster, actorAddrSet);
|
|
||||||
|
|
||||||
// marcasDeTx necesita vin/vout crudos (coinbase, OFAC, minería,
|
|
||||||
// exchange, CoinJoin) — se calcula aquí, sobre originTx de verdad, y se
|
|
||||||
// guarda ya resuelto en graph.origin porque ese objeto solo lleva los
|
|
||||||
// campos resumidos que necesita el informe, no la tx cruda.
|
|
||||||
const originAnalysis = analyzeTx(originTx);
|
|
||||||
const originEntityMarks = marcasDeTx(originTx, originAnalysis).marcas;
|
|
||||||
|
|
||||||
return {
|
|
||||||
origin: {
|
|
||||||
txid: originTxid, vout: originVout, address: originOut.scriptpubkey_address, amount: originOut.value,
|
|
||||||
blockTime: originTx.status?.block_time ?? null, blockHeight: originTx.status?.confirmed ? (originTx.status.block_height ?? null) : null,
|
|
||||||
fingerprint: originFingerprint, analysis: originAnalysis, entityMarks: originEntityMarks,
|
|
||||||
},
|
|
||||||
amountStolen: amountStolen || null,
|
|
||||||
nodes, edges, unspentTerminals, clusters, linkReasons,
|
|
||||||
queryErrors: queryErrors || [],
|
|
||||||
peelingChains: detectPeelingChains(nodes, edges),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Punto de entrada equivalente al motor original de una sola pasada:
|
|
||||||
// crea el estado y lo agota salto a salto sin pausas (modo automático).
|
|
||||||
// Se mantiene por compatibilidad — la UI a demanda usa
|
|
||||||
// initForensicTrace + advanceForensicHop directamente, con el usuario
|
|
||||||
// decidiendo cuándo llamar a cada salto en vez de este bucle.
|
|
||||||
async function buildForensicGraph({ get, getStrict, originTxid, originVout, amountStolen, maxHops, onProgress }) {
|
|
||||||
const trace = await initForensicTrace({ get, getStrict, originTxid, originVout, amountStolen });
|
|
||||||
while (!trace.done) {
|
|
||||||
await advanceForensicHop(trace, { maxHops, onProgress });
|
|
||||||
}
|
|
||||||
return finalizeForensicGraph(trace);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Genera el informe de peritaje a partir del grafo ya construido. Marco
|
// Genera el informe de peritaje a partir del grafo ya construido. Marco
|
||||||
// HECHO/INFERENCIA/DECLARACION (ver TRASPASO.md): HECHO son datos on-chain
|
// HECHO/INFERENCIA/DECLARACION (ver TRASPASO.md): HECHO son datos on-chain
|
||||||
@@ -779,7 +435,7 @@
|
|||||||
// ── 4. Direcciones atribuidas al actor ──────────────────────────────
|
// ── 4. Direcciones atribuidas al actor ──────────────────────────────
|
||||||
const clusterOf = new Map();
|
const clusterOf = new Map();
|
||||||
clusters.forEach((c,i) => c.forEach(a => clusterOf.set(a, i)));
|
clusters.forEach((c,i) => c.forEach(a => clusterOf.set(a, i)));
|
||||||
// Dirección de cambio por salto (ya resuelta a texto en buildForensicGraph,
|
// Dirección de cambio por salto (ya resuelta a texto al construir el grafo,
|
||||||
// no se recalcula el índice aquí — evita desalinearse si addresses.out
|
// no se recalcula el índice aquí — evita desalinearse si addresses.out
|
||||||
// llegara a deduplicar en un orden distinto al de vout).
|
// llegara a deduplicar en un orden distinto al de vout).
|
||||||
const changeAddrByHop = new Map(); // addr -> {txid, certainty, agreement}
|
const changeAddrByHop = new Map(); // addr -> {txid, certainty, agreement}
|
||||||
@@ -1090,7 +746,7 @@
|
|||||||
`- Sin explorar todavía: ${btcTxt(d.sinExplorar)}`,
|
`- Sin explorar todavía: ${btcTxt(d.sinExplorar)}`,
|
||||||
`- Comisiones pagadas a los mineros: ${btcTxt(d.comisiones || 0)}`, "");
|
`- Comisiones pagadas a los mineros: ${btcTxt(d.comisiones || 0)}`, "");
|
||||||
}
|
}
|
||||||
if (decl) L.push("## Declaración del afectado [DECLARACIÓN]", "", "_Lo que cuenta el afectado, sin comprobar. No se mezcla con los hechos._", "", decl.text, "");
|
if (decl) L.push("## Declaración del afectado [DECLARACIÓN]", "", "_Lo que cuenta el afectado, sin comprobar. No se mezcla con los hechos._", "", citaMD(decl.text), "");
|
||||||
L.push("## Direcciones atribuidas a quien movió el dinero (el «actor»)", "");
|
L.push("## Direcciones atribuidas a quien movió el dinero (el «actor»)", "");
|
||||||
if (!attributed.length) L.push("Ninguna dirección, aparte de la salida de origen, tiene indicios suficientes para atribuirla al actor.");
|
if (!attributed.length) L.push("Ninguna dirección, aparte de la salida de origen, tiene indicios suficientes para atribuirla al actor.");
|
||||||
attributed.forEach(a => L.push(`- [INFERENCIA] ${a.address} — ${a.fundamentos.map(f => `${f.basis} (${f.certainty})${f.refTxid ? ` [tx ${f.refTxid}]` : ""}`).join("; ")}`));
|
attributed.forEach(a => L.push(`- [INFERENCIA] ${a.address} — ${a.fundamentos.map(f => `${f.basis} (${f.certainty})${f.refTxid ? ` [tx ${f.refTxid}]` : ""}`).join("; ")}`));
|
||||||
@@ -1115,7 +771,7 @@
|
|||||||
}
|
}
|
||||||
L.push("", "## Mesa de trabajo", "", "_Marcas y notas de quien hizo el seguimiento._", "");
|
L.push("", "## Mesa de trabajo", "", "_Marcas y notas de quien hizo el seguimiento._", "");
|
||||||
if (!(rep.mesa || []).length) L.push("Sin transacciones marcadas.");
|
if (!(rep.mesa || []).length) L.push("Sin transacciones marcadas.");
|
||||||
(rep.mesa || []).forEach(m => L.push(`- ${m.txid}${m.nota ? ` — ${m.nota}` : ""}`));
|
(rep.mesa || []).forEach(m => { L.push(`- ${m.txid}`); if (m.nota) L.push("", citaMD(m.nota), ""); });
|
||||||
if ((rep.vigiladas || []).length) {
|
if ((rep.vigiladas || []).length) {
|
||||||
const est = e => e === "gastada" ? "gastada" : e === "no_localizada" ? "gastada, sin localizar" : e === "error" ? "no se pudo comprobar" : "sin gastar";
|
const est = e => e === "gastada" ? "gastada" : e === "no_localizada" ? "gastada, sin localizar" : e === "error" ? "no se pudo comprobar" : "sin gastar";
|
||||||
L.push("", "**Salidas guardadas para revisar:**");
|
L.push("", "**Salidas guardadas para revisar:**");
|
||||||
|
|||||||
@@ -229,7 +229,7 @@
|
|||||||
if (p.entrada_seguida != null) L.push(`- Se llegó por la entrada ${p.entrada_seguida} de ${p.salto === 1 ? "el origen" : `el salto ${p.salto - 1}`}`);
|
if (p.entrada_seguida != null) L.push(`- Se llegó por la entrada ${p.entrada_seguida} de ${p.salto === 1 ? "el origen" : `el salto ${p.salto - 1}`}`);
|
||||||
p.coincidencias.forEach(c => L.push(`- Coincidencia (${c.donde}, ${c.direccion}): ${c.texto} · ${c.certeza}`));
|
p.coincidencias.forEach(c => L.push(`- Coincidencia (${c.donde}, ${c.direccion}): ${c.texto} · ${c.certeza}`));
|
||||||
if (p.fin) L.push(`- ${p.fin}${p.fin_certeza ? ` · ${p.fin_certeza}` : ""}`);
|
if (p.fin) L.push(`- ${p.fin}${p.fin_certeza ? ` · ${p.fin_certeza}` : ""}`);
|
||||||
if (p.nota) L.push(`- Nota: ${p.nota}`);
|
if (p.nota) L.push("- Nota (escrita por quien hizo el rastro):", "", citaMD(p.nota), "");
|
||||||
L.push("");
|
L.push("");
|
||||||
});
|
});
|
||||||
if (pendientes.length) {
|
if (pendientes.length) {
|
||||||
|
|||||||
@@ -60,7 +60,21 @@
|
|||||||
const tin = (tx?.vin || []).reduce((s, v) => s + (v.prevout?.value || 0), 0);
|
const tin = (tx?.vin || []).reduce((s, v) => s + (v.prevout?.value || 0), 0);
|
||||||
const val = tx?.vout?.[i]?.value || 0;
|
const val = tx?.vout?.[i]?.value || 0;
|
||||||
if (!tin || !seguido) return { sats: 0, pct: 0 };
|
if (!tin || !seguido) return { sats: 0, pct: 0 };
|
||||||
const sats = Math.round(seguido * val / tin);
|
// v1.48.1 (auditoría A4-03): reparto entero que conserva la suma. Antes
|
||||||
|
// cada salida se redondeaba por su cuenta y 1.001 sat seguidos podían
|
||||||
|
// repartirse en 1.002. Ahora se reparte por el método del mayor resto
|
||||||
|
// entre todas las salidas y la comisión, con enteros grandes (BigInt),
|
||||||
|
// y en caso de empate gana el índice menor: siempre el mismo resultado.
|
||||||
|
const partes = (tx.vout || []).map(o => BigInt(o.value || 0));
|
||||||
|
const sumOut = partes.reduce((a, b) => a + b, 0n);
|
||||||
|
const T = BigInt(tin), S = BigInt(seguido);
|
||||||
|
partes.push(T > sumOut ? T - sumOut : 0n); // la comisión, al final
|
||||||
|
const base = partes.map(v => (S * v) / T);
|
||||||
|
const resto = partes.map((v, k) => ({ k, r: (S * v) % T }));
|
||||||
|
let falta = S - base.reduce((a, b) => a + b, 0n);
|
||||||
|
resto.sort((x, y) => (y.r > x.r ? 1 : y.r < x.r ? -1 : x.k - y.k));
|
||||||
|
for (const { k } of resto) { if (falta <= 0n) break; base[k] += 1n; falta -= 1n; }
|
||||||
|
const sats = Number(base[i] || 0n);
|
||||||
return { sats, pct: Math.round(sats / seguido * 1000) / 10 };
|
return { sats, pct: Math.round(sats / seguido * 1000) / 10 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
// Inventario, exportar, importar, «no guardar nada» y «borrar todo».
|
// Inventario, exportar, importar, «no guardar nada» y «borrar todo».
|
||||||
// Sin diálogos nativos: cada paso delicado se confirma en línea.
|
// Sin diálogos nativos: cada paso delicado se confirma en línea.
|
||||||
function vaciarEstadoEnMemoria() {
|
function vaciarEstadoEnMemoria() {
|
||||||
try { apiCache.clear(); apiInflight.clear(); } catch {}
|
try { API_GEN.n++; apiCache.clear(); apiInflight.clear(); } catch {}
|
||||||
NODE_HEALTH.base = null; NODE_HEALTH.oks = new Set(); NODE_HEALTH.fallos = new Map(); NODE_HEALTH.sustituidos = 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 {} });
|
NODE_HEALTH.listeners.forEach(l => { try { l(); } catch {} });
|
||||||
}
|
}
|
||||||
|
|||||||
+38
-6
@@ -7,6 +7,27 @@
|
|||||||
// importes y scripts de sus entradas, así que no hace falta consultar el
|
// importes y scripts de sus entradas, así que no hace falta consultar el
|
||||||
// nodo. Eso significa que puedes auditar una transacción antes de firmarla
|
// nodo. Eso significa que puedes auditar una transacción antes de firmarla
|
||||||
// aunque el nodo esté sincronizando — y que el nodo no se entera.
|
// aunque el nodo esté sincronizando — y que el nodo no se entera.
|
||||||
|
// ── Utilidades de formato (v1.48.1) ──
|
||||||
|
const MAX_SATS = 2100000000000000n;
|
||||||
|
// CompactSize de Bitcoin: 1, 3, 5 o 9 bytes. Devuelve { n, bytes } o null.
|
||||||
|
function leerCompactSize(b, pos) {
|
||||||
|
if (pos >= b.length) return null;
|
||||||
|
const x = b[pos];
|
||||||
|
if (x < 0xfd) return { n: x, bytes: 1 };
|
||||||
|
const largo = x === 0xfd ? 2 : x === 0xfe ? 4 : 8;
|
||||||
|
if (pos + 1 + largo > b.length) return null;
|
||||||
|
let v = 0n; for (let i = largo - 1; i >= 0; i--) v = (v << 8n) | BigInt(b[pos + 1 + i]);
|
||||||
|
if (v > BigInt(Number.MAX_SAFE_INTEGER)) return null;
|
||||||
|
return { n: Number(v), bytes: 1 + largo };
|
||||||
|
}
|
||||||
|
// final_scriptwitness: nº de elementos (≥1) y cada elemento con su
|
||||||
|
// longitud; tiene que ocupar exactamente el campo.
|
||||||
|
function testigoFinalValido(v) {
|
||||||
|
let pos = 0; const cab = leerCompactSize(v, pos); if (!cab || cab.n < 1) return false; pos += cab.bytes;
|
||||||
|
for (let i = 0; i < cab.n; i++) { const el = leerCompactSize(v, pos); if (!el) return false; pos += el.bytes + el.n; if (pos > v.length) return false; }
|
||||||
|
return pos === v.length;
|
||||||
|
}
|
||||||
|
|
||||||
function parsePsbt(bytes) {
|
function parsePsbt(bytes) {
|
||||||
let p = 0;
|
let p = 0;
|
||||||
const need = (n) => { if (p + n > bytes.length) throw new Error("PSBT truncada: el archivo se acaba antes de tiempo."); };
|
const need = (n) => { if (p + n > bytes.length) throw new Error("PSBT truncada: el archivo se acaba antes de tiempo."); };
|
||||||
@@ -56,7 +77,9 @@
|
|||||||
const tx = utxRec.value; let q = 0;
|
const tx = utxRec.value; let q = 0;
|
||||||
const tneed=(n)=>{ if(q+n>tx.length) throw new Error("La transacción que hay dentro está truncada."); };
|
const tneed=(n)=>{ if(q+n>tx.length) throw new Error("La transacción que hay dentro está truncada."); };
|
||||||
const tu32=()=>{ tneed(4); const v=tx[q]|(tx[q+1]<<8)|(tx[q+2]<<16)|(tx[q+3]<<24); q+=4; return v>>>0; };
|
const tu32=()=>{ tneed(4); const v=tx[q]|(tx[q+1]<<8)|(tx[q+2]<<16)|(tx[q+3]<<24); q+=4; return v>>>0; };
|
||||||
const tu64=()=>{ tneed(8); let v=0n; for(let i=7;i>=0;i--) v=(v<<8n)|BigInt(tx[q+i]); q+=8; return Number(v); };
|
// v1.48.1 (auditoría A2-05): un importe de más de 21 millones de BTC no
|
||||||
|
// existe; antes se convertía a Number y perdía precisión en silencio.
|
||||||
|
const tu64=()=>{ tneed(8); let v=0n; for(let i=7;i>=0;i--) v=(v<<8n)|BigInt(tx[q+i]); q+=8; if (v > MAX_SATS) throw new Error("PSBT inválida: un importe de la transacción supera los 21 millones de BTC."); return Number(v); };
|
||||||
const tvar=()=>{ tneed(1); const v=tx[q++]; if(v<0xfd) return v; if(v===0xfd){const r=tx[q]|(tx[q+1]<<8);q+=2;return r;} if(v===0xfe) return tu32(); return tu64(); };
|
const tvar=()=>{ tneed(1); const v=tx[q++]; if(v<0xfd) return v; if(v===0xfd){const r=tx[q]|(tx[q+1]<<8);q+=2;return r;} if(v===0xfe) return tu32(); return tu64(); };
|
||||||
const ttake=(n)=>{ tneed(n); return tx.slice(q, q+=n); };
|
const ttake=(n)=>{ tneed(n); return tx.slice(q, q+=n); };
|
||||||
const hx=(a)=>Array.from(a).map(b=>b.toString(16).padStart(2,"0")).join("");
|
const hx=(a)=>Array.from(a).map(b=>b.toString(16).padStart(2,"0")).join("");
|
||||||
@@ -99,10 +122,17 @@
|
|||||||
const d = `la entrada ${i}`;
|
const d = `la entrada ${i}`;
|
||||||
for (const e of m) {
|
for (const e of m) {
|
||||||
if (e.type === 0x01) { // witness_utxo: importe (8) + longitud + script
|
if (e.type === 0x01) { // witness_utxo: importe (8) + longitud + script
|
||||||
if (e.key.length || e.value.length < 9 || e.value[8] >= 0xfd || e.value.length !== 9 + e.value[8]) mal(d, "el importe de la moneda (witness_utxo)");
|
// v1.48.1 (A2-06): la longitud del script es un CompactSize, que
|
||||||
|
// puede ocupar 1, 3, 5 o 9 bytes; antes solo se aceptaba 1.
|
||||||
|
const cs = e.value.length >= 9 ? leerCompactSize(e.value, 8) : null;
|
||||||
|
if (e.key.length || !cs || e.value.length !== 8 + cs.bytes + cs.n) mal(d, "el importe de la moneda (witness_utxo)");
|
||||||
if (lee8(e.value) > 21e14) mal(d, "el importe de la moneda (más de 21 millones de BTC)");
|
if (lee8(e.value) > 21e14) mal(d, "el importe de la moneda (más de 21 millones de BTC)");
|
||||||
}
|
}
|
||||||
if (e.type === 0x02 && (!esPub(e.key) || e.value.length < 9 || e.value.length > 73)) mal(d, "una firma parcial");
|
if (e.type === 0x02 && (!esPub(e.key) || e.value.length < 9 || e.value.length > 73)) mal(d, "una firma parcial");
|
||||||
|
// v1.48.1 (A2-03): los campos de firma final tienen su estructura;
|
||||||
|
// un testigo vacío ya no cuenta como «firma final puesta».
|
||||||
|
if (e.type === 0x08 && (e.key.length || !testigoFinalValido(e.value))) mal(d, "la firma final (final_scriptwitness)");
|
||||||
|
if (e.type === 0x07 && e.key.length) mal(d, "la firma final (final_scriptSig)");
|
||||||
if (e.type === 0x06 && (!esPub(e.key) || e.value.length < 4 || e.value.length % 4)) mal(d, "una ruta de derivación");
|
if (e.type === 0x06 && (!esPub(e.key) || e.value.length < 4 || e.value.length % 4)) mal(d, "una ruta de derivación");
|
||||||
if (e.type === 0x13 && (e.key.length || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "la firma Taproot");
|
if (e.type === 0x13 && (e.key.length || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "la firma Taproot");
|
||||||
if (e.type === 0x14 && (e.key.length !== 64 || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "una firma de script Taproot");
|
if (e.type === 0x14 && (e.key.length !== 64 || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "una firma de script Taproot");
|
||||||
@@ -145,7 +175,7 @@
|
|||||||
let q = 0;
|
let q = 0;
|
||||||
const need = n => { if (q + n > b.length) throw new Error("truncada"); };
|
const need = n => { if (q + n > b.length) throw new Error("truncada"); };
|
||||||
const u32 = () => { need(4); const v = (b[q]|(b[q+1]<<8)|(b[q+2]<<16)|(b[q+3]<<24))>>>0; q += 4; return v; };
|
const u32 = () => { need(4); const v = (b[q]|(b[q+1]<<8)|(b[q+2]<<16)|(b[q+3]<<24))>>>0; q += 4; return v; };
|
||||||
const u64 = () => { need(8); let v = 0n; for (let i = 7; i >= 0; i--) v = (v<<8n)|BigInt(b[q+i]); q += 8; return Number(v); };
|
const u64 = () => { need(8); let v = 0n; for (let i = 7; i >= 0; i--) v = (v<<8n)|BigInt(b[q+i]); q += 8; if (v > MAX_SATS) throw new Error("importe imposible"); return Number(v); };
|
||||||
const vi = () => { need(1); const v = b[q++]; if (v < 0xfd) return v; if (v === 0xfd) { need(2); const r = b[q]|(b[q+1]<<8); q += 2; return r; } if (v === 0xfe) return u32(); return u64(); };
|
const vi = () => { need(1); const v = b[q++]; if (v < 0xfd) return v; if (v === 0xfd) { need(2); const r = b[q]|(b[q+1]<<8); q += 2; return r; } if (v === 0xfe) return u32(); return u64(); };
|
||||||
const take = n => { need(n); return b.slice(q, q += n); };
|
const take = n => { need(n); return b.slice(q, q += n); };
|
||||||
const partes = [];
|
const partes = [];
|
||||||
@@ -235,8 +265,8 @@
|
|||||||
const tiposIn = new Set(psbt.inputs.map((m, i) => {
|
const tiposIn = new Set(psbt.inputs.map((m, i) => {
|
||||||
const w = m.find(e=>e.type===0x01);
|
const w = m.find(e=>e.type===0x01);
|
||||||
if (!w) return previas[i] ? psbtScriptType(previas[i].script) : null;
|
if (!w) return previas[i] ? psbtScriptType(previas[i].script) : null;
|
||||||
const l = w.value[8];
|
const cs = leerCompactSize(w.value, 8);
|
||||||
return psbtScriptType(w.value.slice(9, 9+l));
|
return psbtScriptType(w.value.slice(8 + cs.bytes, 8 + cs.bytes + cs.n));
|
||||||
}).filter(Boolean));
|
}).filter(Boolean));
|
||||||
const tiposOut = psbt.vout.map(o => psbtScriptType(o.script));
|
const tiposOut = psbt.vout.map(o => psbtScriptType(o.script));
|
||||||
|
|
||||||
@@ -360,7 +390,9 @@
|
|||||||
const p = parsePsbt(bytes);
|
const p = parsePsbt(bytes);
|
||||||
forma = "psbt"; ({ vin, vout, version, locktime } = p);
|
forma = "psbt"; ({ vin, vout, version, locktime } = p);
|
||||||
firmas = p.inputs.map(m => {
|
firmas = p.inputs.map(m => {
|
||||||
if (m.some(e => e.type === 0x07 || e.type === 0x08)) return { estado: "final" };
|
// Final de verdad: un testigo con al menos un elemento, o un
|
||||||
|
// scriptSig no vacío (A2-03). Un campo vacío no es una firma.
|
||||||
|
if (m.some(e => (e.type === 0x08 && testigoFinalValido(e.value)) || (e.type === 0x07 && e.value.length > 0))) return { estado: "final" };
|
||||||
const n = m.filter(e => e.type === 0x02 || e.type === 0x13 || e.type === 0x14).length;
|
const n = m.filter(e => e.type === 0x02 || e.type === 0x13 || e.type === 0x14).length;
|
||||||
return n ? { estado: "firmada", n } : { estado: "sin" };
|
return n ? { estado: "firmada", n } : { estado: "sin" };
|
||||||
});
|
});
|
||||||
|
|||||||
Vendored
+413
@@ -0,0 +1,413 @@
|
|||||||
|
{
|
||||||
|
"_nota": "Transacciones reales y públicas del contraste con am-i-exposed y Blockchair (25-oct-2026). Datos de mempool.space, recortados a los campos que usa el analizador (sin testigos ni scriptSig). Ver COMPARATIVA-AIE.md (privado) y el roadmap de la auditoría en frío.",
|
||||||
|
"txs": {
|
||||||
|
"whirlpool": {
|
||||||
|
"txid": "323df21f0b0756f98336437aa3d2fb87e02b59f1946b714a7b09df04d429dec2",
|
||||||
|
"version": 1,
|
||||||
|
"locktime": 0,
|
||||||
|
"size": 911,
|
||||||
|
"weight": 2021,
|
||||||
|
"fee": 30000,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 574682,
|
||||||
|
"block_time": 1557046992
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "333f45431e47b9543772013ac83a9b33cc58dc3245ccfd48b972107bb8405c13",
|
||||||
|
"vout": 8,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5010000,
|
||||||
|
"scriptpubkey": "001443985bccbe28f2678ee90c7169a5b620d167d6a5",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qgwv9hn979rex0rhfp3cknfdkyrgk04493gclvv"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"txid": "5fab266662be1b2705aa5790b1924978c14e7c1525d6966f5aaa129bc8f62695",
|
||||||
|
"vout": 1,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "00145d9105feb5163eb6374a87ad85997204aeb78b7c",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qtkgstl44zcltvd62s7kctxtjqjht0zmufhqr9f"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"txid": "8a9d461ef53ac3d6c13b5d80720996a0a93b1a7adbc6c68ba8c29733aa5d8c16",
|
||||||
|
"vout": 150,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5010000,
|
||||||
|
"scriptpubkey": "0014a28e1237a5792b22cf801e37aa0fe611566fc973",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1q528pyda90y4j9nuqrcm65rlxz9txljtn208dqm"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"txid": "b76e75372049605789cae79d60635be1fa483d1d2c877a05ec93fb9b199384a4",
|
||||||
|
"vout": 2,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "00149f39ae1db51efd6eb3639e4338ebeb5d10097169",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qnuu6u8d4rm7kavmrnepn36ltt5gqjutf34rtfv"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"txid": "c209f94473c3cf044bd2d5245ac90a87df96cfed38436466dee25447bff4ab72",
|
||||||
|
"vout": 3,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5010000,
|
||||||
|
"scriptpubkey": "001439c8c5c60037afcc41d996e7df0581c551df49fc",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1q88yvt3sqx7hucswejmna7pvpc4ga7j0ukfppwq"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "001406f788c2baca46d03e48fdd27f9e48799d1f64c8",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qqmmc3s46efrdq0jglhf8l8jg0xw37exgne6q3k"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "00141caf1f8283db1d5e6f90fa020c4f44bfcb81d995",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qrjh3lq5rmvw4umuslgpqcn6yhl9crkv45z03gg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "0014239c27def665e5136b29d14cf1e5c2d325d1f0c0",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qywwz0hhkvhj3x6ef69x0rewz6vjaruxqxva0fz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "00144e1fa58e6c601117d4ccb2450699a3c1222d6535",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qfc06trnvvqg304xvkfzsdxdrcy3z6ef4lflsxt"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 5000000,
|
||||||
|
"scriptpubkey": "0014be588d8043f9a40edfbbed135691a3cee3c4d59d",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qhevgmqzrlxjqahama5f4dydrem3uf4vaj43kg2"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"joinmarket": {
|
||||||
|
"txid": "4f112abd2eefe3484a7bbf7c1731f784cba19de677468835145e9c448fb18b7d",
|
||||||
|
"version": 2,
|
||||||
|
"locktime": 878484,
|
||||||
|
"size": 433,
|
||||||
|
"weight": 1081,
|
||||||
|
"fee": 1290,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 878487,
|
||||||
|
"block_time": 1736432008
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "b38b9fbe1976e3aa5e878e32597d847cf945df84119036e18e3b73a914922656",
|
||||||
|
"vout": 0,
|
||||||
|
"sequence": 4294967294,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 148798,
|
||||||
|
"scriptpubkey": "0014a4cfdb3413cdc02b847fe9a9517dc3c193baa3c2",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1q5n8akdqnehqzhprlax54zlwrcxfm4g7znc4m9c"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"txid": "be47e5560c0f369f4abc373f19c34bff9bc757acbee68057c5147b9ebbf88048",
|
||||||
|
"vout": 4,
|
||||||
|
"sequence": 4294967294,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 1448113,
|
||||||
|
"scriptpubkey": "0014eff2d096e1b800809f84f7e7e170502213efdb2b",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qaledp9hphqqgp8uy7ln7zuzsygf7lketjvxgzd"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 46981,
|
||||||
|
"scriptpubkey": "0014784e7b3c069bb4f20d190a4991aaf382827463d1",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1q0p88k0qxnw60yrgepfyer2hns2p8gc73j9yhq9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 100420,
|
||||||
|
"scriptpubkey": "0014808cbff1a1a3b4ec88bfb0276f0fd6f76914be05",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qszxtludp5w6wez9lkqnk7r7k7a53f0s9v30jxd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 1347800,
|
||||||
|
"scriptpubkey": "0014a4a8fa2008d2ed5a0da3d182d2a81b976e9cf9b2",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1q5j505gqg6tk45rdr6xpd92qmjahfe7djml36ey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 100420,
|
||||||
|
"scriptpubkey": "001416c03664cb044ea82fa93d0320fb916a7fdc48f4",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qzmqrvextq382staf85pjp7u3dflacj85r9k9jf"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"taproot_opreturn": {
|
||||||
|
"txid": "0bf67b1f05326afbd613e11631a2b86466ac7e255499f6286e31b9d7d889cee7",
|
||||||
|
"version": 1,
|
||||||
|
"locktime": 0,
|
||||||
|
"size": 401,
|
||||||
|
"weight": 800,
|
||||||
|
"fee": 4020,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 709635,
|
||||||
|
"block_time": 1636868413
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "436be185c1021ff7ded3d44ca18b144ec97b1ffea602ecf54a985ed1177beb67",
|
||||||
|
"vout": 0,
|
||||||
|
"sequence": 4294967294,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 6490,
|
||||||
|
"scriptpubkey": "51200bbccdfb4b7a53aaccec0777d39d596f71ca936dd433bd15a69dec6ed60469b1",
|
||||||
|
"scriptpubkey_type": "v1_p2tr",
|
||||||
|
"scriptpubkey_address": "bc1ppw7vm76t0ff64n8vqama882edacu4ymd6sem69dxnhkxa4sydxcstcuh40"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 1000,
|
||||||
|
"scriptpubkey": "6a27e2889e2f32316d696c6c696f6e2e205468616e6b73205361746f7368692120e28094426974476f",
|
||||||
|
"scriptpubkey_type": "op_return"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 1470,
|
||||||
|
"scriptpubkey": "a9148432893b31905290618a5cce909b32978ab7f12a87",
|
||||||
|
"scriptpubkey_type": "p2sh",
|
||||||
|
"scriptpubkey_address": "3Dk1fAx11VSiTFyiWkZK8JUoLsuQ31RUNV"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"simple": {
|
||||||
|
"txid": "0b6461de422c46a221db99608fcbe0326e4f2325ebf2a47c9faf660ed61ee6a4",
|
||||||
|
"version": 1,
|
||||||
|
"locktime": 399983,
|
||||||
|
"size": 226,
|
||||||
|
"weight": 904,
|
||||||
|
"fee": 10000,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 399996,
|
||||||
|
"block_time": 1456416472
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "09dc22bb36e520e4e1120a1d5659dbb3d07bdc29ee42850b539eddecd4e036e6",
|
||||||
|
"vout": 1,
|
||||||
|
"sequence": 4294967294,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 83013905944,
|
||||||
|
"scriptpubkey": "76a914c6df807683c6a26f25eebf2add7017098a55cc8a88ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "1K8YYAJJN3E3KD9FFPUXGAxQEVbt2hVj1M"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 39852779,
|
||||||
|
"scriptpubkey": "76a914cb4f45b4ecfe54b25106a919237cf34ce193c1b988ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "1KY18ssAXBZ5iX8zVQiLF7UKpBUx6Phj3H"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 82974043165,
|
||||||
|
"scriptpubkey": "76a91455ae51684c43435da751ac8d2173b2652eb6410588ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "18p3G8gQ3oKy4U9EqnWs7UZswdqAMhE3r8"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"dust": {
|
||||||
|
"txid": "655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5",
|
||||||
|
"version": 2,
|
||||||
|
"locktime": 545753,
|
||||||
|
"size": 225,
|
||||||
|
"weight": 900,
|
||||||
|
"fee": 226,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 545760,
|
||||||
|
"block_time": 1539550430
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "67fde18fe140073483325ff02b7885bb6af95b2ac18d79fcd34455af5edd7609",
|
||||||
|
"vout": 1,
|
||||||
|
"sequence": 4294967293,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 34313,
|
||||||
|
"scriptpubkey": "76a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 555,
|
||||||
|
"scriptpubkey": "76a914628d52443573305b34167c0f2b6cbf0b8dde76fd88ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "19z6WynrjHeD5MMv6919BuQRwybuen1sRv"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 33532,
|
||||||
|
"scriptpubkey": "76a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac",
|
||||||
|
"scriptpubkey_type": "p2pkh",
|
||||||
|
"scriptpubkey_address": "1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hodlhodl": {
|
||||||
|
"txid": "7723b1bba65cfe805e9dc19fd3981791bdd0984afd5d144bf78abc3bdd522577",
|
||||||
|
"version": 1,
|
||||||
|
"locktime": 0,
|
||||||
|
"size": 402,
|
||||||
|
"weight": 846,
|
||||||
|
"fee": 709,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 867583,
|
||||||
|
"block_time": 1730031351
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "00627dedcaddf995632a9ab806a9aee4a9e1ec4be95fd362981fd53f519ab5b6",
|
||||||
|
"vout": 1,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 87234,
|
||||||
|
"scriptpubkey": "a914d71fecff831d3acd6f5f6932d33b3df22841703587",
|
||||||
|
"scriptpubkey_type": "p2sh",
|
||||||
|
"scriptpubkey_address": "3MJVT2ddTmrLWpg5B9rUXMpSGR4muMKgk8"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 85829,
|
||||||
|
"scriptpubkey": "001495f770898312c1d19922645d9f68a7e1aa92ca9c",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qjhmhpzvrztqarxfzv3we7698ux4f9j5uum047z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 696,
|
||||||
|
"scriptpubkey": "001406f625bd53e5460365f186542005da8d9f6bcdc0",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qqmmzt02nu4rqxe03se2zqpw63k0khnwq959zxq"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"sweep": {
|
||||||
|
"txid": "d41bdca5474d5405153fe9cd57163eea72f16534ea0ac0ad3fd8d46aed2e3a09",
|
||||||
|
"version": 2,
|
||||||
|
"locktime": 0,
|
||||||
|
"size": 191,
|
||||||
|
"weight": 437,
|
||||||
|
"fee": 2025,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 714571,
|
||||||
|
"block_time": 1639770690
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "a8f4edaaf60fcd8776a1750f3a0fa8d056aa2e11389ca10b835c10006bdac3ea",
|
||||||
|
"vout": 0,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 973702,
|
||||||
|
"scriptpubkey": "00149fa967156792152beeccfbc8d2207ec5d4a6ff3c",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qn75kw9t8jg2jhmkvl0ydygr7ch22dleu4jrjtj"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 971677,
|
||||||
|
"scriptpubkey": "00141fc1042f92aa972c8d4d67c1462293f6e1c5fa49",
|
||||||
|
"scriptpubkey_type": "v0_p2wpkh",
|
||||||
|
"scriptpubkey_address": "bc1qrlqsgtuj42tjer2dvlq5vg5n7msut7jf783d6c"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hal": {
|
||||||
|
"txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
|
||||||
|
"version": 1,
|
||||||
|
"locktime": 0,
|
||||||
|
"size": 275,
|
||||||
|
"weight": 1100,
|
||||||
|
"fee": 0,
|
||||||
|
"status": {
|
||||||
|
"confirmed": true,
|
||||||
|
"block_height": 170,
|
||||||
|
"block_time": 1231731025
|
||||||
|
},
|
||||||
|
"vin": [
|
||||||
|
{
|
||||||
|
"txid": "0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9",
|
||||||
|
"vout": 0,
|
||||||
|
"sequence": 4294967295,
|
||||||
|
"is_coinbase": false,
|
||||||
|
"prevout": {
|
||||||
|
"value": 5000000000,
|
||||||
|
"scriptpubkey": "410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac",
|
||||||
|
"scriptpubkey_type": "p2pk"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vout": [
|
||||||
|
{
|
||||||
|
"value": 1000000000,
|
||||||
|
"scriptpubkey": "4104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac",
|
||||||
|
"scriptpubkey_type": "p2pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": 4000000000,
|
||||||
|
"scriptpubkey": "410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac",
|
||||||
|
"scriptpubkey_type": "p2pk"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -34,7 +34,7 @@ const motor = cut("// ── FORMATO: lógica pura", "// ── fin formato") +
|
|||||||
+ cut("function behavioralChangeGuess", "// Busca la tx que gasta un output concreto") + "\n"
|
+ cut("function behavioralChangeGuess", "// Busca la tx que gasta un output concreto") + "\n"
|
||||||
+ cut("function detectPeelingChains", "// ── Motor de rastreo forense") + "\n"
|
+ cut("function detectPeelingChains", "// ── Motor de rastreo forense") + "\n"
|
||||||
+ cut("const ALMACEN_PREFIJO", "// ── fin almacén") + "\n"
|
+ cut("const ALMACEN_PREFIJO", "// ── fin almacén") + "\n"
|
||||||
+ cut("function parsePsbt", "// ── Auditoría de PSBT");
|
+ cut("// ── Parser PSBT (BIP174)", "// ── Auditoría de PSBT");
|
||||||
const E = new Function("crypto", preludio + motor + `
|
const E = new Function("crypto", preludio + motor + `
|
||||||
return { analyzeTx, analyzeAddress, guessChangeOutput, detectWallets, fraseBanda, roundness,
|
return { analyzeTx, analyzeAddress, guessChangeOutput, detectWallets, fraseBanda, roundness,
|
||||||
buildWalletReport, behavioralChangeGuess, combineChangeSignals, detectPeelingChains,
|
buildWalletReport, behavioralChangeGuess, combineChangeSignals, detectPeelingChains,
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c &&
|
|||||||
const P = new Function(`const C = {}; const ENTITY_INDEX = new Map();
|
const P = new Function(`const C = {}; const ENTITY_INDEX = new Map();
|
||||||
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
|
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
|
||||||
${cut("function roundness", "const FORMATO_DIR")}
|
${cut("function roundness", "const FORMATO_DIR")}
|
||||||
${cut("function parsePsbt", "// ── Auditoría de PSBT")}
|
${cut("// ── Parser PSBT (BIP174)", "// ── Auditoría de PSBT")}
|
||||||
${cut("const mensajeTxNoLlega", "async function apiGetJson")}
|
${cut("const mensajeTxNoLlega", "async function apiGetJson")}
|
||||||
return { parsePsbt, analyzePsbt, leerTxPrevia, mensajeTxNoLlega };`)();
|
return { parsePsbt, analyzePsbt, leerTxPrevia, mensajeTxNoLlega };`)();
|
||||||
|
|
||||||
|
|||||||
+174
@@ -0,0 +1,174 @@
|
|||||||
|
// 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);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// v1.48.1 — transacciones reales del contraste con am-i-exposed y Blockchair
|
||||||
|
// (25-oct-2026), como pruebas fijas del analizador.
|
||||||
|
//
|
||||||
|
// Dos partes:
|
||||||
|
// 1. Lo que Txoko ya lee bien (si deja de hacerlo, falla).
|
||||||
|
// 2. Lo que el parche 2 tiene que arreglar: se listan como PENDIENTE (◻) y
|
||||||
|
// no hacen fallar la prueba todavía. Cuando el parche 2 los arregle,
|
||||||
|
// saldrán con ✓ y pasarán a la parte 1.
|
||||||
|
//
|
||||||
|
// Los datos vienen de mempool.space (tests/fixtures/contraste-25oct.json). Para
|
||||||
|
// comprobar que no se copiaron mal, en las transacciones solo SegWit se
|
||||||
|
// recalcula el txid a partir de los datos y se compara.
|
||||||
|
//
|
||||||
|
// Uso: node tests/test38.js
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
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 E = new Function(`const C = { green:"g", amber:"a", red:"r", t1:"t1", t2:"t", blue:"b", purple:"p" };
|
||||||
|
const ENTITY_INDEX = new Map(); const OFAC_SET = new Set();
|
||||||
|
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
|
||||||
|
${cut("function detectWallets", "function analyzeAddress")}
|
||||||
|
${cut("// ── BOLTZMANN", "// ── fin boltzmann")}
|
||||||
|
return { analyzeTx, boltzmannDeTx };`)();
|
||||||
|
const T = JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures", "contraste-25oct.json"), "utf8")).txs;
|
||||||
|
|
||||||
|
let pass = 0, fail = 0, pend = 0, yaArreglado = 0;
|
||||||
|
const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c && x !== undefined) console.log(" " + x); c ? pass++ : fail++; };
|
||||||
|
const pendiente = (n, c) => { if (c) { console.log(` ✓ (ya arreglado) ${n}`); yaArreglado++; } else { console.log(` ◻ PENDIENTE parche 2: ${n}`); pend++; } };
|
||||||
|
const ch = (a, id) => a.checks.find(c => c.id === id);
|
||||||
|
const A = {}; for (const [k, tx] of Object.entries(T)) A[k] = E.analyzeTx(tx);
|
||||||
|
|
||||||
|
console.log("=== Los datos son los de la cadena ===\n");
|
||||||
|
{
|
||||||
|
const h = b => Buffer.from(b, "hex");
|
||||||
|
const le = (n, bytes) => { const b = Buffer.alloc(bytes); let v = BigInt(n); for (let i = 0; i < bytes; i++) { b[i] = Number(v & 255n); v >>= 8n; } return b; };
|
||||||
|
const cs = n => n < 0xfd ? Buffer.from([n]) : Buffer.concat([Buffer.from([0xfd]), le(n, 2)]);
|
||||||
|
const txid = tx => {
|
||||||
|
const partes = [le(tx.version, 4), cs(tx.vin.length)];
|
||||||
|
for (const v of tx.vin) partes.push(h(v.txid).reverse(), le(v.vout, 4), cs(0), le(v.sequence, 4));
|
||||||
|
partes.push(cs(tx.vout.length));
|
||||||
|
for (const o of tx.vout) { const s = h(o.scriptpubkey); partes.push(le(o.value, 8), cs(s.length), s); }
|
||||||
|
partes.push(le(tx.locktime, 4));
|
||||||
|
const d = crypto.createHash("sha256").update(crypto.createHash("sha256").update(Buffer.concat(partes)).digest()).digest();
|
||||||
|
return Buffer.from(d).reverse().toString("hex");
|
||||||
|
};
|
||||||
|
for (const k of ["whirlpool", "joinmarket", "taproot_opreturn", "sweep"]) ok(`${k}: el txid recalculado coincide`, txid(T[k]) === T[k].txid);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("\n=== Lo que Txoko ya lee bien ===\n");
|
||||||
|
ok("Whirlpool 5×5: CoinJoin reconocido y banda ALTA", ch(A.whirlpool, "coinjoin").pass === true && A.whirlpool.band === "ALTA");
|
||||||
|
ok("Whirlpool 5×5: 1.496 interpretaciones de Boltzmann", E.boltzmannDeTx(T.whirlpool).interpretaciones === 1496);
|
||||||
|
const camHal = ch(A.hal, "change_detection");
|
||||||
|
ok("Satoshi → Hal: ve que los 40 BTC vuelven a la clave de Satoshi (salida 1), aunque no tengan dirección (am-i-exposed no lo ve)", camHal && camHal.pass === false && /vuelve a la misma dirección o clave/.test(camHal.detail), camHal && camHal.detail.slice(0, 120));
|
||||||
|
const camPolvo = ch(A.dust, "change_detection");
|
||||||
|
ok("Polvo 555 sat: el cambio es la salida que vuelve a la dirección que paga (salida 1)", camPolvo && camPolvo.pass === false && /salida 1/.test(camPolvo.detail), camPolvo && camPolvo.detail.slice(0, 120));
|
||||||
|
ok("Polvo 555 sat: la salida de 555 sat se señala como posible polvo", ch(A.dust, "dust") && ch(A.dust, "dust").pass === false);
|
||||||
|
ok("Barrido 1→1: ninguna fuga propia (banda ALTA)", A.sweep.band === "ALTA");
|
||||||
|
ok("Pago simple antiguo: el formato antiguo se señala", ch(A.simple, "legacy_type") && ch(A.simple, "legacy_type").pass === false);
|
||||||
|
ok("Taproot + mensaje de BitGo: el OP_RETURN se ve", ch(A.taproot_opreturn, "op_return") && ch(A.taproot_opreturn, "op_return").pass === false);
|
||||||
|
ok("JoinMarket/Stonewall 2→4: se ve la forma de Stonewall y se duda (POSIBLE)", ch(A.joinmarket, "stonewall") && ch(A.joinmarket, "input_linkage").certainty === "POSIBLE");
|
||||||
|
|
||||||
|
console.log("\n=== Lo que tiene que arreglar el parche 2 (no falla todavía) ===\n");
|
||||||
|
pendiente("JoinMarket/Stonewall: no decir «No es un CoinJoin» con CERTEZA", ch(A.joinmarket, "coinjoin").certainty !== "CERTEZA");
|
||||||
|
pendiente("Satoshi → Hal: CERTEZA solo de que vuelve a quien paga; «es el cambio» como interpretación", camHal && !/: es el cambio/.test(camHal.detail));
|
||||||
|
pendiente("Escrow HodlHodl: la comisión de 696 sat no es polvo", !(ch(A.hodlhodl, "dust") && ch(A.hodlhodl, "dust").pass === false));
|
||||||
|
pendiente("Escrow HodlHodl: la multifirma 2-de-3 no se presenta como «formato antiguo» a secas", !(ch(A.hodlhodl, "legacy_type") && ch(A.hodlhodl, "legacy_type").pass === false));
|
||||||
|
{
|
||||||
|
// La pizza (a1075db5…): 131 entradas de una misma dirección. Réplica con su
|
||||||
|
// estructura (los importes de las entradas no importan para esto).
|
||||||
|
const dir = "1XPTgDRhN8RFnzniWCddobD9iKZatrvH4";
|
||||||
|
const pizza = { txid: "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d", version: 1, locktime: 0, weight: 94480, size: 23620, fee: 99000000,
|
||||||
|
status: { confirmed: true, block_height: 57043, block_time: 1274552191 },
|
||||||
|
vin: Array.from({ length: 131 }, (_, i) => ({ txid: (i + 1).toString(16).padStart(64, "c"), vout: 0, sequence: 4294967295, prevout: { value: i === 0 ? 1000099000000 - 130 * 1000000 : 1000000, scriptpubkey_address: dir, scriptpubkey_type: "p2pkh", scriptpubkey: "76a914" + "00".repeat(20) + "88ac" } })),
|
||||||
|
vout: [{ value: 1000000000000, scriptpubkey_address: "17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ", scriptpubkey_type: "p2pkh", scriptpubkey: "76a914" + "01".repeat(20) + "88ac" }] };
|
||||||
|
const r = ch(E.analyzeTx(pizza), "input_reuse");
|
||||||
|
pendiente("Pizza: «1 dirección aparece 131 veces», no «130 dirección(es) aparecen repetidas»", r && !/130 dirección/.test(r.detail));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`\n${pass} correctas, ${fail} fallidas · ${pend} pendientes del parche 2${yaArreglado ? ` · ${yaArreglado} ya arregladas: pásalas a la primera parte` : ""}`);
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
Reference in New Issue
Block a user