Files
txoko-dashboard/src/51-pestana-peritaje.jsx
T

459 lines
36 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ── PERITAJE ─────────────────────────────────────────────────────────
function PeritajeForense({base}) {
const {get, getStrict} = useApi(base);
const [txidInput, setTxidInput] = useState("");
const [voutInput, setVoutInput] = useState("0");
const [amountInput, setAmountInput] = useState("");
const [declaracion, setDeclaracion] = useState("");
const [maxHops, setMaxHops] = useState(8);
const [busy, setBusy] = useState(false); // consultando el origen
const [error, setError] = useState(null);
const [report, setReport] = useState(null);
const [, setTick] = useState(0);
const [abierto, setAbierto] = useState(false);
const demo = !base;
// El peritaje vive en un ref para la sesión: cerrar y reabrir el espacio
// de trabajo, o volver atrás, no repite ninguna consulta.
const perRef = useRef(null);
const per = perRef.current;
const iniciar = async () => {
setError(null); setReport(null);
const amountStolen = amountInput.trim() ? Math.round(parseFloat(amountInput)*1e8) : null;
if (demo) {
const D = DEMO_PERITAJE;
perRef.current = { origen:{...D.origen}, txs:new Map([[D.origen.txid, D.txs[D.origen.txid]]]), gastos:new Map(), abiertas:new Set([D.origen.txid]),
robado: amountStolen || 50000000, maxSaltos: D.maxSaltos, consultas: 0, _demoGastos: {...D.gastos} };
setTick(t=>t+1); setAbierto(true); return;
}
const txid = txidInput.trim();
if (!/^[0-9a-f]{64}$/i.test(txid)) { setError("Introduce un txid de origen válido (64 caracteres hex)."); return; }
const vout = parseInt(voutInput, 10);
if (!Number.isInteger(vout) || vout < 0) { setError("El número de salida debe ser un entero de 0 en adelante."); return; }
setBusy(true);
try {
let tx;
try { tx = await getStrict(`/api/tx/${txid}`); }
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 (!tx) throw new Error("No se pudo obtener la transacción de origen. Comprueba el txid.");
if (!tx.vout?.[vout]) throw new Error("Esa salida no existe en la transacción de origen.");
perRef.current = { origen:{txid, vout}, txs:new Map([[txid, tx]]), gastos:new Map(), abiertas:new Set([txid]),
robado: amountStolen, maxSaltos: maxHops, consultas: 1 };
setTick(t=>t+1); setAbierto(true);
} catch(e) { setError(e.message); }
setBusy(false);
};
const limpiar = () => { perRef.current = null; setReport(null); setError(null); setAbierto(false); setTick(t=>t+1); };
const generarInforme = (mesa, vigilancia) => {
if (!per) return;
const g = grafoDesdePeritaje(per);
const r = buildForensicReport(g, declaracion);
const m = mesa || ALMACEN.get("peritaje-mesa", {}), v = vigilancia || ALMACEN.get("peritaje-vigilancia", {});
r.mesa = Object.entries(m).filter(([,x])=>x.origen===per.origen.txid).map(([txid,x])=>({ txid, nota:x.nota||"" }));
r.vigiladas = Object.values(v).filter(x=>x.origen===per.origen.txid).map(x=>({ clave:x.clave, address:x.address, sats:x.sats, ultima:x.checks?.[x.checks.length-1]||null }));
r.movimientos = cronologiaPeritaje(per);
r.dondeAcabo = dondeAcabo(per);
r.generadoCon = per.abiertas.size;
r.ejemplo = demo;
setReport(r); setAbierto(false);
setTimeout(()=>{ try { const el=document.getElementById("informe-peritaje"); if(el) window.scrollTo({top: el.getBoundingClientRect().top + window.scrollY - 70}); } catch {} }, 50);
};
const exportJSON = () => {
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,
verificationAppendix: report.verificationAppendix,
movimientos: report.movimientos, mesa: report.mesa, vigiladas: report.vigiladas,
dondeAcabo: report.dondeAcabo, ejemplo: !!report.ejemplo,
};
const blob = new Blob([JSON.stringify(exportData,null,2)], {type:"application/json"});
const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "peritaje-forense.json"; a.click();
};
const exportMD = () => {
const { summary, declaracion:decl, chronology, attributed, unspentFunds, failedBranches, conclusions, recommendations, methodology, verificationAppendix } = report;
const lines = [
`# Peritaje forense — Txoko${report.ejemplo?" (EJEMPLO)":""}`, ``,
`## Resumen`, ``,
`- Origen: ${summary.originTxid}, salida ${summary.originVout+1} (vout ${summary.originVout})`,
`- Dirección de origen: ${summary.originAddress}`,
`- Importe rastreado: ${btcTxt(summary.amountTraced)}`,
summary.amountStolen ? `- Importe declarado como robado: ${btcTxt(summary.amountStolen)}` : null,
`- Saltos: ${summary.hops} · Transacciones: ${summary.txCount} · Direcciones tocadas: ${summary.addressesTouched}`,
`- 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} · 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."] :
attributed.map(a => `- [INFERENCIA] ${a.address} — ${a.fundamentos.map(f=>`${f.basis} (${f.certainty})${f.refTxid?` [tx ${f.refTxid}]`:""}`).join("; ")}`)),
``,
`## Destinatarios (posible tercero)`, ``,
...((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})`)),
``,
...((failedBranches && failedBranches.length>0) ? [
`## Ramas NO comprobadas (fallo de consulta)`, ``,
`Estas ramas no pudieron consultarse. **No** son fondos sin gastar: simplemente no se sabe qué pasó con ellas. El alcance del informe es incompleto hasta que se repita el rastreo sobre ellas.`, ``,
...failedBranches.map(f => `- [HECHO] ${f.address} — consulta fallida en tx ${f.txid.slice(0,16)}…, salida ${f.vout+1} · vout ${f.vout} (${btcTxt(f.amount)} en juego)`),
``,
] : []),
`## Conclusiones`, ``,
...conclusions.map((c,i) => `${i+1}. [${c.level}${c.certainty?"/"+c.certainty:""}] ${c.text}`),
``,
`## Movimientos explorados (cronología detallada)`, ``,
`| 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}`:""}`)),
...((report.vigiladas||[]).length ? [``, `**Salidas vigiladas:**`, ...report.vigiladas.map(v => `- ${v.clave.split(":")[0]}, salida ${Number(v.clave.split(":")[1])+1} (vout ${v.clave.split(":")[1]}) · ${v.address} · ${btcTxt(v.sats)} · última comprobación ${v.ultima?fechaISO(v.ultima.fecha)+" ("+(v.ultima.estado==="gastada"?"gastada":v.ultima.estado==="no_localizada"?"gastada, sin localizar":v.ultima.estado==="error"?"falló":"sin gastar")+")":"—"}`)] : []),
``,
`## Contexto`, ``,
...recommendations.map(r => `- ${r.text}`),
``,
`## Metodología`, ``,
`**Niveles de certeza:** ${methodology.levels}`, ``,
`**Heurísticas usadas:** ${methodology.heuristics}`, ``,
`**Límites:** ${methodology.limits}`, ``,
`## Anexo de verificación`, ``,
`**Txids:**`, ...verificationAppendix.txids.map(t=>`- ${t}`), ``,
`**Direcciones:**`, ...verificationAppendix.addresses.map(a=>`- ${a}`),
].filter(l => l !== null);
const blob = new Blob([lines.join("\n")], {type:"text/markdown"});
const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "peritaje-forense.md"; a.click();
};
return (
<div style={{display:"flex",flexDirection:"column",gap:12}}>
{!base&&<DemoBanner/>}
<SectionTitle accent={C.red} icon="🔍">PERITAJE FORENSE</SectionTitle>
<Card>
<div style={{fontSize:"0.7rem",color:C.t2,marginBottom:10,lineHeight:1.6}}>
Sigue hacia adelante unas monedas robadas o perdidas, desde la transacción del robo, en un espacio de trabajo propio. <strong style={{color:C.t1}}>Nada se explora solo:</strong> antes de cada comprobación ves cuántas consultas a tu nodo puede costar, y lo ya traído no se vuelve a pedir. Todo sobre tu propio nodo: nada sale de tu red.
</div>
{!per ? (
<div style={{display:"flex",flexDirection:"column",gap:8}}>
{/* En demo los campos no se usan: antes parecía que no había dónde pegar el txid. */}
{demo&&<div style={{padding:"9px 12px",background:C.amberMuted,border:`1px solid ${C.amber}55`,borderRadius:6,color:C.t1,fontSize:"0.7rem",lineHeight:1.55}}>
<strong style={{color:C.amber}}>Sin nodo no se puede peritar una transacción real.</strong> El botón de abajo abre un robo de ejemplo para que veas cómo funciona. Con tu nodo configurado, aquí pegarás el txid de la transacción del robo.
</div>}
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4}}>Transacción del robo · salida robada (vout: la primera es 0) · tope de saltos</div>
<div style={{display:"flex",gap:8,flexWrap:"wrap",opacity:demo?0.45:1}}>
<input value={txidInput} onChange={e=>setTxidInput(e.target.value)} placeholder={demo?"(no se usa en el ejemplo)":"txid del robo (64 caracteres hex)"} disabled={demo}
style={{flex:"3 1 220px",minWidth:0,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none"}}/>
<input value={voutInput} onChange={e=>setVoutInput(e.target.value)} type="number" min="0" disabled={demo} placeholder="vout (0 = salida 1)" title="Número de la salida robada dentro de esa transacción (la primera es 0)"
style={{flex:"1 1 70px",minWidth:0,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none"}}/>
<select value={maxHops} onChange={e=>setMaxHops(Number(e.target.value))} disabled={demo} title="Tope de saltos: una red de seguridad para proteger el nodo"
style={{flex:"1 1 120px",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 8px",color:C.t1,fontFamily:C.mono,fontSize:"0.7rem",outline:"none",cursor:"pointer"}}>
<option value={8}>hasta 8 saltos</option><option value={15}>hasta 15 saltos</option><option value={25}>hasta 25 saltos</option>
</select>
</div>
<div style={{fontSize:"0.62rem",color:C.t2,lineHeight:1.5,opacity:demo?0.45:1}}>Tope de saltos: hasta dónde puede llegar el peritaje como mucho, para proteger tu nodo. Cada salto se abre igualmente a mano.</div>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4,marginTop:4}}>Importe robado en BTC <span style={{textTransform:"none"}}>(opcional: sirve para saber qué parte de lo robado sigue en cada mezcla)</span></div>
<input value={amountInput} onChange={e=>setAmountInput(e.target.value)} type="number" step="0.00000001" min="0"
placeholder="0,00000000"
style={{background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none",minWidth:0}}/>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4,marginTop:4}}>Declaración del afectado <span style={{textTransform:"none"}}>(opcional)</span></div>
<textarea value={declaracion} onChange={e=>setDeclaracion(e.target.value)} rows={3}
placeholder="Qué pasó, cuándo se notó, cómo pudo ocurrir. En el informe va aparte, como DECLARACIÓN, y nunca se mezcla con los hechos."
style={{background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.68rem",outline:"none",resize:"vertical",minWidth:0}}/>
<button onClick={iniciar} disabled={busy} style={{alignSelf:"flex-start",padding:"9px 18px",background:C.redMuted,border:`1px solid ${C.red}50`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>
{busy?"consultando…":demo?"Abrir el peritaje de ejemplo ›":"Abrir el peritaje (1 consulta) ›"}
</button>
</div>
) : (
<div style={{display:"flex",flexDirection:"column",gap:8}}>
<div style={{fontSize:"0.7rem",color:C.t1,lineHeight:1.6}}>
Peritaje en curso{demo?" (EJEMPLO)":""}: <span style={{fontFamily:C.mono}}>{abrevTxid(per.origen.txid)}</span>, salida {per.origen.vout+1} (vout {per.origen.vout}) · {per.abiertas.size-1} salto(s) abiertos · {per.consultas} consulta(s) a tu nodo.
</div>
<textarea value={declaracion} onChange={e=>setDeclaracion(e.target.value)} rows={2}
placeholder="Declaración del afectado (opcional). En el informe va aparte, etiquetada como DECLARACIÓN."
style={{background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.68rem",outline:"none",resize:"vertical",minWidth:0}}/>
<div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
<button onClick={()=>setAbierto(true)} style={{padding:"8px 16px",background:C.redMuted,border:`1px solid ${C.red}50`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer",fontWeight:700}}>Abrir el espacio de trabajo ›</button>
<button onClick={()=>generarInforme()} disabled={per.abiertas.size<2} style={{padding:"8px 16px",background:C.purpleMuted,border:`1px solid ${C.purple}50`,borderRadius:6,color:C.purple,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer",fontWeight:700,opacity:per.abiertas.size<2?0.45:1}}>Generar informe pericial</button>
<button onClick={limpiar} style={{padding:"8px 14px",background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.t2,fontFamily:C.mono,fontSize:"0.68rem",cursor:"pointer"}}>Nuevo peritaje</button>
</div>
{per.abiertas.size<2&&<div style={{fontSize:"0.62rem",color:C.t2}}>El informe se activa en cuanto haya al menos un salto abierto.</div>}
</div>
)}
{error&&<div style={{marginTop:8,padding:"8px 12px",background:C.redMuted,border:`1px solid ${C.red}30`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.7rem"}}>{error}</div>}
</Card>
{abierto&&per&&<PeritajeTrabajo per={per} base={base} getStrict={getStrict} demo={demo} onCerrar={()=>{setAbierto(false);setTick(t=>t+1);}} onInforme={generarInforme}/>}
{report&&(
<Card glow={C.red} innerRef={el=>{ if(el) el.id="informe-peritaje"; }}>
<div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14,flexWrap:"wrap",gap:8}}>
<div style={{display:"flex",alignItems:"center",gap:8}}><span style={{fontSize:"0.65rem",color:C.red,fontFamily:C.mono,fontWeight:700}}>INFORME DE PERITAJE</span>{report.ejemplo&&<Badge color={C.amber}>EJEMPLO</Badge>}</div>
<div style={{display:"flex",gap:6}}>
<button onClick={exportJSON} style={{padding:"3px 10px",background:"none",border:`1px solid ${C.border}`,borderRadius:4,color:C.t2,fontFamily:C.mono,fontSize:"0.6rem",cursor:"pointer"}}>↓ JSON</button>
<button onClick={exportMD} style={{padding:"3px 10px",background:"none",border:`1px solid ${C.border}`,borderRadius:4,color:C.t2,fontFamily:C.mono,fontSize:"0.6rem",cursor:"pointer"}}>↓ MD</button>
</div>
</div>
{/* El análisis no sale de la red del usuario, pero el archivo
exportado sí puede salir — y lleva sus direcciones dentro.
Avisar aquí, junto a los botones, no en la letra pequeña. */}
<div style={{marginBottom:14,padding:"8px 12px",background:C.amberMuted,border:`1px solid ${C.amber}30`,borderRadius:6,fontSize:"0.62rem",color:C.amber,fontFamily:C.mono,lineHeight:1.6}}>
Lo que descargues lleva dentro tus direcciones y tu declaración. Nada de esto ha salido de tu red hasta ahora; a partir de aquí depende de ti. No lo subas a foros, chats de soporte ni servicios en la nube para pedir ayuda.
</div>
{per&&report.generadoCon!==per.abiertas.size&&(
<div style={{marginBottom:14,padding:"8px 12px",background:C.amberMuted,border:`1px solid ${C.amber}30`,borderRadius:6,fontSize:"0.62rem",color:C.amber,fontFamily:C.mono}}>
Desde este informe se han abierto más saltos: no los incluye hasta que se genere de nuevo.
</div>
)}
{/* Resumen */}
<div style={{display:"flex",gap:16,flexWrap:"wrap",padding:"12px 14px",background:C.bgCard,borderRadius:8,marginBottom:14,border:`1px solid ${C.border}`}}>
{[
{label:"Rastreado", v: fmt.sbtc(report.summary.amountTraced)},
{label:"Saltos", v: report.summary.hops},
{label:"Transacciones", v: report.summary.txCount},
{label:"Direcciones tocadas", v: report.summary.addressesTouched},
].map(({label,v})=>(
<div key={label}>
<div style={{fontSize:"0.55rem",color:C.t2,fontFamily:C.mono}}>{label}</div>
<div style={{fontSize:"0.8rem",fontFamily:C.mono,fontWeight:700,color:C.t1}}>{v}</div>
</div>
))}
</div>
{/* Declaración */}
{report.declaracion&&(
<div style={{marginBottom:14,padding:"10px 12px",background:C.blueMuted,border:`1px solid ${C.blue}40`,borderRadius:6}}>
<div style={{fontSize:"0.58rem",color:C.blue,fontFamily:C.mono,fontWeight:700,marginBottom:6,letterSpacing:"0.1em"}}>DECLARACIÓN DEL AFECTADO</div>
<div style={{fontSize:"0.68rem",color:C.t1,lineHeight:1.6,whiteSpace:"pre-wrap"}}>{report.declaracion.text}</div>
</div>
)}
{/* Cronología */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>CRONOLOGÍA — {report.chronology.length} TRANSACCIONES</div>
<div style={{display:"flex",flexDirection:"column",gap:4,maxHeight:320,overflowY:"auto"}}>
{report.chronology.map((c,i)=>{
const bColor = bandColorRastro(c.band.value);
return (
<div key={i} style={{padding:"7px 10px",background:C.bgCard,borderRadius:5,border:`1px solid ${C.border}`}}>
<div style={{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"}}>
<span style={{fontSize:"0.56rem",color:C.t2,fontFamily:C.mono,minWidth:50}}>salto {c.hop}</span>
<span style={{fontSize:"0.6rem",color:C.t1,fontFamily:C.mono,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{c.txid.slice(0,20)}…</span>
<span style={{fontSize:"0.58rem",color:bColor,fontFamily:C.mono,fontWeight:600}}>{c.band.value}</span>
</div>
<div style={{fontSize:"0.56rem",color:C.t2,fontFamily:C.mono,marginTop:3}}>
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})`:""}
</div>
{c.entityMarks.length>0&&(
<div style={{display:"flex",gap:6,flexWrap:"wrap",marginTop:4}}>
{c.entityMarks.map((m,j)=>(<span key={j} style={{fontSize:"0.55rem",fontFamily:C.mono,fontWeight:700,color:m.color,background:`${m.color}1a`,border:`1px solid ${m.color}55`,borderRadius:4,padding:"1px 6px"}}>{m.txt}</span>))}
</div>
)}
</div>
);
})}
</div>
</div>
{/* Direcciones atribuidas */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.amber,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>DIRECCIONES ATRIBUIDAS AL ACTOR — {report.attributed.length}</div>
{report.attributed.length===0?(
<div style={{fontSize:"0.65rem",color:C.t2,fontFamily:C.mono}}>No se atribuyen direcciones adicionales con fundamento suficiente.</div>
):(
<div style={{display:"flex",flexDirection:"column",gap:6}}>
{report.attributed.map((a,i)=>(
<div key={i} style={{padding:"8px 10px",background:C.bgCard,border:`1px solid ${C.amber}30`,borderRadius:6}}>
<div style={{display:"flex",alignItems:"center",gap:8,marginBottom:4,flexWrap:"wrap"}}>
<span style={{fontSize:"0.6rem",color:C.t1,fontFamily:C.mono,wordBreak:"break-all"}}>{a.address}</span>
<VerEnMempool base={base} tipo="direccion" id={a.address} texto="↗"/>
</div>
<div style={{display:"flex",flexDirection:"column",gap:2}}>
{a.fundamentos.map((f,j)=>(
<div key={j} style={{fontSize:"0.56rem",color:C.t2,fontFamily:C.mono}}>
<span style={{color:C.amber}}>[{f.certainty}]</span> {f.basis}{f.refTxid?` — tx ${f.refTxid.slice(0,16)}…`:""}
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
{/* Destinatarios: probables pagos a terceros, fuera de la atribución */}
{(report.destinatarios||[]).length>0&&(
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.purple,fontFamily:C.mono,fontWeight:700,marginBottom:4,letterSpacing:"0.15em"}}>DESTINATARIOS (POSIBLE TERCERO) — {report.destinatarios.length}</div>
<div style={{fontSize:"0.62rem",color:C.t2,marginBottom:8,lineHeight:1.5}}>Salidas que parecen pagos a otra persona. No se atribuyen al actor.</div>
<div style={{display:"flex",flexDirection:"column",gap:6}}>
{report.destinatarios.map((d,i)=>(
<div key={i} style={{padding:"8px 10px",background:C.bgCard,border:`1px solid ${C.purple}30`,borderRadius:6}}>
<div style={{display:"flex",alignItems:"center",gap:8,marginBottom:4,flexWrap:"wrap"}}>
<span style={{fontSize:"0.6rem",color:C.t1,fontFamily:C.mono,wordBreak:"break-all"}}>{d.address}</span>
<CertaintyBadge level={d.certainty}/>
</div>
<div style={{fontSize:"0.58rem",color:C.t2,fontFamily:C.mono}}>{d.basis} — tx {d.txid.slice(0,16)}…</div>
</div>
))}
</div>
</div>
)}
{/* Sin determinar y ramas sin seguir */}
{((report.sinDeterminar||[]).length>0||(report.pendingBranches||[]).length>0)&&(
<div style={{marginBottom:14}}>
{(report.pendingBranches||[]).length>0&&(<>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:4,letterSpacing:"0.15em"}}>RAMAS SIN SEGUIR — {report.pendingBranches.length}</div>
<div style={{display:"flex",flexDirection:"column",gap:4,marginBottom:10}}>
{report.pendingBranches.map((b,i)=>(
<div key={i} style={{padding:"7px 10px",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:6,fontSize:"0.58rem",color:C.t2,fontFamily:C.mono,lineHeight:1.5,wordBreak:"break-all"}}>
<span style={{color:C.t1}}>{b.address}</span> · salida {b.vout+1} de {b.txid.slice(0,16)}… · {btcTxt(b.amount)} · de lo seguido {btcTxt(b.seguido)} (proporcional) · {b.estado}
</div>
))}
</div>
</>)}
{(report.sinDeterminar||[]).length>0&&(<>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:4,letterSpacing:"0.15em"}}>SIN DETERMINAR — {report.sinDeterminar.length}</div>
<div style={{fontSize:"0.62rem",color:C.t2,marginBottom:6,lineHeight:1.5}}>Salidas no seguidas o donde se dejó de seguir. No se atribuyen al actor.</div>
<div style={{display:"flex",flexDirection:"column",gap:4}}>
{report.sinDeterminar.map((d,i)=>(
<div key={i} style={{padding:"7px 10px",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:6,fontSize:"0.58rem",color:C.t2,fontFamily:C.mono,lineHeight:1.5,wordBreak:"break-all"}}>
<span style={{color:C.t1}}>{d.address}</span> — {d.basis} · tx {d.txid.slice(0,16)}…
</div>
))}
</div>
</>)}
</div>
)}
{/* Fondos sin gastar */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.green,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>FONDOS LOCALIZADOS SIN GASTAR — {report.unspentFunds.length}</div>
{report.unspentFunds.length===0?(
<div style={{fontSize:"0.65rem",color:C.t2,fontFamily:C.mono}}>Ninguno detectado en las ramas exploradas.</div>
):(
<div style={{display:"flex",flexDirection:"column",gap:4}}>
{report.unspentFunds.map((u,i)=>(
<div key={i} style={{padding:"7px 10px",background:C.greenMuted,border:`1px solid ${C.green}30`,borderRadius:6}}>
<div style={{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"}}>
<span style={{fontSize:"0.6rem",color:C.t1,fontFamily:C.mono,wordBreak:"break-all"}}>{u.address}</span>
<VerEnMempool base={base} tipo="direccion" id={u.address} texto="↗"/>
</div>
<div style={{fontSize:"0.58rem",color:C.green,fontFamily:C.mono,fontWeight:700}}>{btcTxt(u.amount)} · tx {u.txid.slice(0,12)}…, salida {u.vout+1} (vout {u.vout})</div>
</div>
))}
</div>
)}
</div>
{report.failedBranches&&report.failedBranches.length>0&&(
<div style={{marginBottom:14,padding:"10px 12px",background:C.redMuted,border:`1px solid ${C.red}40`,borderRadius:6}}>
<div style={{fontSize:"0.62rem",color:C.red,fontFamily:C.mono,fontWeight:700,marginBottom:6,letterSpacing:"0.1em"}}>
RAMAS NO COMPROBADAS — {report.failedBranches.length}
</div>
<div style={{fontSize:"0.63rem",color:C.t1,fontFamily:C.mono,lineHeight:1.6,marginBottom:8}}>
La consulta al nodo falló en estas ramas. <strong>No son fondos sin gastar</strong> — no se sabe qué pasó con ellas. El alcance de este informe es incompleto hasta repetir el rastreo sobre ellas.
</div>
<div style={{display:"flex",flexDirection:"column",gap:4}}>
{report.failedBranches.map((f,i)=>(
<div key={i} style={{fontSize:"0.58rem",color:C.t2,fontFamily:C.mono,wordBreak:"break-all"}}>
{f.address} · {btcTxt(f.amount)} · tx {f.txid.slice(0,16)}…, salida {f.vout+1} (vout {f.vout})
</div>
))}
</div>
</div>
)}
{report.truncatedBranches.length>0&&(
<div style={{marginBottom:14,padding:"10px 12px",background:C.amberMuted,border:`1px solid ${C.amber}30`,borderRadius:6}}>
<div style={{fontSize:"0.65rem",color:C.amber,fontFamily:C.mono}}>
{report.truncatedBranches.length} rama(s) cortada(s) por el tope de saltos ({maxHops}) — no es un punto de parada natural. Ese tope solo es una red de seguridad aparte del control manual; para explorarlas, sube el tope arriba y pulsa "Limpiar" para repetir el rastreo desde el principio con el tope nuevo (una rama ya cortada no se puede reanudar por separado).
</div>
</div>
)}
{/* Conclusiones */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>CONCLUSIONES</div>
<div style={{display:"flex",flexDirection:"column",gap:6}}>
{report.conclusions.map((c,i)=>(
<div key={i} style={{display:"flex",gap:8,fontSize:"0.66rem",color:C.t1,lineHeight:1.6}}>
<span style={{fontFamily:C.mono,color:C.t2,flexShrink:0}}>{i+1}.</span>
<span>
<span style={{fontFamily:C.mono,fontSize:"0.56rem",fontWeight:700,color:c.level==="HECHO"?C.green:c.level==="DECLARACION"?C.blue:C.amber,border:`1px solid ${c.level==="HECHO"?C.green:c.level==="DECLARACION"?C.blue:C.amber}40`,borderRadius:3,padding:"1px 5px",marginRight:6}}>
{c.level}{c.certainty?`/${c.certainty}`:""}
</span>
{c.text}
</span>
</div>
))}
</div>
</div>
{/* Recomendaciones */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>CONTEXTO</div>
<div style={{display:"flex",flexDirection:"column",gap:8}}>
{report.recommendations.map((r,i)=>(
<div key={i} style={{padding:"8px 10px",background:r.fixed?C.redMuted:C.bgCard,border:`1px solid ${r.fixed?C.red:C.border}`,borderRadius:6,fontSize:"0.65rem",color:r.fixed?C.red:C.t2,lineHeight:1.6}}>
{r.text}
</div>
))}
</div>
</div>
{/* Mesa de trabajo */}
{((report.mesa||[]).length>0||(report.vigiladas||[]).length>0)&&(
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.amber,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>MESA DE TRABAJO</div>
{(report.mesa||[]).map((m,i)=>(<div key={i} style={{fontSize:"0.64rem",color:C.t2,fontFamily:C.mono,marginBottom:3}}>★ {m.txid.slice(0,16)}…{m.nota?` — ${m.nota}`:""}</div>))}
{(report.vigiladas||[]).map((v,i)=>(<div key={"v"+i} style={{fontSize:"0.64rem",color:C.t2,fontFamily:C.mono,marginBottom:3}}>◉ {abrevDir(v.address)} · {btcTxt(v.sats)} · última comprobación {v.ultima?fechaHora(v.ultima.fecha):"—"}</div>))}
</div>
)}
{/* Metodología */}
<div style={{marginBottom:14}}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>METODOLOGÍA</div>
<div style={{fontSize:"0.64rem",color:C.t2,lineHeight:1.7,display:"flex",flexDirection:"column",gap:8}}>
<div><strong style={{color:C.t1}}>Niveles de certeza:</strong> {report.methodology.levels}</div>
<div><strong style={{color:C.t1}}>Heurísticas usadas:</strong> {report.methodology.heuristics}</div>
<div><strong style={{color:C.t1}}>Límites:</strong> {report.methodology.limits}</div>
</div>
</div>
{/* Anexo de verificación */}
<div>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,marginBottom:8,letterSpacing:"0.15em"}}>ANEXO DE VERIFICACIÓN</div>
<div style={{fontSize:"0.58rem",color:C.t2,fontFamily:C.mono,lineHeight:1.6}}>
{report.verificationAppendix.txids.length} txid(s) · {report.verificationAppendix.addresses.length} dirección(es). Compruébalos en tu propio nodo o en cualquier explorador.
</div>
</div>
</Card>
)}
</div>
);
}