From 58249da67b73dd443df3a23ca020c910e031d886 Mon Sep 17 00:00:00 2001 From: pikaro Date: Tue, 13 Oct 2026 20:10:56 +0000 Subject: [PATCH] =?UTF-8?q?v1.24.7:=20informe=20pericial=20sin=20atribuir?= =?UTF-8?q?=20de=20m=C3=A1s=20(huella=20vac=C3=ADa=20no=20cuenta;=20ramas?= =?UTF-8?q?=20no=20seguidas=20=C2=ABsin=20determinar=C2=BB),=20importe=20d?= =?UTF-8?q?e=20la=20salida=20y=20seguido,=20paradas=20y=20ramas=20pendient?= =?UTF-8?q?es,=20mezcla=20como=20HECHO;=20test12.js=20con=20el=20rastro=20?= =?UTF-8?q?real=20Satoshi=E2=86=92Hal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 23 +++++ dashboard.html | 246 +++++++++++++++++++++++++++++++++++++++++------- tests/README.md | 1 + tests/test10.js | 2 +- tests/test12.js | 165 ++++++++++++++++++++++++++++++++ 5 files changed, 403 insertions(+), 34 deletions(-) create mode 100644 tests/test12.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2645067..c4b95fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,29 @@ y el versionado sigue [Versionado Semántico](https://semver.org/lang/es/): - **PARCHE** — arreglos de errores --- +## [1.24.7] — 2026-10-13 + +### Arreglado — informe pericial del peritaje (pantalla, Markdown y JSON) +Visto en un informe real: Satoshi→Hal, seguido 7 saltos hacia delante. +- **Atribuía de más.** 9 de 11 direcciones salían «del actor» solo por una «huella de wallet estable», y en todos los saltos la huella era «sin rasgos distintivos», es decir, ninguna. Entraban salidas que nunca se siguieron y la dirección final. Ahora: + - «sin rasgos distintivos» no cuenta como huella, así que dos saltos sin huella no tienen «la misma huella»; + - una huella identificada y estable solo acompaña a otro fundamento; por sí sola no atribuye nada; + - se atribuyen el camino seguido (direcciones que recibieron lo seguido y lo volvieron a mover en el salto siguiente), el cambio detectado y las co-entradas por CIOH; + - las salidas no seguidas quedan «sin determinar» (o en destinatarios, si parecen un pago); + - la última dirección alcanzada es «rama abierta». +- **CIOH.** Solo agrupa direcciones que son ENTRADAS de una misma transacción: la semilla del agrupamiento ya no incluye salidas. En el informe real, el grupo {18cHSR…, 1FvShf…} sale de que c7bc… gasta las dos salidas de 8aab…, como indican los importes: entra 1 BTC en a1fd…, y por 18cHSR… solo llegaban 0,01. Ahora el informe lo dice: «se vuelven a juntar salidas de transacciones anteriores del rastro». +- **Cronología con dos importes.** Cada fila lleva el importe de la salida y el importe seguido (reparto proporcional), en pantalla, Markdown, CSV (columnas nuevas al final: `seguido_sats`, `seguido_btc`, `via`) y JSON (`followed`). El importe seguido cuenta también las salidas del rastro que vuelven a juntarse, y la vista del peritaje usa la misma cuenta. «De» lista todas las entradas de la transacción, la seguida primero. +- **Conclusiones que faltaban (HECHO):** + - dónde y por qué se detuvo cada rama: aquí, en el salto 7, porque se dejó de seguir, sin llegar a un final natural; + - las ramas sin seguir, con su importe y su parte de lo seguido; + - la mezcla con dinero de otras direcciones, con importes y porcentaje, aunque no se haya declarado el importe robado. +- **Origen P2PK.** `summary.originAddress` decía "": ahora dice «clave pública (P2PK, sin dirección)». + +### Pruebas +- `tests/test12.js` (nuevo, 26 casos), construido con los txids, direcciones, bloques e importes del rastro real. 22 de ellos fallan en la v1.24.6. + +--- + ## [1.24.6] — 2026-10-13 ### Arreglado diff --git a/dashboard.html b/dashboard.html index 4f5d1b2..e0094e1 100644 --- a/dashboard.html +++ b/dashboard.html @@ -5050,12 +5050,15 @@ // "cambio de actor o entrada en infraestructura de un servicio" — nunca // CERTEZA, porque una misma persona puede cambiar de wallet sin cambiar // de dueño de los fondos. + // «sin rasgos distintivos» es la AUSENCIA de huella: dos saltos sin huella + // no tienen «la misma huella». Solo se comparan huellas identificadas. + const huellaIdentificada = fp => { const n = fp?.[0]?.name || null; return n && n !== "sin rasgos distintivos" ? n : null; }; function compareFingerprints(prevFp, nextFp) { - const prevTop = prevFp?.[0]?.name || null; - const nextTop = nextFp?.[0]?.name || null; + const prevTop = huellaIdentificada(prevFp); + const nextTop = huellaIdentificada(nextFp); if (!prevTop || !nextTop) { return { changed: null, certainty: null, - note: "Huella insuficiente en uno de los dos saltos para comparar." }; + note: "Sin huella identificada en uno de los dos saltos (o en ambos): no hay nada que comparar." }; } if (prevTop === nextTop) { return { changed: false, certainty: null, @@ -5579,7 +5582,7 @@ // ── 1. Resumen ────────────────────────────────────────────────────── const summary = { - originTxid: origin.txid, originVout: origin.vout, originAddress: origin.address, + originTxid: origin.txid, originVout: origin.vout, originAddress: origin.address || origin.addressLabel || "", amountTraced: origin.amount, amountStolen, generatedAt: Math.floor(Date.now()/1000), hops: maxHop, txCount: allNodes.length + 1, addressesTouched: addressesTouched.size, @@ -5591,15 +5594,18 @@ : null; // ── 3. Cronología ──────────────────────────────────────────────────── - const chronologyRow = (txid, hop, blockTime, blockHeight, amount, analysis, fingerprint, entityMarks) => ({ - level: "HECHO", txid, hop, blockTime, blockHeight, amount, refs:[txid], + // amount = importe de la(s) salida(s) seguida(s) que entran en la tx; + // followed = importe seguido: reparto proporcional de lo robado (una + // cuenta, no una atribución). Pueden ser muy distintos. + const chronologyRow = (txid, hop, blockTime, blockHeight, amount, analysis, fingerprint, entityMarks, followed) => ({ + level: "HECHO", txid, hop, blockTime, blockHeight, amount, followed: followed ?? null, refs:[txid], band: { level:"INFERENCIA", certainty: analysis?.band ? (analysis.band==="ALTA"?"CERTEZA":analysis.band==="MEDIA"?"PROBABLE":"POSIBLE") : null, value: analysis?.band || "—" }, fingerprint: { level:"INFERENCIA", certainty: fingerprint?.[0]?.confidence || null, value: fingerprint?.[0]?.name || "sin huella clara" }, entityMarks: entityMarks || [], }); const chronology = [ - chronologyRow(origin.txid, 0, origin.blockTime, origin.blockHeight, origin.amount, origin.analysis, origin.fingerprint, origin.entityMarks), - ...allNodes.map(n => chronologyRow(n.txid, n.hop, n.blockTime, n.blockHeight, n.amountTraced, n.analysis, n.fingerprint, n.entityMarks)), + chronologyRow(origin.txid, 0, origin.blockTime, origin.blockHeight, origin.amount, origin.analysis, origin.fingerprint, origin.entityMarks, origin.amount), + ...allNodes.map(n => chronologyRow(n.txid, n.hop, n.blockTime, n.blockHeight, n.amountTraced, n.analysis, n.fingerprint, n.entityMarks, n.amountFollowed)), ]; // ── 4. Direcciones atribuidas al actor ────────────────────────────── @@ -5670,12 +5676,34 @@ certainty: c.certainty, refTxid: c.txid, }); } - if (fingerprintStableAddrs.has(a) && !destinatariosMap.has(a)) fundamentos.push({ basis:"huella de wallet estable con el salto anterior", certainty:"POSIBLE" }); - if (fundamentos.length === 0) continue; + const ruta = graph.rutaSeguida?.get(a); + if (ruta) fundamentos.push({ basis:"recibió lo seguido y lo volvió a mover en el salto siguiente del rastro", certainty:"POSIBLE", refTxid: ruta.txid }); + // La huella estable solo acompaña: por sí sola no atribuye nada. + if (fingerprintStableAddrs.has(a) && !destinatariosMap.has(a)) fundamentos.push({ basis:"huella de wallet identificada y estable con el salto anterior (solo acompaña)", certainty:"POSIBLE", apoyo:true }); + if (fundamentos.filter(f => !f.apoyo).length === 0) continue; if (destinatariosMap.has(a) && !clusterOf.has(a)) continue; attributed.push({ level:"INFERENCIA", address:a, fundamentos, refs:[a] }); } + // Salidas que no se siguieron ni tienen fundamento: «sin determinar». + // Nunca del actor por defecto. Las de la última tx de una rama son + // «rama abierta»: ahí se dejó de seguir. + const desdeTx = new Set((graph.edges || []).map(e => e.fromTxid)); + const atribSet = new Set(attributed.map(x => x.address)); + const sinDeterminar = [], vistosSD = new Set(); + for (const n of allNodes) { + if (n.stopReason === "mixer" || n.stopReason === "fanOut") continue; + for (const a of n.addresses.out) { + if (atribSet.has(a) || destinatariosMap.has(a) || (n.custodyAddrs || []).includes(a) || vistosSD.has(a)) continue; + vistosSD.add(a); + const abierta = !desdeTx.has(n.txid); + sinDeterminar.push({ level:"HECHO", address:a, txid:n.txid, ramaAbierta:abierta, + basis: abierta ? "rama abierta: es donde se dejó de seguir; sin indicios para atribuirla" : "salida no seguida: sin indicios para atribuirla", refs:[n.txid, a] }); + } + } + const pendingBranches = graph.pendientes || []; + const paradaRastro = graph.paradas || []; + // ── 5. Fondos localizados sin gastar ──────────────────────────────── // Solo entra aquí lo COMPROBADO sin gastar. Las ramas con consulta // fallida (queryFailed) se quedan fuera a propósito: afirmar que unos @@ -5736,6 +5764,37 @@ conclusions.push({ level:"HECHO", text:`El rastro se detiene en ${n.txid} por el tope de transacciones exploradas — una red de seguridad aparte del límite de saltos, para no sobrecargar el nodo si un salto desemboca en una consolidación con muchísimas ramas. No es un punto de parada natural; se puede seguir rastreando manualmente desde aquí si hace falta.`, refs:[n.txid] }); } } + // Mezcla con dinero de otros (HECHO: importes de la cadena, haya o no + // importe robado declarado) y salidas del rastro que vuelven a juntarse. + for (const n of allNodes) { + const m = n.mezcla; + if (!m) continue; + if (m.reunidas.length) conclusions.push({ level:"HECHO", + text:`En el salto ${n.hop} (tx ${n.txid}) se vuelven a juntar salidas de transacciones anteriores del rastro que no se habían seguido: ${m.reunidas.map(x => `${x.address} (${btcTxt(x.value)}, de la tx ${x.txid.slice(0,16)}…)`).join(", ")}. Por eso lo que entra es más que la salida seguida.`, + refs:[n.txid, ...m.reunidas.map(x => x.txid)] }); + if (m.otras.length) { + const suma = m.otras.reduce((t, x) => t + x.value, 0); + conclusions.push({ level:"HECHO", + text:`En el salto ${n.hop} (tx ${n.txid}) el dinero seguido se juntó con ${btcTxt(suma)} de otra${m.otras.length > 1 ? "s" : ""} dirección${m.otras.length > 1 ? "es" : ""} (${[...new Set(m.otras.map(x => x.address))].join(", ")}). Entran ${btcTxt(m.tin)} en total; lo seguido es ${btcTxt(m.seguido)} (reparto proporcional), el ${m.tin ? (Math.round(m.seguido / m.tin * 1000) / 10).toLocaleString("es-ES") : "0"} % de lo que entra. Desde aquí, cada salida lleva dinero mezclado.`, + refs:[n.txid, ...m.otras.map(x => x.address)] }); + } + } + for (const pr of paradaRastro) { + if (pr.motivo === "usuario") conclusions.push({ level:"HECHO", + text:`El rastro se detuvo en el salto ${pr.hop} (tx ${pr.txid}) porque se dejó de seguir: lo decidió quien hizo el peritaje. No se llegó a un final natural (depósito en un servicio, mezcla o monedas sin gastar); lo que sigue desde ahí está sin explorar.`, refs:[pr.txid] }); + else if (pr.motivo === "sin_gastar") conclusions.push({ level:"HECHO", + text:`La rama del salto ${pr.hop} (tx ${pr.txid}) termina en monedas sin gastar: es un final natural del rastro.`, refs:[pr.txid] }); + else if (pr.motivo === "tope") conclusions.push({ level:"HECHO", + text:`La rama del salto ${pr.hop} (tx ${pr.txid}) se detuvo en el tope de saltos configurado, no en un final natural.`, refs:[pr.txid] }); + } + if (pendingBranches.length > 0) { + conclusions.push({ level:"HECHO", + text:`Quedan ${pendingBranches.length} rama(s) sin seguir: ${pendingBranches.map(b => `${b.address} (salida ${b.vout+1} de la tx ${b.txid.slice(0,16)}…, ${btcTxt(b.amount)}; de lo seguido, ${btcTxt(b.seguido)} por reparto proporcional; ${b.estado})`).join("; ")}. Lo que pasó con ese dinero no está en este informe.`, + refs: pendingBranches.map(b => b.txid) }); + } + if (sinDeterminar.length > 0) { + conclusions.push({ level:"HECHO", text:`${sinDeterminar.length} dirección(es) del rastro quedan sin determinar: salidas no seguidas o donde se dejó de seguir. No se atribuyen al actor.`, refs: sinDeterminar.map(x => x.address) }); + } if (unspentFunds.length > 0) { conclusions.push({ level:"HECHO", text:`${unspentFunds.length} salida(s) con fondos localizados sin gastar, sumando ${btcTxt(unspentFunds.reduce((s,u)=>s+u.amount,0))}.`, refs: unspentFunds.map(u=>u.txid) }); } @@ -5776,7 +5835,7 @@ }; const destinatarios = [...destinatariosMap.values()].filter(d => !attributed.some(x => x.address === d.address)); - return { summary, declaracion, chronology, attributed, destinatarios, unspentFunds, truncatedBranches, failedBranches, queryErrors, conclusions, recommendations, methodology, verificationAppendix }; + return { summary, declaracion, chronology, attributed, destinatarios, sinDeterminar, pendingBranches, paradaRastro, unspentFunds, truncatedBranches, failedBranches, queryErrors, conclusions, recommendations, methodology, verificationAppendix }; } // Eslabón recursivo: muestra una tx de origen y permite seguir SUS inputs. @@ -6256,15 +6315,48 @@ return r; } - // Cronología de movimientos explorados, en orden. + // Importe seguido que entra en cada tx abierta: reparto proporcional de + // lo robado. Cuenta TODAS las entradas que vienen del rastro (la salida + // robada del origen o salidas de txs abiertas), también las que no se + // siguieron una a una pero vuelven a juntarse. Una cuenta, no una + // atribución. + function seguidoPorTx(per) { + const ori = per.origen, memo = new Map(), enCurso = new Set(); + const valorRobado = per.txs.get(ori.txid)?.vout?.[ori.vout]?.value || 0; + const parte = (txid, vout) => { + if (txid === ori.txid) return vout === ori.vout ? valorRobado : 0; + if (!per.abiertas.has(txid) || !per.txs.has(txid)) return 0; + return repartoSalida(entra(txid), per.txs.get(txid), vout).sats; + }; + const entra = txid => { + if (txid === ori.txid) return valorRobado; + if (memo.has(txid)) return memo.get(txid); + if (enCurso.has(txid)) return 0; + enCurso.add(txid); + const s = (per.txs.get(txid)?.vin || []).reduce((t, v) => t + parte(v.txid, v.vout), 0); + enCurso.delete(txid); memo.set(txid, s); + return s; + }; + const r = new Map(); + for (const t of per.abiertas) if (per.txs.has(t)) r.set(t, entra(t)); + r.parte = parte; + return r; + } + + // Cronología de movimientos explorados, en orden. `sats` es el importe + // de la salida que se gasta; `seguido`, la parte de lo robado que va por + // ella (reparto proporcional). `de` son TODAS las entradas de la tx + // (la seguida primero, en `via`). function cronologiaPeritaje(per) { const filas = []; + const seg = seguidoPorTx(per); + const dirDe = x => x ? (x.scriptpubkey_address || etiquetaSinDir(x)) : null; const ori = per.txs.get(per.origen.txid); if (ori) { const o = ori.vout[per.origen.vout]; - filas.push({ fecha: ori.status?.block_time || null, txid: ori.txid, sats: o?.value || 0, - de: [...new Set((ori.vin || []).map(v => v.prevout ? (v.prevout.scriptpubkey_address || etiquetaSinDir(v.prevout)) : null).filter(Boolean))], - a: o ? [o.scriptpubkey_address || etiquetaSinDir(o)] : [], que: "robo (salida de origen)" }); + filas.push({ fecha: ori.status?.block_time || null, txid: ori.txid, sats: o?.value || 0, seguido: o?.value || 0, + de: [...new Set((ori.vin || []).map(v => dirDe(v.prevout)).filter(Boolean))], via: null, + a: o ? [dirDe(o)] : [], que: "robo (salida de origen)" }); } for (const [k, g] of per.gastos) { if (g.estado !== "gastada" || !per.abiertas.has(g.spendTxid)) continue; @@ -6272,23 +6364,24 @@ const o = per.txs.get(txid)?.vout?.[Number(vout)]; const tg = per.txs.get(g.spendTxid); if (!o || !tg) continue; - filas.push({ fecha: tg.status?.block_time || null, txid: tg.txid, sats: o.value, - de: [o.scriptpubkey_address || etiquetaSinDir(o)], - a: [...new Set((tg.vout || []).map(x => x.scriptpubkey_address || etiquetaSinDir(x)))], que: "movimiento" }); + const via = dirDe(o); + filas.push({ fecha: tg.status?.block_time || null, txid: tg.txid, sats: o.value, seguido: seg.parte(txid, Number(vout)), + de: [...new Set([via, ...(tg.vin || []).map(v => dirDe(v.prevout)).filter(Boolean)])], via, + a: [...new Set((tg.vout || []).map(x => dirDe(x)))], que: "movimiento" }); } return filas.sort((a, b) => (a.fecha || Infinity) - (b.fecha || Infinity)); } const fechaISO = ts => ts ? new Date(ts * 1000).toISOString().replace("T", " ").slice(0, 16) + " UTC" : "sin confirmar"; function cronologiaCSV(filas) { const q = s => `"${String(s).replace(/"/g, '""')}"`; - return ["fecha,importe_sats,importe_btc,de,a,txid,tipo", - ...filas.map(f => [q(fechaISO(f.fecha)), f.sats, (f.sats / 1e8).toFixed(8), q(f.de.join(" ")), q(f.a.join(" ")), f.txid, q(f.que)].join(","))].join("\n"); + return ["fecha,importe_sats,importe_btc,de,a,txid,tipo,seguido_sats,seguido_btc,via", + ...filas.map(f => [q(fechaISO(f.fecha)), f.sats, (f.sats / 1e8).toFixed(8), q(f.de.join(" ")), q(f.a.join(" ")), f.txid, q(f.que), f.seguido ?? "", f.seguido != null ? (f.seguido / 1e8).toFixed(8) : "", q(f.via || "")].join(","))].join("\n"); } function cronologiaMD(filas, ejemplo) { return [`# Cronología de movimientos — Txoko${ejemplo ? " (EJEMPLO)" : ""}`, "", - "| Fecha | Importe | De | A | Txid |", "| --- | --- | --- | --- | --- |", - ...filas.map(f => `| ${fechaISO(f.fecha)} | ${btcTxt(f.sats)} | ${f.de.join(", ") || "—"} | ${f.a.length > 4 ? f.a.slice(0, 4).join(", ") + ` y ${f.a.length - 4} más` : f.a.join(", ") || "—"} | \`${f.txid}\` |`), - "", "_Solo lo explorado en este peritaje. Los importes son los de cada salida gastada._"].join("\n"); + "| Fecha | Importe de la salida | Importe seguido (proporcional) | De | A | Txid |", "| --- | --- | --- | --- | --- | --- |", + ...filas.map(f => `| ${fechaISO(f.fecha)} | ${btcTxt(f.sats)} | ${f.seguido != null ? btcTxt(f.seguido) : "—"} | ${f.de.join(", ") || "—"} | ${f.a.length > 4 ? f.a.slice(0, 4).join(", ") + ` y ${f.a.length - 4} más` : f.a.join(", ") || "—"} | \`${f.txid}\` |`), + "", "_Solo lo explorado en este peritaje. «Importe de la salida» es el de la salida gastada; «importe seguido» es la parte de lo robado que va por ella según un reparto proporcional por importes (una cuenta, no una atribución). «De» lista todas las entradas de la transacción, la seguida primero._"].join("\n"); } // Vigilancia de salidas sin gastar: compara la comprobación nueva con la @@ -6341,6 +6434,7 @@ } } const padreDe = txid => edges.find(e => e.toTxid === txid)?.fromTxid; + const seg = seguidoPorTx(per); const huella = new Map([[ori.txid, detectWallets(ori)]]); const orden = [...per.abiertas].filter(t => t !== ori.txid && per.txs.has(t) && hops.has(t)).sort((a, b) => hops.get(a) - hops.get(b)); for (const t of orden) { @@ -6354,13 +6448,21 @@ const custodyAddrs = outAddrs.filter(a => entidadDe(a)?.cat === "exchange"); const custodyStop = custodyAddrs.length ? { addr:custodyAddrs[0], name:entidadDe(custodyAddrs[0]).name, known:true, byVolume:false } : null; const dil = detectarDilucion(tx, entrante.get(t) || 0, per.robado); + // Entradas: las que vienen del rastro (seguidas o que vuelven a + // juntarse) y las de otros. HECHO, con o sin importe robado. + const entradas = (tx.vin || []).map(v => ({ txid:v.txid, vout:v.vout, value:v.prevout?.value || 0, + address: v.prevout ? (v.prevout.scriptpubkey_address || etiquetaSinDir(v.prevout)) : "—", + delRastro: v.txid === ori.txid ? v.vout === per.origen.vout : per.abiertas.has(v.txid), + seguida: edges.some(e => e.toTxid === t && e.fromTxid === v.txid && e.fromVout === v.vout) })); + const mezcla = { tin: entradas.reduce((a, x) => a + x.value, 0), seguido: seg.get(t) || 0, + otras: entradas.filter(x => !x.delRastro), reunidas: entradas.filter(x => x.delRastro && !x.seguida) }; const parada = paradaSalto(tx, hops.get(t), per.maxSaltos); const p = padreDe(t); nodes.set(t, { txid:t, hop:hops.get(t), blockTime:tx.status?.block_time ?? null, blockHeight: tx.status?.confirmed ? (tx.status.block_height ?? null) : null, confirmed:!!tx.status?.confirmed, vinCount:(tx.vin || []).length, voutCount:(tx.vout || []).length, addresses:{ in:inAddrs, out:outAddrs }, - amountTraced: entrante.get(t) || 0, analysis, fingerprint, + amountTraced: entrante.get(t) || 0, amountFollowed: seg.get(t) || 0, mezcla, analysis, fingerprint, fingerprintComparison: p && huella.has(p) ? compareFingerprints(huella.get(p), fingerprint) : null, entityMarks: marcasDeTx(tx, analysis).marcas, addressProfiles:{}, changeGuess:{ structural, behavioral:null, combined:null }, @@ -6370,23 +6472,62 @@ stopReason: parada?.motivo === "coinjoin" ? "mixer" : parada?.motivo === "abanico" ? "fanOut" : custodyStop ? "exchange" : null, }); } - const actor = new Set([oo.scriptpubkey_address].filter(Boolean)), mixers = new Set(); + // Semilla para CIOH: solo ENTRADAS de las txs abiertas (y la salida + // robada). Las salidas no se agrupan nunca por estar en la misma tx. // En un salto con dilución, las otras entradas son dinero de otros: al // actor solo se le atribuye la dirección por la que llegó el rastro. + const actor = new Set([oo.scriptpubkey_address].filter(Boolean)), mixers = new Set(); const llegada = t => edges.filter(e => e.toTxid === t).map(e => per.txs.get(e.fromTxid)?.vout?.[e.fromVout]?.scriptpubkey_address).filter(Boolean); for (const n of nodes.values()) { if (n.stopReason === "mixer") { mixers.add(n.txid); continue; } (n.diluted ? llegada(n.txid) : n.addresses.in).forEach(a => actor.add(a)); - n.addresses.out.forEach(a => { if (!n.custodyAddrs.includes(a)) actor.add(a); }); + } + // Camino seguido: direcciones que recibieron lo seguido y lo volvieron + // a mover en un salto abierto. + const rutaSeguida = new Map(); + for (const e of edges) { + if (mixers.has(e.toTxid)) continue; + const a = per.txs.get(e.fromTxid)?.vout?.[e.fromVout]?.scriptpubkey_address; + if (a && !rutaSeguida.has(a)) rutaSeguida.set(a, { txid:e.toTxid }); + } + // Dónde se detuvo cada rama y por qué; ramas que quedan sin seguir. + const desde = new Set(edges.map(e => e.fromTxid)); + const salidasDe = t => t === ori.txid ? [per.origen.vout] : (per.txs.get(t)?.vout || []).map((_, i) => i); + const cuenta = (t, i) => { const o = per.txs.get(t)?.vout?.[i]; return o && !esSalidaDeDatos(o) && o.value >= PER_POLVO && entidadDe(o.scriptpubkey_address)?.cat !== "exchange"; }; + const paradas = [ori.txid, ...orden].filter(t => !desde.has(t)).map(t => { + const n = nodes.get(t), tx = per.txs.get(t); + let motivo = t === ori.txid ? null : (paradaSalto(tx, hops.get(t), per.maxSaltos)?.motivo || (n?.custodyStop ? "exchange" : null)); + if (!motivo) { + const ss = salidasDe(t).filter(i => cuenta(t, i)); + motivo = ss.length === 0 ? "sin_salidas" : ss.every(i => per.gastos.get(claveSalida(t, i))?.estado === "sin_gastar") ? "sin_gastar" : "usuario"; + } + return { txid:t, hop:hops.get(t) ?? 0, motivo }; + }); + const gastadaEnAbierta = (t, i) => [...per.abiertas].some(x => (per.txs.get(x)?.vin || []).some(v => v.txid === t && v.vout === i)); + const pendientes = []; + for (const t of [ori.txid, ...orden]) { + const n = nodes.get(t); + if (n && (n.stopReason === "mixer" || n.stopReason === "fanOut")) continue; + for (const i of salidasDe(t)) { + if (!cuenta(t, i)) continue; + const g = per.gastos.get(claveSalida(t, i)); + if (g && g.estado !== "gastada") continue; // terminal o fallo: va en su sección + if (g && per.abiertas.has(g.spendTxid)) continue; + if (gastadaEnAbierta(t, i)) continue; // vuelve a juntarse en un salto abierto + const o = per.txs.get(t).vout[i]; + pendientes.push({ level:"HECHO", txid:t, vout:i, hop:hops.get(t) ?? 0, address:o.scriptpubkey_address || etiquetaSinDir(o), amount:o.value, seguido:seg.parte(t, i), + estado: g ? `gastada en la tx ${g.spendTxid.slice(0,16)}…, sin abrir` : "sin comprobar", spendTxid:g?.spendTxid || null, refs:[t] }); + } } const diluidas = new Set([...nodes.values()].filter(n => n.diluted).map(n => n.txid)); const { clusters, linkReasons } = unionFindCluster([...per.txs.values()].filter(t => per.abiertas.has(t.txid) && !mixers.has(t.txid) && !diluidas.has(t.txid)), actor); const oa = analyzeTx(ori); return { - origin: { txid:ori.txid, vout:per.origen.vout, address:oo.scriptpubkey_address, amount:oo.value, + origin: { txid:ori.txid, vout:per.origen.vout, address:oo.scriptpubkey_address, addressLabel: oo.scriptpubkey_address || etiquetaSinDir(oo), amount:oo.value, blockTime:ori.status?.block_time ?? null, blockHeight: ori.status?.confirmed ? (ori.status.block_height ?? null) : null, fingerprint: huella.get(ori.txid), analysis: oa, entityMarks: marcasDeTx(ori, oa).marcas }, amountStolen: per.robado || null, nodes, edges, unspentTerminals, clusters, linkReasons, queryErrors, + rutaSeguida, paradas, pendientes, peelingChains: detectPeelingChains(nodes, edges), modo:"a_demanda", }; } @@ -7194,7 +7335,10 @@ // Lo que se sigue en cada salto del camino, por reparto de importes. // En el salto 1 se sigue la salida robada entera; después, la parte // proporcional de lo que entró en cada salto. - const seguidos = []; camino.forEach((h,k)=>{ if(k<=1){ seguidos.push(per.txs.get(camino[0].txid).vout[per.origen.vout]?.value||0); } else { seguidos.push(repartoSalida(seguidos[k-1], per.txs.get(camino[k-1].txid), h.via).sats); } }); + // Lo mismo que el informe: reparto proporcional que cuenta también las + // salidas del rastro que vuelven a juntarse. + const segTx = seguidoPorTx(per); + const seguidos = camino.map((h,k)=> k===0 ? (per.txs.get(camino[0].txid).vout[per.origen.vout]?.value||0) : (segTx.get(h.txid) ?? 0)); const marcada = !!mesa[hop.txid]; const marcar = () => setMesa(m=>{ const n={...m}; if(n[hop.txid]) delete n[hop.txid]; else n[hop.txid]={nota:"",fecha:Date.now(),origen:per.origen.txid}; return n; }); const vigiladas = new Set(Object.keys(vigilancia)); @@ -7957,6 +8101,7 @@ const exportData = { summary: report.summary, declaracion: report.declaracion, chronology: report.chronology, attributed: report.attributed, + sinDeterminar: report.sinDeterminar, pendingBranches: report.pendingBranches, paradaRastro: report.paradaRastro, unspentFunds: report.unspentFunds, conclusions: report.conclusions, failedBranches: report.failedBranches, queryErrors: report.queryErrors, destinatarios: report.destinatarios, contexto: report.recommendations, methodology: report.methodology, @@ -7981,7 +8126,7 @@ `- Generado: ${new Date(summary.generatedAt*1000).toLocaleString("es-ES")}`, ``, decl ? `## Declaración del afectado (DECLARACION)\n\n${decl.text}\n` : null, `## Cronología`, ``, - ...chronology.map(c => `- [HECHO] ${c.txid.slice(0,16)}… · salto ${c.hop} · ${btcTxt(c.amount)} · ${c.blockTime?new Date(c.blockTime*1000).toLocaleDateString("es-ES"):"sin confirmar"} — banda [INFERENCIA${c.band.certainty?"/"+c.band.certainty:""}] ${c.band.value}, huella [INFERENCIA${c.fingerprint.certainty?"/"+c.fingerprint.certainty:""}] ${c.fingerprint.value}`), + ...chronology.map(c => `- [HECHO] ${c.txid.slice(0,16)}… · salto ${c.hop} · importe de la salida ${btcTxt(c.amount)} · importe seguido ${c.followed != null ? btcTxt(c.followed) : "—"} (proporcional) · ${c.blockTime?new Date(c.blockTime*1000).toLocaleDateString("es-ES"):"sin confirmar"} — banda [INFERENCIA${c.band.certainty?"/"+c.band.certainty:""}] ${c.band.value}, huella [INFERENCIA${c.fingerprint.certainty?"/"+c.fingerprint.certainty:""}] ${c.fingerprint.value}`), ``, `## Direcciones atribuidas al actor`, ``, ...(attributed.length===0 ? ["No se atribuyen direcciones adicionales con fundamento suficiente."] : @@ -7991,6 +8136,14 @@ ...((report.destinatarios||[]).length===0 ? ["Ninguno señalado."] : report.destinatarios.map(d => `- [INFERENCIA/${d.certainty}] ${d.address} — ${d.basis} [tx ${d.txid}]`)), ``, + `## Sin determinar`, ``, + ...((report.sinDeterminar||[]).length===0 ? ["Ninguna."] : + report.sinDeterminar.map(d => `- [HECHO] ${d.address} — ${d.basis} [tx ${d.txid}]`)), + ``, + `## Ramas sin seguir`, ``, + ...((report.pendingBranches||[]).length===0 ? ["Ninguna."] : + report.pendingBranches.map(b => `- [HECHO] ${b.address} — salida ${b.vout+1} (vout ${b.vout}) de la tx ${b.txid}: ${btcTxt(b.amount)}; de lo seguido, ${btcTxt(b.seguido)} (proporcional); ${b.estado}`)), + ``, `## Fondos localizados sin gastar`, ``, ...(unspentFunds.length===0 ? ["Ninguno detectado en las ramas exploradas."] : unspentFunds.map(u => `- [HECHO] ${u.address} — ${btcTxt(u.amount)} (tx ${u.txid.slice(0,16)}…, salida ${u.vout+1} · vout ${u.vout})`)), @@ -8005,8 +8158,8 @@ ...conclusions.map((c,i) => `${i+1}. [${c.level}${c.certainty?"/"+c.certainty:""}] ${c.text}`), ``, `## Movimientos explorados (cronología detallada)`, ``, - `| Fecha | Importe | De | A | Txid |`, `| --- | --- | --- | --- | --- |`, - ...(report.movimientos||[]).map(f => `| ${fechaISO(f.fecha)} | ${btcTxt(f.sats)} | ${f.de.join(", ")||"—"} | ${f.a.length>4?f.a.slice(0,4).join(", ")+` y ${f.a.length-4} más`:f.a.join(", ")||"—"} | ${f.txid} |`), + `| Fecha | Importe de la salida | Importe seguido (proporcional) | De | A | Txid |`, `| --- | --- | --- | --- | --- | --- |`, + ...(report.movimientos||[]).map(f => `| ${fechaISO(f.fecha)} | ${btcTxt(f.sats)} | ${f.seguido!=null?btcTxt(f.seguido):"—"} | ${f.de.join(", ")||"—"} | ${f.a.length>4?f.a.slice(0,4).join(", ")+` y ${f.a.length-4} más`:f.a.join(", ")||"—"} | ${f.txid} |`), ``, `## Mesa de trabajo`, ``, ...((report.mesa||[]).length===0 ? ["Sin transacciones marcadas."] : report.mesa.map(m => `- ${m.txid}${m.nota?` — ${m.nota}`:""}`)), @@ -8146,7 +8299,7 @@ {c.band.value}
- {btcTxt(c.amount)} · {c.blockTime?fmt.date(c.blockTime):"sin confirmar"} · huella: {c.fingerprint.value}{c.fingerprint.certainty?` (${c.fingerprint.certainty})`:""} + salida {btcTxt(c.amount)}{c.followed!=null?` · seguido ${btcTxt(c.followed)} (proporcional)`:""} · {c.blockTime?fmt.date(c.blockTime):"sin confirmar"} · huella: {c.fingerprint.value}{c.fingerprint.certainty?` (${c.fingerprint.certainty})`:""}
{c.entityMarks.length>0&&(
@@ -8204,6 +8357,33 @@
)} + {/* Sin determinar y ramas sin seguir */} + {((report.sinDeterminar||[]).length>0||(report.pendingBranches||[]).length>0)&&( +
+ {(report.pendingBranches||[]).length>0&&(<> +
RAMAS SIN SEGUIR — {report.pendingBranches.length}
+
+ {report.pendingBranches.map((b,i)=>( +
+ {b.address} · salida {b.vout+1} de {b.txid.slice(0,16)}… · {btcTxt(b.amount)} · de lo seguido {btcTxt(b.seguido)} (proporcional) · {b.estado} +
+ ))} +
+ )} + {(report.sinDeterminar||[]).length>0&&(<> +
SIN DETERMINAR — {report.sinDeterminar.length}
+
Salidas no seguidas o donde se dejó de seguir. No se atribuyen al actor.
+
+ {report.sinDeterminar.map((d,i)=>( +
+ {d.address} — {d.basis} · tx {d.txid.slice(0,16)}… +
+ ))} +
+ )} +
+ )} + {/* Fondos sin gastar */}
FONDOS LOCALIZADOS SIN GASTAR — {report.unspentFunds.length}
@@ -9618,7 +9798,7 @@
₿ txoko - · tu nodo, tus reglas · v1.24.6 + · tu nodo, tus reglas · v1.24.7
{showConfig&&{setConfig(cfg);setShowConfig(false);}} onClose={()=>setShowConfig(false)}/>}
diff --git a/tests/README.md b/tests/README.md index 14c8243..0c4e9c8 100644 --- a/tests/README.md +++ b/tests/README.md @@ -21,6 +21,7 @@ node tests/test8.js # regresión de la revisión de heurísticas del 2026-10-1 node tests/test9.js # lógica del rastro de procedencia node tests/test10.js # peritaje a demanda y datos guardados node tests/test11.js # Satoshi→Hal y las pizzas: P2PK, comisión 0, tarifa, peritaje sin dirección, nunca «sin gastar» sin pruebas, historiales largos, Mempool sobre Electrum +node tests/test12.js # informe pericial de un rastro real (Satoshi→Hal, 7 saltos): atribución, CIOH, importes, paradas, mezcla ``` `test7` es de criptografía pero se extrae sola igual que las dos anteriores: no diff --git a/tests/test10.js b/tests/test10.js index 044cabe..280c46e 100644 --- a/tests/test10.js +++ b/tests/test10.js @@ -145,7 +145,7 @@ console.log("\n=== 7. Cronología ===\n"); ok("un movimiento por salto abierto (robo + 3)", f.length === 4, f.length); const csv = P.cronologiaCSV(f); ok("CSV con cabecera y una línea por movimiento", csv.split("\n")[0].startsWith("fecha,importe_sats") && csv.split("\n").length === 5); - ok("MD en tabla", /\| Fecha \| Importe \|/.test(P.cronologiaMD(f, true)) && /EJEMPLO/.test(P.cronologiaMD(f, true))); + ok("MD en tabla", /\| Fecha \| Importe de la salida \| Importe seguido \(proporcional\) \|/.test(P.cronologiaMD(f, true)) && /EJEMPLO/.test(P.cronologiaMD(f, true))); } console.log("\n=== 8. Vigilancia: ¿se ha movido? ===\n"); diff --git a/tests/test12.js b/tests/test12.js new file mode 100644 index 0000000..bc75eed --- /dev/null +++ b/tests/test12.js @@ -0,0 +1,165 @@ +// Informe pericial de un rastro real: Satoshi → Hal, 7 saltos hacia delante +// (v1.24.7) +// +// Reconstruye el rastro que un usuario exportó con la v1.24.6 contra su nodo +// y comprueba el informe que sale de él. Las fixtures llevan los txids, +// direcciones, bloques e importes de ese informe. Donde el informe no daba +// las entradas completas, se deducen de sus importes: c7bc… gasta las DOS +// salidas de 8aab… (0,01 + 0,99 = 1 BTC, que es lo que entra en a1fd…) y +// a1fd… junta 1 BTC del rastro con 0,01 BTC de 1DgzhSK… (sale 1,01 BTC). +// +// Fallos que se comprueban (vistos en la v1.24.6): +// 1. 9 de 11 direcciones atribuidas al actor solo por «huella de wallet +// estable», con huella «sin rasgos distintivos» en todos los saltos; +// incluidas salidas nunca seguidas y la dirección final. +// 2. CIOH: solo agrupa ENTRADAS de una misma tx, nunca salidas. +// 3. Cronología: importe de la salida e importe seguido (proporcional), +// los dos, en pantalla, MD, CSV y JSON. +// 4. Conclusiones: dónde y por qué se detuvo el rastro, ramas sin seguir +// con importes, y la mezcla con dinero de otros como HECHO (sin importe +// robado declarado). +// 5. summary.originAddress vacío para una salida P2PK. +// +// Uso: node tests/test12.js + +const fs = require("fs"); +const path = require("path"); + +const htmlPath = process.env.TXOKO_HTML || path.join(__dirname, "..", "dashboard.html"); +const lines = fs.readFileSync(htmlPath, "utf8").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 dashboard.html`); process.exit(1); } + return lines.slice(s, e).join("\n"); +}; +const preludio = ` + const C = { green:"g", amber:"a", red:"r", t2:"t", blue:"b" }; + const fmt = { num: n => String(n) }; + const ENTITY_INDEX = new Map(); + const OFAC_SET = new Set(); +`; +const src = cut("// ── FORMATO: lógica pura", "// ── fin formato") + + "\n" + cut("const MOCK_TX = {", "// ── Entity Index") + + "\n" + cut("function detectWallets", "function analyzeAddress") + + "\n" + cut("function bandColorRastro", "// ── RASTRO: lógica pura") + + "\n" + cut("// ── RASTRO: lógica pura", "// ── fin lógica pura del rastro") + + "\n" + cut("// ── PERITAJE: lógica pura", "// ── fin lógica pura del peritaje"); +const def = n => `typeof ${n} !== "undefined" ? ${n} : null`; +const P = new Function(preludio + src + ` + return { grafoDesdePeritaje: ${def("grafoDesdePeritaje")}, buildForensicReport: ${def("buildForensicReport")}, + cronologiaPeritaje: ${def("cronologiaPeritaje")}, cronologiaCSV: ${def("cronologiaCSV")}, cronologiaMD: ${def("cronologiaMD")}, + compareFingerprints: ${def("compareFingerprints")}, claveSalida: ${def("claveSalida")} };`)(); + +let pass = 0, fail = 0; +function ok(nombre, f, extra) { + let cond = false, info; + try { cond = !!f(); } catch (e) { info = e.message; } + console.log(` ${cond ? "✓" : "✗"} ${nombre}`); + if (!cond) { const x = info ?? (typeof extra === "function" ? (() => { try { return extra(); } catch (e) { return e.message; } })() : extra); if (x !== undefined) console.log(` ${typeof x === "string" ? x : JSON.stringify(x)}`); } + cond ? pass++ : fail++; +} + +// ── Fixtures (forma Esplora) ───────────────────────────────────────────── +const BTC = 100000000; +const SATOSHI = "0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3"; +const HAL = "04ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84c"; +const p2pk = pub => ({ scriptpubkey: "41" + pub + "ac", scriptpubkey_type: "p2pk" }); +const p2pkh = a => ({ scriptpubkey_address: a, scriptpubkey_type: "p2pkh", scriptpubkey: "76a914" + "00".repeat(20) + "88ac" }); +const D = { + "15kDhR": "15kDhRAcpgsugmh6mQsTcCHdvbsuYncEEV", "1PC45": "1PC45AXE2W9UxyJNbEPU9RiYMNiuZck8Nh", "1NybTk": "1NybTkjpRBUgFfPRKUD4abm2MCWC3LL6Qa", + "18cHSR": "18cHSRrfb7MRD9aS82mshR8mcr19TrbVbC", "1FvShf": "1FvShfQrGmaFnGa8CAUrnZjcrgmY78u7Zv", "1591Ng": "1591NgftHiewU4HaSbFaVeEYgEkXbZ91gZ", + "1DgzhSK": "1DgzhSKcBcmp1CC6Nty2BdSS9dHEpCHVb6", "17zAqc": "17zAqc1xvHdYB3yD7GYbs11boWQGynXgSd", "1Hk6AW": "1Hk6AW8Ps69X895HDyG28ikxM3pWHqtXyN", + "18jKG9": "18jKG9gsSbEbunvHqjEF1k4SWr2HQUzB4c", "1KWSBZ": "1KWSBZAZKKmpujfyxi7UMTFKRaq6xyNvAG", +}; +const T = { + f418: "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16", ea44: "ea44e97271691990157559d0bdd9959e02790c34db6c006d779e82fa5aee708e", + dd11: "dd11322ddb4487a0a7a597838df02fbfd2070870721cd648f3b37f0a164efed9", "8aab": "8aab0beac1b5c76e59e9dc52acd1164a15a2a4694f64d9d028429ddf77202797", + c7bc: "c7bcf51790cd0330cf465a4064f877f8cd45897cbaa0acfd199e0a8ef7d3aa49", a1fd: "a1fd2c246222087971444a9656dd42b7d251821d15fa40b99d04aca196b85be4", + "6898": "68988c51c54f6574bea71a06da2f54ecef9d4bc3e511d85908d32f2e1a56fb2c", "1096": "10966f66302586da5bbce86fa5634ecddcec7b281fc12d54771b690b984f169e", +}; +const IN = (txid, vout, prevout) => ({ txid, vout, prevout, sequence: 4294967295, is_coinbase: false }); +const OUT = (value, spk) => ({ ...spk, value }); +const TX = (txid, vin, vout, h) => ({ txid, version: 1, locktime: 0, size: 258, weight: 1032, fee: 0, vin, vout, status: { confirmed: true, block_height: h, block_time: 1231731025 + (h - 170) * 600 } }); +const txs = {}; +const add = t => { txs[t.txid] = t; return t; }; +add(TX(T.f418, [IN("0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9", 0, OUT(50 * BTC, p2pk(SATOSHI)))], [OUT(10 * BTC, p2pk(HAL)), OUT(40 * BTC, p2pk(SATOSHI))], 170)); +add(TX(T.ea44, [IN(T.f418, 0, OUT(10 * BTC, p2pk(HAL)))], [OUT(10 * BTC, p2pkh(D["15kDhR"]))], 92240)); +add(TX(T.dd11, [IN(T.ea44, 0, OUT(10 * BTC, p2pkh(D["15kDhR"])))], [OUT(1 * BTC, p2pkh(D["1PC45"])), OUT(9 * BTC, p2pkh(D["1NybTk"]))], 92241)); +add(TX(T["8aab"], [IN(T.dd11, 0, OUT(1 * BTC, p2pkh(D["1PC45"])))], [OUT(0.01 * BTC, p2pkh(D["18cHSR"])), OUT(0.99 * BTC, p2pkh(D["1FvShf"]))], 92640)); +add(TX(T.c7bc, [IN(T["8aab"], 0, OUT(0.01 * BTC, p2pkh(D["18cHSR"]))), IN(T["8aab"], 1, OUT(0.99 * BTC, p2pkh(D["1FvShf"])))], [OUT(1 * BTC, p2pkh(D["1591Ng"]))], 93003)); +add(TX(T.a1fd, [IN(T.c7bc, 0, OUT(1 * BTC, p2pkh(D["1591Ng"]))), IN("ab".repeat(32), 0, OUT(0.01 * BTC, p2pkh(D["1DgzhSK"])))], [OUT(1.01 * BTC, p2pkh(D["17zAqc"]))], 93023)); +add(TX(T["6898"], [IN(T.a1fd, 0, OUT(1.01 * BTC, p2pkh(D["17zAqc"])))], [OUT(0.1 * BTC, p2pkh(D["1Hk6AW"])), OUT(0.91 * BTC, p2pkh(D["18jKG9"]))], 93261)); +add(TX(T["1096"], [IN(T["6898"], 0, OUT(0.1 * BTC, p2pkh(D["1Hk6AW"])))], [OUT(0.1 * BTC, p2pkh(D["1KWSBZ"]))], 93347)); + +// El peritaje tal como lo recorrió el usuario: siguió una salida en cada salto. +function peritaje(conjunto) { + const per = { origen: { txid: T.f418, vout: 0 }, txs: new Map(), gastos: new Map(), abiertas: new Set(), robado: null, maxSaltos: 12, consultas: 0 }; + for (const t of Object.values(conjunto)) { per.txs.set(t.txid, t); per.abiertas.add(t.txid); } + const g = (a, i, b) => per.gastos.set(`${a}:${i}`, { estado: "gastada", spendTxid: b, comprobado: 1 }); + g(T.f418, 0, T.ea44); g(T.ea44, 0, T.dd11); g(T.dd11, 0, T["8aab"]); g(T["8aab"], 0, T.c7bc); + g(T.c7bc, 0, T.a1fd); g(T.a1fd, 0, T["6898"]); g(T["6898"], 0, T["1096"]); + return per; +} +const per = peritaje(txs); +const grafo = P.grafoDesdePeritaje(per); +const rep = P.buildForensicReport(grafo, null); +const atrib = new Map(rep.attributed.map(a => [a.address, a])); +const soloHuella = a => a.fundamentos.every(f => f.apoyo || /huella/.test(f.basis)); + +console.log("\n=== 1. Atribución ===\n"); +ok("«sin rasgos distintivos» en los dos saltos no es «la misma huella»", () => P.compareFingerprints([{ name: "sin rasgos distintivos" }], [{ name: "sin rasgos distintivos" }]).changed === null); +ok("ninguna dirección se atribuye solo por la huella", () => rep.attributed.every(a => !soloHuella(a)), () => rep.attributed.filter(soloHuella).map(a => a.address)); +for (const k of ["1NybTk", "18jKG9"]) { + ok(`la salida no seguida ${k}… no es del actor por defecto`, () => { const a = atrib.get(D[k]); return !a || a.fundamentos.some(f => /cambio detectado/.test(f.basis)); }, () => atrib.get(D[k])); +} +ok("la dirección final 1KWSBZ… queda «rama abierta / sin determinar»", () => !atrib.has(D["1KWSBZ"]) && rep.sinDeterminar.some(x => x.address === D["1KWSBZ"] && x.ramaAbierta), () => [atrib.get(D["1KWSBZ"]), rep.sinDeterminar]); +ok("las no seguidas salen en «sin determinar» (o en destinatarios)", () => ["1NybTk", "18jKG9"].every(k => atrib.has(D[k]) || rep.sinDeterminar.some(x => x.address === D[k]) || rep.destinatarios.some(x => x.address === D[k]))); +ok("el camino seguido sí se atribuye (recibió lo seguido y lo movió)", () => ["15kDhR", "1PC45", "18cHSR", "1591Ng", "17zAqc"].every(k => atrib.get(D[k])?.fundamentos.some(f => /lo volvió a mover/.test(f.basis))), () => ["15kDhR", "1PC45", "18cHSR", "1591Ng", "17zAqc"].filter(k => !atrib.has(D[k]))); + +console.log("\n=== 2. CIOH: solo entradas de una misma tx ===\n"); +ok("co-entradas de a1fd… → mismo grupo {1591Ng, 1DgzhSK}", () => grafo.clusters.some(c => c.includes(D["1591Ng"]) && c.includes(D["1DgzhSK"])), grafo.clusters); +ok("c7bc… gasta las dos salidas de 8aab… → {18cHSR, 1FvShf} por CIOH (son co-entradas)", () => grafo.clusters.some(c => c.includes(D["18cHSR"]) && c.includes(D["1FvShf"]))); +ok("…y se explica que las salidas de 8aab… se vuelven a juntar", () => rep.conclusions.some(c => c.level === "HECHO" && /se vuelven a juntar/.test(c.text) && c.text.includes(D["1FvShf"]))); +{ + // Variante: c7bc gasta solo 18cHSR. Las dos salidas de 8aab no se agrupan. + const solo = { ...txs, [T.c7bc]: TX(T.c7bc, [IN(T["8aab"], 0, OUT(0.01 * BTC, p2pkh(D["18cHSR"])))], [OUT(0.01 * BTC, p2pkh(D["1591Ng"]))], 93003) }; + solo[T.a1fd] = TX(T.a1fd, [IN(T.c7bc, 0, OUT(0.01 * BTC, p2pkh(D["1591Ng"]))), IN("ab".repeat(32), 0, OUT(1 * BTC, p2pkh(D["1DgzhSK"])))], [OUT(1.01 * BTC, p2pkh(D["17zAqc"]))], 93023); + const g2 = P.grafoDesdePeritaje(peritaje(solo)); + const r2 = P.buildForensicReport(g2, null); + ok("dos SALIDAS de la misma tx nunca forman grupo CIOH", () => !g2.clusters.some(c => c.includes(D["18cHSR"]) && c.includes(D["1FvShf"])), g2.clusters); + ok("…y la no seguida (1FvShf) no es del actor", () => !r2.attributed.some(a => a.address === D["1FvShf"]) || r2.attributed.find(a => a.address === D["1FvShf"]).fundamentos.some(f => /cambio detectado/.test(f.basis))); + const m5 = r2.conclusions.find(c => c.level === "HECHO" && /salto 5/.test(c.text) && /se juntó con/.test(c.text)); + ok("mezcla HECHO en el salto 5 sin importe robado: 0,01 seguido con 1 BTC de 1DgzhSK… (≈1 %)", () => m5 && m5.text.includes(D["1DgzhSK"]) && /1,00000000 BTC de otra dirección/.test(m5.text) && /el 1 % de lo que entra/.test(m5.text), () => m5?.text); + const f2 = P.cronologiaPeritaje(peritaje(solo)); + const fa1 = f2.find(f => f.txid === T.a1fd); + ok("cronología del salto 5: importe de la salida 0,01 y seguido 0,01", () => fa1.sats === 0.01 * BTC && fa1.seguido === 0.01 * BTC, fa1); +} + +console.log("\n=== 3. Cronología: los dos importes ===\n"); +const c5 = rep.chronology.find(c => c.txid === T.a1fd), c4 = rep.chronology.find(c => c.txid === T.c7bc); +ok("cada fila del informe lleva importe de la salida y seguido", () => rep.chronology.every(c => Number.isFinite(c.amount) && Number.isFinite(c.followed)), () => rep.chronology.map(c => [c.amount, c.followed])); +ok("salto 4: salida de 0,01 BTC; seguido 1 BTC (las dos salidas de 8aab… se juntan)", () => c4.amount === 0.01 * BTC && c4.followed === 1 * BTC, c4); +ok("salto 5: salida de 1 BTC; seguido 1 BTC de 1,01 que entran", () => c5.amount === 1 * BTC && c5.followed === 1 * BTC, c5); +const filas = P.cronologiaPeritaje(per); +const csv = P.cronologiaCSV(filas), md = P.cronologiaMD(filas, false); +ok("CSV con seguido_sats y via", () => /seguido_sats,seguido_btc,via$/.test(csv.split("\n")[0]) && csv.split("\n").length === filas.length + 1); +ok("MD con las dos columnas", () => /Importe de la salida \| Importe seguido \(proporcional\)/.test(md)); +ok("«De» lista todas las entradas de la tx (c7bc…: 18cHSR y 1FvShf)", () => { const f = filas.find(x => x.txid === T.c7bc); return f.de.includes(D["18cHSR"]) && f.de.includes(D["1FvShf"]) && f.via === D["18cHSR"]; }); + +console.log("\n=== 4. Conclusiones que faltaban ===\n"); +ok("parada en el salto 7: la decidió el usuario, sin final natural", () => rep.paradaRastro.some(p => p.txid === T["1096"] && p.motivo === "usuario" && p.hop === 7) && rep.conclusions.some(c => /salto 7/.test(c.text) && /se dejó de seguir/.test(c.text) && /sin explorar/.test(c.text)), rep.paradaRastro); +ok("ramas sin seguir con importes: 1NybTk… (9 BTC), 18jKG9… (0,91), 1KWSBZ… (0,1)", () => { + const b = new Map(rep.pendingBranches.map(x => [x.address, x])); + return b.get(D["1NybTk"])?.amount === 9 * BTC && b.get(D["18jKG9"])?.amount === 0.91 * BTC && b.get(D["1KWSBZ"])?.amount === 0.1 * BTC && !b.has(D["1FvShf"]); +}, () => rep.pendingBranches.map(x => [x.address, x.amount, x.seguido])); +ok("…y su parte de lo seguido (proporcional): 1NybTk… 9 BTC", () => rep.pendingBranches.find(x => x.address === D["1NybTk"]).seguido === 9 * BTC); +ok("conclusión HECHO con las ramas sin seguir", () => rep.conclusions.some(c => c.level === "HECHO" && /Quedan 3 rama\(s\) sin seguir/.test(c.text))); +const m5 = rep.conclusions.find(c => c.level === "HECHO" && /salto 5/.test(c.text) && /se juntó con/.test(c.text)); +ok("salto 5: mezcla con 0,01 BTC de 1DgzhSK… como HECHO, sin importe robado declarado", () => rep.summary.amountStolen == null && m5 && m5.text.includes(D["1DgzhSK"]) && /0,01000000 BTC de otra dirección/.test(m5.text) && /1,01000000 BTC en total/.test(m5.text), () => m5?.text); + +console.log("\n=== 5. Origen P2PK ===\n"); +ok("summary.originAddress nombra la clave pública", () => /clave pública \(P2PK/.test(rep.summary.originAddress), rep.summary.originAddress); + +console.log(`\n${pass} correctos, ${fail} fallos`); +process.exit(fail === 0 ? 0 : 1);