Files
txoko-dashboard/src/72-herramientas-psbt.jsx
T
pikaroandClaude Opus 5.5 e2adf88f77 v1.34.0: leer QR con la cámara
Botón ⌗ QR junto a cada campo (direcciones, URI de pago, txid, xpub,
PSBT, tx en crudo). Enseña lo leído y pide confirmar. Rechaza semillas y
claves privadas sin mostrarlas. Foto de respaldo sin cámara en directo.
Librería qr 0.7.2 (Paul Miller) en vendor/qr/, con su huella en SETUP.
Pruebas en tests/test22.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
2026-10-22 00:40:23 +02:00

252 lines
17 KiB
React

// ── Auditoría de PSBT ──────────────────────────────────────────────────
function ToolPsbt() {
const [input, setInput] = useState("");
const [result, setResult] = useState(null);
const [err, setErr] = useState(null);
// Al tocar el texto, el resultado anterior desaparece: si no, se podía
// pegar otra PSBT y leer el «sin problemas» de la anterior (P-08).
const cambiarTexto = (v) => { setInput(v); setResult(null); setErr(null); };
const limpiar = () => { setInput(""); setResult(null); setErr(null); };
// Acepta base64 (lo habitual al copiar) o hexadecimal.
const decode = () => {
const raw = input.trim().replace(/\s/g,"");
if (!raw) return;
setErr(null); setResult(null);
try {
let bytes;
if (/^[0-9a-fA-F]+$/.test(raw) && raw.length % 2 === 0) {
bytes = new Uint8Array(raw.match(/../g).map(h=>parseInt(h,16)));
} else {
const bin = atob(raw);
bytes = new Uint8Array(bin.length);
for (let i=0;i<bin.length;i++) bytes[i] = bin.charCodeAt(i);
}
const psbt = parsePsbt(bytes);
setResult(analyzePsbt(psbt));
} catch(e) {
setErr(e.message);
}
};
const cargarArchivo = (file) => {
if (!file) return;
const r = new FileReader();
r.onload = (e) => {
const bytes = new Uint8Array(e.target.result);
setErr(null); setResult(null);
try { setResult(analyzePsbt(parsePsbt(bytes))); }
catch(err2) { setErr(err2.message); }
};
r.readAsArrayBuffer(file);
};
const colorNivel = (n) => n==="critico"?C.red : n==="aviso"?C.amber : C.blue;
const etiquetaNivel = (n) => n==="critico"?"CRÍTICO" : n==="aviso"?"AVISO" : "INFORMATIVO";
const R = result?.resumen;
return (
<Card>
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Auditoría de PSBT</div>
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12,lineHeight:1.6}}>
Revisa una transacción <strong style={{color:C.t1}}>antes de firmarla</strong>, cuando todavía puedes cambiarla. Todo se analiza en tu navegador: el archivo no se envía a ningún sitio, ni siquiera a tu nodo.
</div>
<textarea value={input} onChange={e=>cambiarTexto(e.target.value)}
placeholder="Pega aquí la PSBT en base64 (cHNidP8BAH…) o en hexadecimal"
rows={4}
style={{width:"100%",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none",resize:"vertical",boxSizing:"border-box",marginBottom:8}}
onFocus={e=>e.target.style.borderColor=C.blue} onBlur={e=>e.target.style.borderColor=C.borderBright}
/>
<div style={{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",marginBottom:10}}>
<button onClick={decode} style={{padding:"9px 16px",background:C.blueMuted,border:`1px solid ${C.blue}40`,borderRadius:6,color:C.blue,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>ANALIZAR</button>
<BotonQR campo="psbt" color={C.blue} onLeido={v=>cambiarTexto(v)}/>
<label style={{padding:"9px 16px",background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.t2,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer"}}>
…o abrir archivo .psbt
<input type="file" accept=".psbt,.txn,application/octet-stream" style={{display:"none"}} onChange={e=>{ setInput(""); cargarArchivo(e.target.files[0]); e.target.value=""; }}/>
</label>
{(input||result||err)&&<button onClick={limpiar} style={{padding:"9px 14px",background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.t2,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer"}}>Limpiar</button>}
</div>
{err&&<div style={{padding:"10px 12px",background:C.redMuted,border:`1px solid ${C.red}40`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.7rem",lineHeight:1.6}}>{err}</div>}
{result&&(
<div style={{display:"flex",flexDirection:"column",gap:12}}>
{/* Resumen de la transacción */}
<div style={{padding:"12px 14px",background:C.bg,borderRadius:6,border:`1px solid ${C.border}`}}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,fontWeight:700,letterSpacing:"0.12em",marginBottom:10}}>QUÉ HACE ESTA TRANSACCIÓN</div>
<div style={{display:"flex",gap:18,flexWrap:"wrap"}}>
<Tag label="Entradas" value={R.entradas}/>
<Tag label="Salidas" value={R.salidas}/>
{R.totalIn!=null&&<Tag label="Gasta" value={fmt.btc(R.totalIn)}/>}
<Tag label="Envía" value={fmt.btc(R.totalOut)}/>
{R.fee!=null&&<Tag label="Comisión" value={R.importesInvalidos?"inválida":`${fmt.num(R.fee)} sat`} color={R.importesInvalidos?C.red:C.amber}/>}
<Tag label="Firmas ya puestas" value={R.firmasPresentes}/>
</div>
<div style={{marginTop:10,fontSize:"0.62rem",color:C.t2,fontFamily:C.mono,lineHeight:1.7}}>
Gasta monedas de tipo {R.tiposEntrada.join(", ")||"desconocido"} · envía a {R.tiposSalida.join(", ")}<br/>
{R.rbf ? "Señaliza RBF (BIP125) en sus entradas." : "No señaliza RBF (BIP125) en sus entradas. Que se pueda reemplazar depende también de la política de los nodos (Bitcoin Core acepta reemplazos sin señal desde la versión 28) y de lo que permita tu monedero."}
{R.locktime>0 && (R.locktime < 500000000
? ` · locktime ${R.locktime}: altura de bloque${R.locktimeActivo?"; no puede minarse antes":" (sin efecto: ninguna entrada lo activa)"}.`
: ` · locktime ${R.locktime}: marca de tiempo (${new Date(R.locktime*1000).toISOString().slice(0,10)}).`)}
</div>
</div>
{/* Avisos */}
{result.avisos.length===0 ? (
<div style={{padding:"12px 14px",background:C.greenMuted,border:`1px solid ${C.green}40`,borderRadius:6,fontSize:"0.68rem",color:C.green,fontFamily:C.mono}}>
✓ No se detectan problemas de privacidad en la estructura de esta transacción.
</div>
) : result.avisos.map((a,i)=>(
<div key={i} style={{padding:"12px 14px",background:C.bgCard,borderRadius:6,border:`1px solid ${colorNivel(a.nivel)}40`}}>
<div style={{display:"flex",alignItems:"center",gap:8,marginBottom:8,flexWrap:"wrap"}}>
<span style={{fontSize:"0.55rem",fontFamily:C.mono,fontWeight:700,color:colorNivel(a.nivel),border:`1px solid ${colorNivel(a.nivel)}50`,borderRadius:3,padding:"2px 6px"}}>{etiquetaNivel(a.nivel)}</span>
<span style={{fontSize:"0.72rem",color:C.t1,fontWeight:600}}>{a.titulo}</span>
</div>
<div style={{fontSize:"0.65rem",color:C.t2,lineHeight:1.7,marginBottom:6}}>{a.hecho}</div>
<div style={{fontSize:"0.65rem",color:C.t1,lineHeight:1.7}}>{a.consecuencia}</div>
{a.quePuedesHacer&&(
<div style={{marginTop:8,paddingTop:8,borderTop:`1px solid ${C.border}`,fontSize:"0.64rem",color:C.green,lineHeight:1.7}}>
<strong>Qué lo cambia:</strong> {a.quePuedesHacer}
</div>
)}
</div>
))}
<div style={{fontSize:"0.58rem",color:C.t3,fontFamily:C.mono,lineHeight:1.6}}>
{R.size} bytes analizados (PSBT …{R.huella}) · sin consultar el nodo · esta herramienta no firma ni modifica nada
</div>
</div>
)}
</Card>
);
}
// ── Decodificador Tx Raw ───────────────────────────────────────────────
function ToolRawTx() {
const [input, setInput] = useState("");
const [result, setResult] = useState(null);
const [err, setErr] = useState(null);
// Desde la v1.28 la descodifica entera (entradas, salidas, importes,
// RBF, locktime, txid). Acepta espacios y saltos de línea y exige un
// número par de caracteres: antes solo leía la versión y, con un
// carácter de menos, enseñaba un tamaño con medio byte (revisión T-01).
const decode = () => {
const raw = input.replace(/\s+/g, "");
if (!raw) return;
setErr(null); setResult(null);
try {
if (!/^[0-9a-fA-F]+$/.test(raw)) throw new Error("No es hexadecimal válido");
if (raw.length % 2) throw new Error("Tiene un número impar de caracteres: falta o sobra uno (cada byte son dos)");
if (raw.length < 20) throw new Error("Demasiado corto para ser una transacción");
const bytes = new Uint8Array(raw.match(/../g).map(h => parseInt(h, 16)));
let t;
try { t = leerTxPrevia(bytes); } catch (e) { throw new Error(e.message === "sobran bytes" ? "Sobran bytes al final: no es una transacción completa" : "No se puede descodificar como transacción (está cortada o no lo es)"); }
setResult(t);
} catch(e) {
setErr(`Error: ${e.message}`);
}
};
return (
<Card>
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Comprobar transacción en crudo (hex)</div>
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12}}>Una transacción «en crudo» es su texto hexadecimal completo. Esto la descodifica: entradas, salidas con sus importes, RBF, locktime y txid. No comprueba firmas, y sin consultar el nodo no sabe cuánto vale cada moneda que gasta. Todo ocurre en el navegador.</div>
<textarea value={input} onChange={e=>{ setInput(e.target.value); setResult(null); setErr(null); }}
placeholder="0100000001..."
rows={4}
style={{width:"100%",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"10px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.72rem",outline:"none",resize:"vertical",boxSizing:"border-box",marginBottom:8}}
onFocus={e=>e.target.style.borderColor=C.blue} onBlur={e=>e.target.style.borderColor=C.borderBright}
/>
<div style={{display:"flex",gap:8,alignItems:"stretch",marginBottom:10}}>
<button onClick={decode} style={{padding:"9px 16px",background:C.blueMuted,border:`1px solid ${C.blue}40`,borderRadius:6,color:C.blue,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>COMPROBAR</button>
<BotonQR campo="tx" color={C.blue} onLeido={v=>{ setInput(v); setResult(null); setErr(null); }}/>
</div>
{err&&<div style={{padding:"8px 12px",background:C.redMuted,border:`1px solid ${C.red}30`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.72rem"}}>{err}</div>}
{result&&(
<div style={{padding:"12px 14px",background:C.bg,borderRadius:6,border:`1px solid ${C.green}40`}}>
<div style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
<span style={{color:C.green,fontSize:"1rem"}}>✓</span>
<span style={{color:C.green,fontFamily:C.mono,fontSize:"0.78rem",fontWeight:700}}>Transacción descodificada</span>
</div>
<div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
<Tag label="Tamaño" value={`${result.bytes} bytes`} color={C.blue}/>
<Tag label="Versión" value={result.version} color={C.amber}/>
<Tag label="Entradas" value={result.vin.length} color={C.t2}/>
<Tag label="Salidas" value={result.outs.length} color={C.t2}/>
</div>
<div style={{marginTop:10,fontSize:"0.62rem",color:C.t2,fontFamily:C.mono,lineHeight:1.7,wordBreak:"break-all"}}>
txid {result.txid}<br/>
{result.segwit?"SegWit":"Sin datos SegWit"} · {result.vin.some(i=>i.sequence<0xfffffffe)?"señaliza RBF (BIP125)":"no señaliza RBF (BIP125)"} · locktime {result.locktime===0?"0 (sin efecto)":result.locktime<500000000?`${result.locktime} (altura de bloque)`:`${result.locktime} (marca de tiempo)`}
</div>
<div style={{marginTop:8,display:"flex",flexDirection:"column",gap:3}}>
{result.outs.map((o,i)=>(
<div key={i} style={{fontSize:"0.62rem",fontFamily:C.mono,color:C.t1}}>
<span style={{color:C.t2}}>salida {i+1}:</span> {fmtBtc(o.value)} · {PSBT_TIPOS[psbtScriptType(o.script)]}
</div>))}
</div>
</div>
)}
</Card>
);
}
// ── Verificador de firma ───────────────────────────────────────────────
function ToolVerifySig() {
const [addr, setAddr] = useState("");
const [msg, setMsg] = useState("");
const [sig, setSig] = useState("");
const [result, setResult] = useState(null);
const verify = () => {
// Basic format validation — full cryptographic verification requires secp256k1
setResult(null);
if (!addr.trim()||!msg.trim()||!sig.trim()) { setResult({valid:false, note:"Faltan campos: dirección, mensaje y firma."}); return; }
// Validate signature format (base64, ~88 chars)
const sigClean = sig.trim().replace(/\s/g,"");
if (sigClean.length < 80 || sigClean.length > 100) {
setResult({valid:false, note:"La firma no tiene la forma esperada: una firma de mensaje ocupa unos 88 caracteres en base64."});
return;
}
try { atob(sigClean); } catch { setResult({valid:false, note:"La firma no es base64 válido"}); return; }
setResult({
valid: null, // Can't verify without secp256k1
note: "La firma tiene la forma esperada. Esto no dice si es válida ni si la dirección pertenece a quien la firmó: eso solo lo establece una verificación criptográfica (verifymessage de Bitcoin Core, o Sparrow).",
addr: addr.trim(),
msgHash: msg.trim().length + " caracteres",
});
};
return (
<Card>
<div style={{fontSize:"0.62rem",color:C.blue,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Comprobar formato de firma</div>
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12}}>Comprueba solo que la firma de un mensaje tiene la forma esperada (unos 88 caracteres en base64). <strong style={{color:C.t1}}>No comprueba que la firma sea válida ni que la dirección sea de quien firma</strong>: eso exige verificarla criptográficamente, por ejemplo con <span style={{fontFamily:C.mono}}>verifymessage</span> de Bitcoin Core o con Sparrow.</div>
<div style={{display:"flex",flexDirection:"column",gap:8,marginBottom:10}}>
{[
{label:"Dirección", value:addr, onChange:e=>setAddr(e.target.value), placeholder:"bc1q..."},
{label:"Mensaje", value:msg, onChange:e=>setMsg(e.target.value), placeholder:"El mensaje que fue firmado"},
{label:"Firma", value:sig, onChange:e=>setSig(e.target.value), placeholder:"Base64 de la firma..."},
].map(f=>(
<div key={f.label}>
<div style={{fontSize:"0.6rem",color:C.t2,fontFamily:C.mono,textTransform:"uppercase",marginBottom:4}}>{f.label}</div>
<input value={f.value} onChange={f.onChange} placeholder={f.placeholder}
style={{width:"100%",background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none",boxSizing:"border-box"}}
onFocus={e=>e.target.style.borderColor=C.blue} onBlur={e=>e.target.style.borderColor=C.borderBright}
/>
</div>
))}
</div>
<button onClick={verify} style={{padding:"9px 16px",background:C.blueMuted,border:`1px solid ${C.blue}40`,borderRadius:6,color:C.blue,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700,marginBottom:10}}>COMPROBAR FORMATO</button>
{result&&(
<div style={{padding:"12px 14px",background:C.bg,borderRadius:6,border:`1px solid ${result.valid===false?C.red:C.amber}40`}}>
<div style={{fontSize:"0.7rem",color:result.valid===false?C.red:C.amber,fontFamily:C.mono,marginBottom:6,fontWeight:700}}>
{result.valid===false?"✗ Forma incorrecta":"Forma correcta (no verificada)"}
</div>
<div style={{fontSize:"0.68rem",color:C.t2,lineHeight:1.6}}>{result.note}</div>
</div>
)}
</Card>
);
}