Files
txoko-dashboard/src/49-simulador-gasto.jsx
T

181 lines
16 KiB
React

// ── «¿Qué revelaría este gasto?» (v1.45.0) ──────────────────────────────
// Tarjeta de Auditar privacidad, bajo el informe de la wallet. Se eligen
// monedas y un destino, se arma una transacción SIMULADA en memoria
// (simularGasto) y se pasa por el mismo analyzeTx que las reales. Nada se
// construye de verdad, nada se firma, nada se guarda (ni en ALMACEN ni en
// el navegador). La única consulta es a TU nodo, por el destino, y solo al
// pulsar «Simular».
function SimuladorGasto({ base, walletAddrs, walletReport, labels }) {
const { getStrict } = useApi(base);
const [marcadas, setMarcadas] = useState(() => new Set());
const [destino, setDestino] = useState("");
const [importeTxt, setImporteTxt] = useState("");
const [tarifaTxt, setTarifaTxt] = useState("");
const [res, setRes] = useState(null);
const [cargando, setCargando] = useState(false);
const gen = useRef(0);
const limpiar = () => { gen.current++; setMarcadas(new Set()); setDestino(""); setImporteTxt(""); setTarifaTxt(""); setRes(null); setCargando(false); };
// Otra wallet u otro informe: lo marcado ya no vale.
useEffect(() => { limpiar(); }, [walletReport, walletAddrs]);
const listo = walletAddrs && walletReport && !walletReport.error && Array.isArray(walletReport.utxos);
const utxos = listo ? walletReport.utxos : [];
const clusters = listo ? (walletReport.clusters || []) : [];
const clave = m => `${m.txid}:${m.vout}`;
const etiquetaDe = m => (labels && (labels.get(clave(m)) || labels.get(m.address))) || null;
const grupoDe = a => clusters.findIndex(g => g.includes(a));
const elegidas = utxos.filter(m => marcadas.has(clave(m)));
const totalElegido = elegidas.reduce((s, m) => s + (m.value || 0), 0);
const alternar = m => { setRes(null); setMarcadas(prev => { const n = new Set(prev); n.has(clave(m)) ? n.delete(clave(m)) : n.add(clave(m)); return n; }); };
const myAddr = a => !walletAddrs ? null : walletAddrs.receive.includes(a) ? "recepción" : walletAddrs.change.includes(a) ? "cambio" : null;
const simular = async () => {
const g = ++gen.current;
setRes(null);
const dest = destino.trim();
const monedas = elegidas.map(m => ({ ...m, label: etiquetaDe(m) }));
// Importe: vacío = enviar todo. Coma o punto decimal.
let importeSats = null;
if (importeTxt.trim()) {
if (!/^\d+([.,]\d{1,8})?$/.test(importeTxt.trim().replace(/\s/g, ""))) { setRes({ error: "El importe no es válido: escríbelo en BTC, con coma o punto (por ejemplo 0,001) y como mucho 8 decimales." }); return; }
importeSats = leerBtc(importeTxt);
if (!(importeSats > 0)) { setRes({ error: "El importe tiene que ser mayor que 0. Para enviarlo todo, deja el importe vacío." }); return; }
}
setCargando(true);
// Tarifa: la escrita; si no, la del nodo; si no, 5 sat/vB.
let tarifa, tarifaInfo;
if (tarifaTxt.trim()) {
tarifa = parseFloat(tarifaTxt.trim().replace(",", "."));
tarifaInfo = "la que has escrito";
} else if (base) {
try {
const f = await getStrict("/api/v1/fees/recommended");
const v = Number(f && f.halfHourFee);
if (!(v > 0)) throw new Error("respuesta sin halfHourFee");
tarifa = v; tarifaInfo = "la que da tu nodo para entrar en un bloque en media hora (halfHourFee)";
} catch (e) { tarifa = TARIFA_SIMULADOR_DEFECTO; tarifaInfo = `tu nodo no la ha dado (${(e && e.message) || "sin respuesta"}), así que se usan ${TARIFA_SIMULADOR_DEFECTO} sat/vB`; }
} else { tarifa = TARIFA_SIMULADOR_DEFECTO; tarifaInfo = `sin nodo no hay tarifa de referencia, así que se usan ${TARIFA_SIMULADOR_DEFECTO} sat/vB`; }
if (g !== gen.current) return;
const cambio = cambioParaSimular(walletAddrs, walletReport.direccionesUsadas);
const sim = simularGasto({ monedas, destino: dest, importeSats, tarifa, cambio });
if (sim.error) { setRes({ error: sim.error }); setCargando(false); return; }
const ctx = { misDirecciones: new Set([...walletAddrs.receive, ...walletAddrs.change, ...(cambio.ficticia ? [cambio.address] : [])]), simulada: true };
let analysis;
try { analysis = analyzeTx(sim.tx, ctx); }
catch (e) { setRes({ error: "No se pudo analizar la simulación: " + e.message }); setCargando(false); return; }
// Lo que sabe TU nodo del destino (la guarda de signet vale aquí).
let historialDestino;
if (!base) historialDestino = { estado: "sin_nodo" };
else {
try {
const st = await getStrict(`/api/address/${encodeURIComponent(dest)}`);
const txCount = (st?.chain_stats?.tx_count || 0) + (st?.mempool_stats?.tx_count || 0);
const recepciones = txoFiable(st) ? (st.chain_stats.funded_txo_count || 0) + (st.mempool_stats?.funded_txo_count || 0) : null;
historialDestino = { estado: "ok", recepciones, txCount };
} catch (e) {
historialDestino = e && e.bloqueado ? { estado: "bloqueado" } : { estado: "error", mensaje: (e && e.message) || "sin respuesta" };
}
}
if (g !== gen.current) return;
const entidad = ENTITY_INDEX.get(dest) || null;
const hechos = hechosDeGasto({ monedas, destino: dest, clusters, walletAddrs, labels, historialDestino, entidad, procedencia: entidad ? procedenciaEntidades([entidad]) : null });
setRes({ sim, analysis, hechos, tarifaInfo, cambioPrevisto: cambio });
setCargando(false);
};
const campo = { background: C.bg, border: `1px solid ${C.borderBright}`, borderRadius: 6, padding: "8px 10px", color: C.t1, fontFamily: C.mono, fontSize: "0.7rem", outline: "none", minWidth: 0 };
return (
<Card glow={C.amber}>
<div style={{ fontSize: "0.65rem", color: C.amber, fontFamily: C.mono, fontWeight: 700, marginBottom: 6 }}>¿QUÉ REVELARÍA ESTE GASTO?</div>
<div style={{ fontSize: "0.68rem", color: C.t2, lineHeight: 1.55, marginBottom: 10 }}>
Elige monedas y un destino y mira qué quedaría a la vista si se gastaran así. No se construye ni se firma nada: es una simulación con el mismo análisis que una transacción real.
</div>
{!listo ? (
<div style={{ fontSize: "0.66rem", color: C.t2, lineHeight: 1.6, padding: "8px 10px", border: `1px dashed ${C.border}`, borderRadius: 6 }}>
{walletReport && walletReport.error
? "El informe de la wallet dio error, así que no hay monedas que elegir. Cuando «Analizar wallet» termine bien, aparecerán aquí."
: walletAddrs
? (base ? "Necesita el informe de la wallet: pulsa «⊙ Analizar wallet» arriba y, cuando termine, aquí saldrán tus monedas sin gastar."
: "Necesita el informe de la wallet, y sin nodo (⚙ Ajustes) no se puede calcular: no hay a quién preguntar por tus monedas. La app no trae una wallet de ejemplo.")
: (base ? "Necesita una wallet cargada (xpub o descriptor, arriba) y su informe («Analizar wallet»)."
: "Necesita una wallet cargada y su informe, que se calcula preguntando a tu nodo. Sin nodo (⚙ Ajustes) no hay monedas que elegir, y la app no trae una wallet de ejemplo.")}
</div>
) : (<>
{walletReport.scanComplete === false && (
<div style={{ fontSize: "0.64rem", color: C.amber, lineHeight: 1.5, marginBottom: 8, padding: "6px 9px", border: `1px solid ${C.amber}40`, borderRadius: 6 }}>
⚠ El informe de la wallet está incompleto: puede faltar alguna moneda, o salir como sin gastar una que ya se gastó.
</div>)}
{utxos.length === 0 ? (
<div style={{ fontSize: "0.66rem", color: C.t2, marginBottom: 8 }}>No se ve ninguna moneda sin gastar en las direcciones analizadas.</div>
) : (
<div style={{ marginBottom: 10 }}>
<div style={{ fontSize: "0.58rem", color: C.t2, fontFamily: C.mono, marginBottom: 6 }}>TUS MONEDAS SIN GASTAR · {utxos.length}{marcadas.size ? ` · ${marcadas.size} marcada${marcadas.size > 1 ? "s" : ""} (${fmtBtc(totalElegido)})` : ""}</div>
<div style={{ display: "flex", flexDirection: "column", gap: 4, maxHeight: 260, overflowY: "auto" }}>
{utxos.map(m => {
const k = clave(m), on = marcadas.has(k), lbl = etiquetaDe(m), gr = grupoDe(m.address), rama = myAddr(m.address);
return (
<label key={k} style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", padding: "6px 9px", background: on ? C.amberMuted : C.bgCard, border: `1px solid ${on ? C.amber : C.border}`, borderRadius: 5, cursor: "pointer" }}>
<input type="checkbox" checked={on} onChange={() => alternar(m)} />
<span style={{ fontSize: "0.68rem", color: C.t1, fontFamily: C.mono, minWidth: 110 }}>{fmtBtc(m.value)}</span>
<span style={{ fontSize: "0.6rem", color: C.t2, fontFamily: C.mono, display: "inline-flex", alignItems: "center", gap: 4 }}>{abrevDirSim(m.address)} <BotonCopiar texto={m.address} etiqueta="la dirección" /></span>
{rama && <span style={{ fontSize: "0.56rem", color: C.t3, fontFamily: C.mono }}>{rama}</span>}
{lbl && <span style={{ fontSize: "0.6rem", color: C.purple, fontFamily: C.mono }}>🏷 {lbl}</span>}
<span style={{ fontSize: "0.56rem", color: gr >= 0 ? C.amber : C.t3, fontFamily: C.mono, marginLeft: "auto" }}>{gr >= 0 ? `grupo ${gr + 1}` : "suelta"}</span>
{esPolvoMoneda(m) && <span style={{ fontSize: "0.56rem", color: C.amber, fontFamily: C.mono }}>polvo</span>}
{!m.confirmada && <span style={{ fontSize: "0.56rem", color: C.t3, fontFamily: C.mono }}>sin confirmar</span>}
</label>);
})}
</div>
{clusters.length > 0 && <div style={{ fontSize: "0.58rem", color: C.t3, marginTop: 4 }}>«grupo N» es el grupo de direcciones vinculadas N del informe de arriba; «suelta», una dirección que no está vinculada con otras.</div>}
</div>)}
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(160px,1fr))", gap: 8, marginBottom: 8 }}>
<input value={destino} onChange={e => { setDestino(filtrarSecreto(e.target.value)); setRes(null); }} placeholder="Dirección de destino" spellCheck={false} autoComplete="off" style={{ ...campo, gridColumn: "1 / -1" }} />
<input value={importeTxt} onChange={e => { setImporteTxt(e.target.value); setRes(null); }} placeholder="Importe en BTC (vacío = enviar todo)" inputMode="decimal" style={campo} />
<input value={tarifaTxt} onChange={e => { setTarifaTxt(e.target.value); setRes(null); }} placeholder={`Tarifa sat/vB (vacío = la de tu nodo, o ${TARIFA_SIMULADOR_DEFECTO})`} inputMode="decimal" style={campo} />
</div>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
<button onClick={simular} disabled={cargando || !marcadas.size || !destino.trim()}
style={{ padding: "7px 16px", background: C.amberMuted, border: `1px solid ${C.amber}60`, borderRadius: 6, color: C.amber, fontFamily: C.mono, fontSize: "0.68rem", fontWeight: 700, cursor: cargando || !marcadas.size || !destino.trim() ? "default" : "pointer", opacity: !marcadas.size || !destino.trim() ? 0.6 : 1 }}>
{cargando ? "···" : "Simular"}
</button>
<button onClick={limpiar} style={{ padding: "7px 14px", background: "none", border: `1px solid ${C.border}`, borderRadius: 6, color: C.t2, fontFamily: C.mono, fontSize: "0.66rem", cursor: "pointer" }}>Limpiar</button>
{(!marcadas.size || !destino.trim()) && <span style={{ fontSize: "0.6rem", color: C.t3, alignSelf: "center" }}>Hace falta al menos una moneda marcada y un destino.</span>}
</div>
</>)}
{res && res.error && (
<div style={{ marginTop: 10, padding: "8px 12px", background: C.redMuted, border: `1px solid ${C.red}30`, borderRadius: 6, color: C.red, fontSize: "0.68rem", lineHeight: 1.5 }}>{res.error}</div>)}
{res && res.sim && (
<div style={{ marginTop: 12 }}>
<div style={{ padding: "10px 14px", border: `2px dashed ${C.amber}`, borderRadius: 8, background: C.amberMuted, color: C.amber, fontFamily: C.mono, fontWeight: 700, fontSize: "0.78rem", letterSpacing: "0.08em", textAlign: "center", marginBottom: 10 }}>
SIMULACIÓN · no es una transacción real
<div style={{ fontSize: "0.6rem", fontWeight: 400, letterSpacing: 0, marginTop: 3 }}>No tiene firmas ni txid, no se ha enviado a ninguna parte y no se guarda.</div>
</div>
{(() => { const s = res.sim, c = s.cambio, cp = res.cambioPrevisto; return (
<div style={{ fontSize: "0.66rem", color: C.t1, lineHeight: 1.7, marginBottom: 10, padding: "10px 12px", background: C.bgCard, border: `1px solid ${C.border}`, borderRadius: 6 }}>
<div>Entradas: {s.tx.vin.length} moneda{s.tx.vin.length > 1 ? "s" : ""}, {fmtBtc(s.totalIn)}.</div>
<div>Salida 0: {s.enviarTodo ? "todo" : "el pago"}, {fmtBtc(s.tx.vout[0].value)} a <span style={{ fontFamily: C.mono }}>{abrevDirSim(s.tx.vout[0].scriptpubkey_address)}</span> ({formatoDir(s.tx.vout[0].scriptpubkey_type)}).</div>
{c ? <div>Salida 1: el cambio, {fmtBtc(c.value)} a {c.ficticia ? <span style={{ color: C.amber }}>una dirección de cambio ficticia ({formatoDir(c.scriptpubkey_type)}), porque {cp.motivo}</span> : <>tu dirección de cambio {c.indice} (<span style={{ fontFamily: C.mono }}>{abrevDirSim(c.address)}</span>), la primera sin usar</>}.</div>
: s.enviarTodo ? <div>Sin cambio: se envía todo menos la comisión.</div>
: <div>Sin cambio: lo que sobraba ({fmtEnt(s.sobranteAComision)} sat) es menos que el mínimo de la red y se suma a la comisión, como hacen los monederos.</div>}
<div>Comisión estimada: {fmtEnt(s.fee)} sat, unos {fmtEnt(s.vsize)} vB a {fmtDec(s.tarifa, s.tarifa % 1 ? 2 : 0)} sat/vB ({res.tarifaInfo}).</div>
<div style={{ fontSize: "0.6rem", color: C.t2, marginTop: 4 }}>Tamaño aproximado: cabecera {s.vbytes.cabecera} vB + entradas {s.vbytes.entradas.join(" + ")} vB + salidas {s.vbytes.salidas.join(" + ")} vB. La firma real puede variar un byte arriba o abajo.{s.entradaDesconocida ? " Alguna entrada es de un formato del que la app no sabe el tamaño: se ha contado como antigua (148 vB)." : ""}</div>
</div>); })()}
{res.hechos.length > 0 && (
<div style={{ marginBottom: 10, padding: "10px 12px", background: C.bgCard, border: `1px solid ${C.borderBright}`, borderRadius: 6 }}>
<div style={{ fontSize: "0.6rem", color: C.t2, fontFamily: C.mono, letterSpacing: "0.12em", fontWeight: 700, marginBottom: 8 }}>LO QUE SABE TU WALLET Y NO VE EL ANÁLISIS DE UNA SOLA TRANSACCIÓN</div>
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
{res.hechos.map(h => (
<div key={h.id} style={{ display: "flex", gap: 8, alignItems: "flex-start", flexWrap: "wrap" }}>
<CertaintyBadge level={h.certeza} />
<span style={{ fontSize: "0.68rem", color: C.t1, lineHeight: 1.55, flex: 1, minWidth: 200 }}>{h.texto}</span>
</div>))}
</div>
</div>)}
<PrivacyLab analysis={res.analysis} tx={res.sim.tx} labels={labels} myAddr={myAddr} />
</div>)}
</Card>
);
}