El lector junta los trozos de los QR animados (UR, BBQr y Specter) con la cámara abierta y barra de progreso. Lee la xpub animada de SeedSigner (crypto-account) y la convierte en zpub con huella y ruta. En la auditoría de PSBT, después del análisis, compara la PSBT firmada (o la transacción final) con la auditada y dice qué cambia o qué entradas llevan firma. Pieza nueva src/06-qr-animado.js, sin librerías nuevas. Pruebas en tests/test23.js con los vectores oficiales de Blockchain Commons y BBQr de la implementación de referencia de Coinkite. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
227 lines
15 KiB
React
227 lines
15 KiB
React
// ── Leer QR con la cámara (v1.34; animados desde la v1.35) ─────────────────────────────────────
|
||
// La librería (qr de Paul Miller) vive en vendor/qr/ y solo se carga al
|
||
// abrir el lector. Todo ocurre en el navegador: la imagen de la cámara no
|
||
// sale del aparato y leer un QR no hace ninguna consulta de red.
|
||
let promesaLectorQR = null;
|
||
// import() dinámico escondido en una función para que Babel no lo toque.
|
||
const importarModulo = new Function("u", "return import(u)");
|
||
function cargarLectorQR() {
|
||
if (!promesaLectorQR) {
|
||
promesaLectorQR = importarModulo(new URL("vendor/qr/decode.js", location.href).href)
|
||
.then(m => m.decodeQR || m.default)
|
||
.catch(e => { promesaLectorQR = null; throw e; });
|
||
}
|
||
return promesaLectorQR;
|
||
}
|
||
function resumenQR(r) {
|
||
if (!r) return "";
|
||
if (r.tipo === "xpub") return `${r.valor.slice(0, 12)}…${r.valor.slice(-8)}${r.huella ? ` · huella ${r.huella}` : ""}${r.ruta ? ` · ${r.ruta}` : ""}`;
|
||
if (r.tipo === "psbt") return `PSBT de ${r.valor.length.toLocaleString("es-ES")} caracteres`;
|
||
if (r.tipo === "tx") return `transacción de ${(r.valor.length / 2).toLocaleString("es-ES")} bytes`;
|
||
return r.valor;
|
||
}
|
||
|
||
function BotonQR({ campo, onLeido, color }) {
|
||
const [abierto, setAbierto] = useState(false);
|
||
const col = color || C.purple;
|
||
return (
|
||
<>
|
||
<button type="button" onClick={() => setAbierto(true)} title="Leer un QR con la cámara" aria-label="Leer un QR con la cámara"
|
||
style={{ padding: "0 12px", minWidth: 42, background: C.bg, border: `1px solid ${col}40`, borderRadius: 6, color: col, fontSize: "1rem", cursor: "pointer", flexShrink: 0 }}>
|
||
⌗<span style={{ fontFamily: C.mono, fontSize: "0.6rem", marginLeft: 4 }}>QR</span>
|
||
</button>
|
||
{abierto && <LectorQR campo={campo} onCerrar={() => setAbierto(false)} onUsar={v => { setAbierto(false); onLeido(v); }} />}
|
||
</>
|
||
);
|
||
}
|
||
|
||
function LectorQR({ campo, onCerrar, onUsar }) {
|
||
const videoRef = useRef(null), streamRef = useRef(null), vivoRef = useRef(true), fotoRef = useRef(null);
|
||
const [fase, setFase] = useState("cargando"); // cargando · camara · sin-camara · leido · otro · secreto · sin-lector
|
||
const [aviso, setAviso] = useState("");
|
||
const [leido, setLeido] = useState(null);
|
||
// QR animados (v1.35): los trozos se van juntando mientras la cámara
|
||
// sigue abierta. El colector vive fuera del estado de React.
|
||
const colectorRef = useRef(null);
|
||
const [progreso, setProgreso] = useState(null); // { formato, hechos, total }
|
||
|
||
const pararCamara = () => {
|
||
if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; }
|
||
if (videoRef.current) videoRef.current.srcObject = null;
|
||
};
|
||
const procesar = texto => mostrar(clasificarQR(texto));
|
||
const mostrar = r => {
|
||
pararCamara();
|
||
setAviso(""); setProgreso(null);
|
||
if (r.tipo === "secreto") { setLeido(null); setFase("secreto"); return; }
|
||
const e = encajaQR(r, campo);
|
||
setLeido(r);
|
||
if (e.ok) { setFase("leido"); setAviso(""); }
|
||
else { setFase("otro"); setAviso(e.mensaje); }
|
||
};
|
||
const leerImagen = (decode, fuente, w, h, opts) => {
|
||
const lienzo = document.createElement("canvas");
|
||
lienzo.width = w; lienzo.height = h;
|
||
const ctx = lienzo.getContext("2d", { willReadFrequently: true });
|
||
ctx.drawImage(fuente, 0, 0, w, h);
|
||
const img = ctx.getImageData(0, 0, w, h);
|
||
try { return decode({ width: w, height: h, data: img.data }, { textDecoder: textoDeBytesQR, ...opts }); }
|
||
catch { return null; }
|
||
};
|
||
|
||
// Lo que lee la cámara pasa primero por el colector de QR animados. Si
|
||
// no es un trozo de uno, se trata como un QR normal.
|
||
const recibir = (t, enFoto) => {
|
||
const c = colectorRef.current || (colectorRef.current = crearColectorQR());
|
||
const e = c.recibir(t);
|
||
if (e.estado === "nada") { if (c.formato && !enFoto) return false; procesar(t); return true; }
|
||
if (e.estado === "secreto") { mostrar({ tipo: "secreto" }); return true; }
|
||
if (e.estado === "error") { setAviso(`Un trozo no se ha podido leer (${e.mensaje}). Sigue apuntando: se vuelve a empezar.`); setProgreso(null); return false; }
|
||
if (e.estado === "progreso") {
|
||
if (enFoto) { c.reiniciar(); setAviso(`Es un trozo (${e.hechos} de ${e.total}) de un QR animado: hace falta la cámara en directo, que vaya leyendo los trozos mientras pasan.`); return true; }
|
||
setProgreso(p => p && p.hechos === e.hechos && p.total === e.total && p.formato === e.formato ? p : { formato: e.formato, hechos: e.hechos, total: e.total });
|
||
return false;
|
||
}
|
||
// listo
|
||
pararCamara();
|
||
c.resultado().then(r => { if (vivoRef.current) mostrar(r); })
|
||
.catch(err => { if (!vivoRef.current) return; setProgreso(null); setLeido(null); setFase("otro"); setAviso(`No se ha podido reconstruir el QR animado: ${err.message}`); })
|
||
.finally(() => { colectorRef.current = null; });
|
||
return true;
|
||
};
|
||
|
||
const arrancar = async () => {
|
||
setAviso(""); setLeido(null); setProgreso(null); setFase("cargando");
|
||
colectorRef.current = crearColectorQR();
|
||
let decode;
|
||
try { decode = await cargarLectorQR(); }
|
||
catch { if (vivoRef.current) setFase("sin-lector"); return; }
|
||
if (!vivoRef.current) return;
|
||
if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia) {
|
||
setAviso("La cámara en directo solo funciona si abres Txoko por https. Puedes hacer una foto del QR.");
|
||
setFase("sin-camara"); return;
|
||
}
|
||
try {
|
||
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: "environment" } }, audio: false });
|
||
if (!vivoRef.current) { stream.getTracks().forEach(t => t.stop()); return; }
|
||
streamRef.current = stream;
|
||
setFase("camara");
|
||
const v = videoRef.current;
|
||
v.srcObject = stream;
|
||
v.setAttribute("playsinline", ""); v.muted = true;
|
||
await v.play().catch(() => {});
|
||
let ultimo = 0;
|
||
const bucle = ahora => {
|
||
if (!vivoRef.current || !streamRef.current) return;
|
||
if (ahora - ultimo > 120 && v.videoWidth) {
|
||
ultimo = ahora;
|
||
const esc = Math.min(1, 720 / Math.max(v.videoWidth, v.videoHeight));
|
||
const t = leerImagen(decode, v, Math.round(v.videoWidth * esc), Math.round(v.videoHeight * esc));
|
||
if (t != null && recibir(t, false)) return;
|
||
}
|
||
requestAnimationFrame(bucle);
|
||
};
|
||
requestAnimationFrame(bucle);
|
||
} catch (e) {
|
||
const n = e && e.name;
|
||
setAviso(n === "NotAllowedError" ? "No hay permiso para usar la cámara (o el navegador no lo da con este certificado). Puedes hacer una foto del QR."
|
||
: n === "NotFoundError" || n === "OverconstrainedError" ? "No encuentro ninguna cámara en este aparato. Puedes elegir una imagen con el QR."
|
||
: "No se ha podido abrir la cámara. Puedes hacer una foto del QR.");
|
||
setFase("sin-camara");
|
||
}
|
||
};
|
||
|
||
const leerFoto = async archivo => {
|
||
if (!archivo) return;
|
||
setAviso("Buscando el QR en la imagen…");
|
||
try {
|
||
const decode = await cargarLectorQR();
|
||
const bmp = await createImageBitmap(archivo);
|
||
const esc = Math.min(1, 1600 / Math.max(bmp.width, bmp.height));
|
||
const t = leerImagen(decode, bmp, Math.round(bmp.width * esc), Math.round(bmp.height * esc), { effort: Infinity, timeLimit: 3000 });
|
||
if (bmp.close) bmp.close();
|
||
if (t != null) { colectorRef.current = crearColectorQR(); recibir(t, true); }
|
||
else setAviso("No encuentro ningún QR en esa imagen. Prueba con otra más cerca y con luz.");
|
||
} catch {
|
||
setAviso("No he podido leer esa imagen.");
|
||
}
|
||
};
|
||
|
||
useEffect(() => {
|
||
vivoRef.current = true;
|
||
arrancar();
|
||
const tecla = e => { if (e.key === "Escape") onCerrar(); };
|
||
window.addEventListener("keydown", tecla);
|
||
return () => { vivoRef.current = false; pararCamara(); window.removeEventListener("keydown", tecla); };
|
||
}, []);
|
||
|
||
const boton = (txt, onClick, col, fuerte) => (
|
||
<button type="button" onClick={onClick} style={{ padding: "9px 14px", background: fuerte ? `${col}22` : "none", border: `1px solid ${col}${fuerte ? "" : "60"}`, borderRadius: 6, color: col, fontFamily: C.mono, fontSize: "0.72rem", cursor: "pointer", fontWeight: fuerte ? 700 : 400 }}>{txt}</button>
|
||
);
|
||
return (
|
||
<div role="dialog" aria-modal="true" aria-label="Leer un QR"
|
||
style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,0.78)", display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}
|
||
onClick={e => { if (e.target === e.currentTarget) onCerrar(); }}>
|
||
<div style={{ width: "100%", maxWidth: 440, background: C.bgCard, border: `1px solid ${C.borderBright}`, borderRadius: 10, padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
|
||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||
<div style={{ fontFamily: C.mono, fontSize: "0.7rem", color: C.t1, fontWeight: 700, letterSpacing: "0.08em" }}>LEER UN QR</div>
|
||
<button type="button" onClick={onCerrar} aria-label="Cerrar el lector" style={{ background: "none", border: "none", color: C.t2, fontSize: "1.1rem", cursor: "pointer" }}>×</button>
|
||
</div>
|
||
|
||
{(fase === "camara" || fase === "cargando") && (
|
||
<div style={{ position: "relative", width: "100%", aspectRatio: "1 / 1", background: "#000", borderRadius: 8, overflow: "hidden" }}>
|
||
<video ref={videoRef} playsInline muted style={{ width: "100%", height: "100%", objectFit: "cover", display: fase === "camara" ? "block" : "none" }} />
|
||
<div style={{ position: "absolute", inset: "14%", border: `2px solid ${C.green}aa`, borderRadius: 10, pointerEvents: "none" }} />
|
||
{fase === "cargando" && <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", color: C.t2, fontFamily: C.mono, fontSize: "0.7rem" }}>abriendo la cámara…</div>}
|
||
</div>
|
||
)}
|
||
{fase === "camara" && !progreso && <div style={{ fontSize: "0.66rem", color: C.t2, lineHeight: 1.5 }}>Apunta al QR. Si es animado (una PSBT, la xpub de SeedSigner), mantenlo delante hasta que se complete. La imagen no sale de este aparato.</div>}
|
||
{fase === "camara" && progreso && (
|
||
<div role="status" aria-live="polite">
|
||
<div style={{ display: "flex", justifyContent: "space-between", fontFamily: C.mono, fontSize: "0.64rem", color: C.t1, marginBottom: 5 }}>
|
||
<span>QR animado ({progreso.formato === "ur" ? "UR" : progreso.formato === "bbqr" ? "BBQr" : "Specter"})</span>
|
||
<span>{progreso.hechos} de {progreso.total} trozos</span>
|
||
</div>
|
||
<div style={{ height: 6, background: C.bg, borderRadius: 3, overflow: "hidden", border: `1px solid ${C.border}` }}>
|
||
<div style={{ width: `${Math.round(100 * progreso.hechos / progreso.total)}%`, height: "100%", background: C.green, transition: "width 0.2s" }} />
|
||
</div>
|
||
<div style={{ fontSize: "0.62rem", color: C.t2, marginTop: 5, lineHeight: 1.5 }}>Mantén el QR delante. No hace falta leerlos en orden{progreso.formato === "ur" ? ", y si se escapa alguno, los siguientes lo reponen" : ""}.</div>
|
||
</div>
|
||
)}
|
||
|
||
{fase === "sin-lector" && (
|
||
<div style={{ fontSize: "0.7rem", color: C.amber, lineHeight: 1.6 }}>
|
||
Falta el lector de QR en el nodo: la carpeta <span style={{ fontFamily: C.mono }}>vendor/qr/</span>. Se instala con el paso 2 de SETUP.md.
|
||
</div>
|
||
)}
|
||
|
||
{fase === "secreto" && (
|
||
<div style={{ padding: "12px 14px", background: C.redMuted, border: `1px solid ${C.red}60`, borderRadius: 8, fontSize: "0.72rem", color: C.t1, lineHeight: 1.6 }}>
|
||
<strong style={{ color: C.red }}>Esto parece una semilla o una clave privada.</strong> Txoko no la necesita nunca, así que no la muestra ni la guarda: ya la ha olvidado. Guarda esa tarjeta y asegúrate de que no la ha visto nadie.
|
||
</div>
|
||
)}
|
||
|
||
{(fase === "leido" || fase === "otro") && leido && (
|
||
<div style={{ padding: "10px 12px", background: C.bg, border: `1px solid ${fase === "leido" ? C.green : C.amber}60`, borderRadius: 8 }}>
|
||
<div style={{ fontSize: "0.6rem", color: C.t2, fontFamily: C.mono, marginBottom: 4 }}>HE LEÍDO {(QR_NOMBRE[leido.tipo] || "").toUpperCase()}</div>
|
||
{leido.valor && <div style={{ fontFamily: C.mono, fontSize: "0.72rem", color: C.t1, wordBreak: "break-all" }}>{resumenQR(leido)}</div>}
|
||
{leido.tipo === "xpub" && leido.script && <div style={{ fontSize: "0.64rem", color: C.t2, marginTop: 4, lineHeight: 1.5 }}>Cuenta de direcciones {TIPO_SCRIPT[leido.script]}{leido.otras ? ` (el QR traía ${leido.otras + 1} tipos; se usa este)` : ""}.{leido.sinPadre ? " El QR no traía la huella de la clave madre: la clave puede verse distinta de la de tu monedero, pero da las mismas direcciones." : ""}</div>}
|
||
{leido.importe && <div style={{ fontSize: "0.64rem", color: C.t2, marginTop: 4 }}>El QR pedía un pago de {leido.importe} BTC{leido.etiqueta ? ` («${leido.etiqueta}»)` : ""}. Txoko solo usa la dirección.</div>}
|
||
</div>
|
||
)}
|
||
|
||
{aviso && <div style={{ fontSize: "0.68rem", color: fase === "otro" ? C.amber : C.t2, lineHeight: 1.6 }}>{aviso}</div>}
|
||
|
||
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
|
||
{fase === "leido" && boton("Usar esto", () => onUsar(leido.valor), C.green, true)}
|
||
{(fase === "leido" || fase === "otro" || fase === "secreto") && boton("Leer otro", arrancar, C.purple)}
|
||
{fase !== "sin-lector" && boton("Hacer una foto o elegir imagen", () => fotoRef.current && fotoRef.current.click(), C.blue)}
|
||
{boton("Cerrar", onCerrar, C.t2)}
|
||
<input ref={fotoRef} type="file" accept="image/*" capture="environment" style={{ display: "none" }}
|
||
onChange={e => { pararCamara(); setFase("sin-camara"); leerFoto(e.target.files[0]); e.target.value = ""; }} />
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|