Files
txoko-dashboard/src/06-qr-animado.js
T
pikaroandClaude Fable 5.2 a6293c3b50 v2.1.0: Taproot (BIP86) en «Cargar mi wallet»
Hasta ahora la app analizaba transacciones Taproot pero no sabía calcular
las direcciones bc1p… de una wallet: rechazaba tr(…), y la xpub suelta de
una wallet Taproot daba direcciones bc1q… que nunca coincidían.

- Derivación: clave retocada (BIP341, «TapTweak») y bech32m (BIP350).
- Descriptores tr(KEY) de una sola clave, con las mismas comprobaciones
  que wpkh, sh(wpkh) y pkh. Siguen fuera, con su motivo: árbol de
  scripts, rawtr y multi_a.
- xpub suelta: cuarto tipo, «Taproot (bc1p…)».
- QR: la cuenta Taproot de un UR (crypto-account / crypto-output) y el
  QR de texto [huella/86h/0h/0h]xpub se entregan como descriptor tr(…)
  con su suma.
- Aviso cuando la ruta del origen no casa con el tipo del descriptor.
- Simulador de gasto: el cambio de una wallet Taproot es Taproot.

Pruebas: tests/test49.js (68 casos: vectores oficiales de BIP350, BIP341
y BIP86) y 17 casos nuevos en tests/test23.js (vector de BCR-2020-015).
Las direcciones se contrastaron además con una derivación independiente
por el lado privado. 25 cambios hechos a mano para romper cada pieza: 25
cazados.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
2026-11-13 12:36:06 +01:00

397 lines
26 KiB
JavaScript

// ── QR animado: lógica pura (probada en tests/test23.js) ────────────────
// Un QR no cabe más que unos 3 KB, y una PSBT puede ocupar mucho más. Por
// eso los monederos la parten en trozos y los pasan en bucle, como una
// animación. Hay tres formas de hacerlo y Txoko lee las tres:
//
// · UR (Blockchain Commons): Sparrow, SeedSigner, Keystone, Jade,
// Passport, Krux. Trozos «ur:tipo/n-total/…» en «bytewords» (cada byte
// es una palabra de cuatro letras; en el QR van solo la primera y la
// última). A partir del trozo «total» los trozos son MEZCLAS de varios
// (códigos «fountain»): da igual cuáles se pierdan, con unos pocos más
// se reconstruye todo.
// · BBQr (Coinkite): Coldcard Q, Sparrow, Krux. Cabecera «B$», trozos
// numerados, en hexadecimal o base32, con compresión opcional.
// · Specter: «p1of3 …», trozos de texto numerados.
//
// Todo es cálculo en el navegador: nada se envía a ninguna parte. Lo que
// se reconstruye se trata igual que lo pegado (se clasifica y, si es una
// semilla o una clave privada, se rechaza).
//
// Referencias: bc-ur (C++, Blockchain Commons), BCR-2020-005/006/007/012/
// 015; BBQr (github.com/coinkite/BBQr, dominio público).
// Bytewords: los 256 «nombres» de byte, de cuatro letras cada uno.
const BYTEWORDS = "ableacidalsoapexaquaarchatomauntawayaxisbackbaldbarnbeltbetabiasbluebodybragbrewbulbbuzzcalmcashcatschefcityclawcodecolacookcostcruxcurlcuspcyandarkdatadaysdelidicedietdoordowndrawdropdrumdulldutyeacheasyechoedgeepicevenexamexiteyesfactfairfernfigsfilmfishfizzflapflewfluxfoxyfreefrogfuelfundgalagamegeargemsgiftgirlglowgoodgraygrimgurugushgyrohalfhanghardhawkheathelphighhillholyhopehornhutsicedideaidleinchinkyintoirisironitemjadejazzjoinjoltjowljudojugsjumpjunkjurykeepkenokeptkeyskickkilnkingkitekiwiknoblamblavalazyleaflegsliarlimplionlistlogoloudloveluaulucklungmainmanymathmazememomenumeowmildmintmissmonknailnavyneednewsnextnoonnotenumbobeyoboeomitonyxopenovalowlspaidpartpeckplaypluspoempoolposepuffpumapurrquadquizraceramprealredorichroadrockroofrubyruinrunsrustsafesagascarsetssilkskewslotsoapsolosongstubsurfswantacotasktaxitenttiedtimetinytoiltombtoystriptunatwinuglyundouniturgeuservastveryvetovialvibeviewvisavoidvowswallwandwarmwaspwavewaxywebswhatwhenwhizwolfworkyankyawnyellyogayurtzapszerozestzinczonezoom";
const BYTEWORDS_MIN = (() => { const m = new Map(); for (let i = 0; i < 256; i++) { const w = BYTEWORDS.slice(i * 4, i * 4 + 4); m.set(w[0] + w[3], i); } return m; })();
const CRC32_TABLA = (() => { const t = new Uint32Array(256); for (let i = 0; i < 256; i++) { let c = i; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[i] = c >>> 0; } return t; })();
function crc32QR(bytes) { let c = 0xffffffff; for (const b of bytes) c = CRC32_TABLA[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }
const u32aBytes = n => Uint8Array.of(n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255);
// Bytewords «mínimas» (2 letras por byte) → bytes, comprobando el CRC32
// de los 4 últimos bytes.
function desdeBytewords(texto) {
const s = texto.toLowerCase();
if (s.length % 2 || s.length < 10) throw new Error("UR: el texto del trozo no tiene la longitud esperada.");
const out = new Uint8Array(s.length / 2);
for (let i = 0; i < out.length; i++) {
const v = BYTEWORDS_MIN.get(s.slice(i * 2, i * 2 + 2));
if (v === undefined) throw new Error("UR: el trozo tiene letras que no son bytewords.");
out[i] = v;
}
const cuerpo = out.slice(0, -4), suma = out.slice(-4);
const c = crc32QR(cuerpo);
if (((suma[0] << 24 | suma[1] << 16 | suma[2] << 8 | suma[3]) >>> 0) !== c) throw new Error("UR: la suma de comprobación de un trozo no cuadra (lectura dañada).");
return cuerpo;
}
// CBOR mínimo (RFC 8949), lo justo para los UR: enteros, bytes, texto,
// listas, mapas, etiquetas y true/false/null. Sin decimales.
function leerCbor(bytes) {
let p = 0;
const need = n => { if (p + n > bytes.length) throw new Error("CBOR truncado."); };
const arg = (info) => {
if (info < 24) return info;
const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : info === 27 ? 8 : 0;
if (!n) throw new Error("CBOR: longitud indefinida o reservada, no admitida.");
need(n); let v = 0;
for (let i = 0; i < n; i++) v = v * 256 + bytes[p++];
if (!Number.isSafeInteger(v)) throw new Error("CBOR: número demasiado grande.");
return v;
};
const item = (prof) => {
if (prof > 32) throw new Error("CBOR demasiado anidado.");
need(1); const ib = bytes[p++], mt = ib >> 5, info = ib & 31;
if (mt === 7) {
if (info === 20) return false; if (info === 21) return true; if (info === 22 || info === 23) return null;
throw new Error("CBOR: valor simple no admitido.");
}
const v = arg(info);
if (mt === 0) return v;
if (mt === 1) return -1 - v;
if (mt === 2) { need(v); return bytes.slice(p, p += v); }
if (mt === 3) { need(v); return new TextDecoder().decode(bytes.slice(p, p += v)); }
if (mt === 4) { const a = []; for (let i = 0; i < v; i++) a.push(item(prof + 1)); return a; }
if (mt === 5) { const m = new Map(); for (let i = 0; i < v; i++) { const k = item(prof + 1); m.set(k, item(prof + 1)); } return m; }
return { tag: v, valor: item(prof + 1) }; // mt === 6
};
const r = item(0);
if (p !== bytes.length) throw new Error("CBOR: sobran bytes.");
return r;
}
// Xoshiro256** con BigInt: el generador pseudoaleatorio que decide qué
// trozos lleva cada mezcla. Tiene que ser idéntico bit a bit al de bc-ur.
function crearXoshiro(semilla32) {
const M = (1n << 64n) - 1n;
const s = [0, 1, 2, 3].map(i => { let v = 0n; for (let n = 0; n < 8; n++) v = (v << 8n) | BigInt(semilla32[i * 8 + n]); return v; });
const rotl = (x, k) => ((x << BigInt(k)) | (x >> BigInt(64 - k))) & M;
const next = () => {
const r = (rotl((s[1] * 5n) & M, 7) * 9n) & M;
const t = (s[1] << 17n) & M;
s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = rotl(s[3], 45);
return r;
};
const nextDouble = () => Number(next()) / 18446744073709551616;
const nextInt = (lo, hi) => Math.floor(nextDouble() * (hi - lo + 1)) + lo;
return { next, nextDouble, nextInt };
}
// Qué trozos originales lleva el trozo número `n` (bc-ur: choose_fragments).
function elegirFragmentos(n, total, suma) {
if (n <= total) return [n - 1];
const semilla = new Uint8Array(8); semilla.set(u32aBytes(n), 0); semilla.set(u32aBytes(suma), 4);
const rng = crearXoshiro(sha256Bytes(semilla));
// Grado (cuántos trozos se mezclan): muestreo por el método del alias,
// con probabilidades 1/i, en la variante de bc-ur.
const P = []; let suma1 = 0;
for (let i = 1; i <= total; i++) { P.push(1 / i); suma1 += 1 / i; }
for (let i = 0; i < total; i++) P[i] = P[i] * total / suma1;
const S = [], L = [];
for (let i = total - 1; i >= 0; i--) (P[i] < 1 ? S : L).push(i);
const prob = new Array(total).fill(0), alias = new Array(total).fill(0);
while (S.length && L.length) {
const a = S.pop(), g = L.pop();
prob[a] = P[a]; alias[a] = g; P[g] += P[a] - 1;
(P[g] < 1 ? S : L).push(g);
}
while (L.length) prob[L.pop()] = 1;
while (S.length) prob[S.pop()] = 1;
const r1 = rng.nextDouble(), r2 = rng.nextDouble();
const i = Math.floor(total * r1);
const grado = (r2 < prob[i] ? i : alias[i]) + 1;
const restantes = Array.from({ length: total }, (_, k) => k), barajados = [];
while (restantes.length) barajados.push(restantes.splice(rng.nextInt(0, restantes.length - 1), 1)[0]);
return barajados.slice(0, grado).sort((a, b) => a - b);
}
// Reconstrucción de un UR de varios trozos (bc-ur: FountainDecoder).
function crearDecodificadorUR() {
let clave = null, total = 0, largo = 0, suma = 0, tamFrag = 0;
const sueltos = new Map(); // índice → bytes del trozo original
let mezclas = []; // [{ idx: Set, datos }]
const vistos = new Set();
const xor = (a, b) => { const r = a.slice(); for (let i = 0; i < r.length; i++) r[i] ^= b[i]; return r; };
const reducir = (m) => {
for (const i of [...m.idx]) if (sueltos.has(i)) { m.datos = xor(m.datos, sueltos.get(i)); m.idx.delete(i); }
return m;
};
// Cola de trabajo: cada trozo nuevo puede «soltar» otros de las mezclas
// guardadas, y una mezcla contenida en otra se le resta.
const procesar = (inicial) => {
const cola = [inicial];
while (cola.length) {
let x = reducir(cola.pop());
if (x.idx.size === 0) continue;
if (x.idx.size === 1) {
const i = [...x.idx][0];
if (!sueltos.has(i)) { sueltos.set(i, x.datos); const pend = mezclas; mezclas = []; cola.push(...pend); }
continue;
}
const menor = mezclas.find(o => o.idx.size < x.idx.size && [...o.idx].every(i => x.idx.has(i)));
if (menor) { cola.push({ idx: new Set([...x.idx].filter(i => !menor.idx.has(i))), datos: xor(x.datos, menor.datos) }); continue; }
const quedan = [];
for (const o of mezclas) {
if (x.idx.size < o.idx.size && [...x.idx].every(i => o.idx.has(i))) cola.push({ idx: new Set([...o.idx].filter(i => !x.idx.has(i))), datos: xor(o.datos, x.datos) });
else quedan.push(o);
}
mezclas = quedan; mezclas.push(x);
}
};
return {
// Devuelve true si el trozo pertenece a OTRO mensaje (otro QR): quien
// llama decide si empezar de nuevo.
recibir(n, parte) {
if (!Array.isArray(parte) || parte.length !== 5) throw new Error("UR: el trozo no tiene la estructura del estándar.");
const [sn, sl, ml, cs, datos] = parte;
if (!(datos instanceof Uint8Array) || sn !== n || !(sl >= 1) || !(ml >= 1) || !datos.length) throw new Error("UR: el trozo no tiene la estructura del estándar.");
const k = `${sl}/${ml}/${cs}/${datos.length}`;
if (clave && k !== clave) return true;
// Límite de sensatez: un QR malicioso no debe poder colgar el
// navegador con millones de trozos (una PSBT normal son decenas).
if (sl > 5000 || ml > 4000000) throw new Error("UR: dice tener un tamaño desmesurado; no se lee.");
if (!clave) { clave = k; total = sl; largo = ml; suma = cs; tamFrag = datos.length; if (Math.ceil(largo / tamFrag) !== total) throw new Error("UR: los tamaños del trozo no cuadran."); }
if (vistos.has(sn)) return false;
vistos.add(sn);
procesar(reducir({ idx: new Set(elegirFragmentos(sn, total, suma)), datos }));
return false;
},
get total() { return total; },
get hechos() { return sueltos.size; },
listo() { return total > 0 && sueltos.size === total; },
mensaje() {
const out = new Uint8Array(total * tamFrag);
for (let i = 0; i < total; i++) out.set(sueltos.get(i), i * tamFrag);
const msg = out.slice(0, largo);
if (crc32QR(msg) !== suma) throw new Error("UR: el mensaje reconstruido no supera la suma de comprobación.");
return msg;
},
};
}
// ── Del contenido del UR a algo que Txoko entiende ──────────────────────
const hexDe = a => Array.from(a, b => b.toString(16).padStart(2, "0")).join("");
const base64De = a => { let s = ""; for (const b of a) s += String.fromCharCode(b); return btoa(s); };
const esPsbtBytes = b => b.length > 5 && b[0] === 0x70 && b[1] === 0x73 && b[2] === 0x62 && b[3] === 0x74 && b[4] === 0xff;
const pareceTxBytes = b => b.length > 60 && b[1] === 0 && b[2] === 0 && b[3] === 0 && b[0] >= 1 && b[0] <= 3;
const UR_SECRETOS = new Set(["crypto-seed", "seed", "crypto-bip39", "bip39", "crypto-sskr", "sskr", "crypto-eckey", "eckey", "crypto-keypair"]);
function base58CheckQR(payload) {
const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const h = sha256Bytes(sha256Bytes(payload));
const full = new Uint8Array(payload.length + 4); full.set(payload); full.set(h.slice(0, 4), payload.length);
let n = 0n; for (const b of full) n = n * 256n + BigInt(b);
let out = ""; while (n > 0n) { out = A[Number(n % 58n)] + out; n /= 58n; }
for (const b of full) { if (b !== 0) break; out = "1" + out; }
return out;
}
// Etiquetas CBOR (v1 «crypto-…» y v2 con 40000+).
const T = n => [n, n + 40000];
const esTag = (x, n) => x && typeof x === "object" && "tag" in x && T(n).includes(x.tag);
// Clave HD (crypto-hdkey, etiqueta 303) → xpub/ypub/zpub. Una clave
// PRIVADA se rechaza aunque venga dentro de una cuenta.
function hdkeyAXpub(hd, script) {
const m = hd instanceof Map ? hd : null;
if (!m) throw new Error("UR: la clave no tiene el formato del estándar.");
if (m.get(2) === true) return { secreto: true };
const key = m.get(3), cc = m.get(4);
if (!(key instanceof Uint8Array) || key.length !== 33 || !(key[0] === 2 || key[0] === 3) || !(cc instanceof Uint8Array) || cc.length !== 32)
throw new Error("UR: la clave pública o su código de cadena no tienen el tamaño del estándar.");
const uso = m.get(5); const red = uso && esTag(uso, 305) && uso.valor instanceof Map ? (uso.valor.get(2) || 0) : 0;
const ori = m.get(6); const om = ori && esTag(ori, 304) && ori.valor instanceof Map ? ori.valor : null;
const comp = om && Array.isArray(om.get(1)) ? om.get(1) : [];
const pasos = []; for (let i = 0; i + 1 < comp.length; i += 2) if (typeof comp[i] === "number") pasos.push({ i: comp[i], h: comp[i + 1] === true });
const huellaRaiz = om && typeof om.get(2) === "number" ? om.get(2) : null;
const prof = om && typeof om.get(3) === "number" ? om.get(3) : pasos.length;
const padre = typeof m.get(8) === "number" ? m.get(8) : null;
const hijo = pasos.length ? (pasos[pasos.length - 1].i + (pasos[pasos.length - 1].h ? 0x80000000 : 0)) >>> 0 : 0;
// Taproot no tiene bytes de versión propios: va como xpub/tpub corriente.
const VER = { p2wpkh: [0x04b24746, 0x045f1cf6], "p2sh-p2wpkh": [0x049d7cb2, 0x044a5262], p2pkh: [0x0488b21e, 0x043587cf], p2tr: [0x0488b21e, 0x043587cf] };
const p = new Uint8Array(78);
p.set(u32aBytes(VER[script][red ? 1 : 0]), 0); p[4] = prof & 255;
p.set(u32aBytes(padre ?? 0), 5); p.set(u32aBytes(hijo), 9); p.set(cc, 13); p.set(key, 45);
return {
valor: base58CheckQR(p),
huella: huellaRaiz != null ? hexDe(u32aBytes(huellaRaiz)) : null,
ruta: pasos.length ? "m/" + pasos.map(s => s.i + (s.h ? "'" : "")).join("/") : null,
sinPadre: padre == null && prof > 0,
};
}
// Una salida de una cuenta: wpkh(clave), sh(wpkh(clave)), pkh(clave)…
function salidaAXpub(o) {
if (esTag(o, 308)) o = o.valor; // dentro de una cuenta van envueltas en crypto-output
if (esTag(o, 404) && esTag(o.valor, 303)) return { script: "p2wpkh", ...hdkeyAXpub(o.valor.valor, "p2wpkh") };
if (esTag(o, 400) && esTag(o.valor, 404) && esTag(o.valor.valor, 303)) return { script: "p2sh-p2wpkh", ...hdkeyAXpub(o.valor.valor.valor, "p2sh-p2wpkh") };
if (esTag(o, 403) && esTag(o.valor, 303)) return { script: "p2pkh", ...hdkeyAXpub(o.valor.valor, "p2pkh") };
// Mira dentro por si hay una clave privada, para rechazarla igual.
const buscaPriv = x => !x || typeof x !== "object" ? false : x instanceof Map ? (x.get(2) === true && x.get(3) instanceof Uint8Array) || [...x.values()].some(buscaPriv) : Array.isArray(x) ? x.some(buscaPriv) : "tag" in x ? buscaPriv(x.valor) : false;
if (buscaPriv(o)) return { secreto: true };
// v2.1.0: tr(clave), Taproot de una sola clave (etiqueta 409; en el
// vector de BCR-2020-015 es la salida de la ruta m/86'/0'/0'). Si dentro
// no hay una clave HD sola (un árbol de scripts, una clave suelta), no.
if (esTag(o, 409) && esTag(o.valor, 303)) return { script: "p2tr", ...hdkeyAXpub(o.valor.valor, "p2tr") };
if (esTag(o, 409)) return { noAdmitido: "Taproot con scripts" };
if (esTag(o, 401) || (esTag(o, 400) && esTag(o.valor, 401))) return { noAdmitido: "multifirma" };
return { noAdmitido: "un tipo de script que Txoko no reconoce" };
}
const UR_PREFERENCIA = ["p2wpkh", "p2tr", "p2sh-p2wpkh", "p2pkh"];
function cuentaAXpub(c, esSalidaSola) {
const salidas = esSalidaSola ? [c] : (c instanceof Map && Array.isArray(c.get(2)) ? c.get(2) : null);
if (!salidas) throw new Error("UR: la cuenta no tiene el formato del estándar.");
const leidas = salidas.map(salidaAXpub);
if (leidas.some(l => l.secreto)) return { tipo: "secreto" };
const buena = UR_PREFERENCIA.map(s => leidas.find(l => l.script === s)).find(Boolean);
if (!buena) return { tipo: "noAdmitido", mensaje: `El QR trae una clave de cuenta de ${[...new Set(leidas.map(l => l.noAdmitido))].join(" y ")}. La auditoría de wallet de Txoko todavía no deriva ese tipo de direcciones.` };
const huella = !esSalidaSola && typeof c.get(1) === "number" ? hexDe(u32aBytes(c.get(1))) : buena.huella;
const otras = leidas.filter(l => l.valor && l !== buena).length;
// Taproot: como descriptor (ver descriptorTaprootQR), no como xpub suelta.
if (buena.script === "p2tr") return { tipo: "xpub", valor: descriptorTaprootQR(buena.valor, huella, buena.ruta), xpub: buena.valor, descriptor: true, huella, ruta: buena.ruta, script: "p2tr", sinPadre: buena.sinPadre, otras };
return { tipo: "xpub", valor: buena.valor, huella, ruta: buena.ruta, script: buena.script, sinPadre: buena.sinPadre, otras };
}
// UR completo (tipo + bytes CBOR) → resultado clasificado.
function interpretarUR(tipo, cbor) {
if (UR_SECRETOS.has(tipo)) return { tipo: "secreto" };
const v = leerCbor(cbor);
if (tipo === "crypto-psbt" || tipo === "psbt" || tipo === "bytes") {
if (!(v instanceof Uint8Array)) throw new Error("UR: el contenido no son bytes.");
if (esPsbtBytes(v)) return { tipo: "psbt", valor: base64De(v), bytes: v };
if (pareceTxBytes(v)) return { tipo: "tx", valor: hexDe(v), bytes: v };
if (tipo === "bytes") { let t = null; try { t = new TextDecoder("utf-8", { fatal: true }).decode(v); } catch {} if (t != null) return clasificarQR(t); }
return { tipo: "desconocido" };
}
if (tipo === "crypto-account" || tipo === "account-descriptor") return cuentaAXpub(v, false);
if (tipo === "crypto-output") return cuentaAXpub(v, true);
if (tipo === "crypto-hdkey" || tipo === "hdkey") {
if (v instanceof Map && v.get(2) === true) return { tipo: "secreto" };
return { tipo: "noAdmitido", mensaje: "Es una clave pública suelta sin el tipo de direcciones. Exporta la cuenta entera (en SeedSigner: Exportar Xpub)." };
}
return { tipo: "noAdmitido", mensaje: `Es un UR de tipo «${tipo}», que Txoko no usa.` };
}
// ── BBQr ────────────────────────────────────────────────────────────────
function base32Bytes(s) {
const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let bits = 0, val = 0; const out = [];
for (const ch of s) {
const i = A.indexOf(ch); if (i < 0) throw new Error("BBQr: carácter no válido en base32.");
val = (val << 5) | i; bits += 5;
if (bits >= 8) { bits -= 8; out.push((val >> bits) & 255); }
}
return Uint8Array.from(out);
}
async function inflarCrudo(bytes) {
if (typeof DecompressionStream === "undefined") throw new Error("Este navegador no sabe descomprimir el BBQr. Prueba con otro o pide al monedero el QR sin comprimir.");
// v1.48.1 (auditoría A2-07): se descomprime por trozos con un tope de
// 4 MB, el mismo que el del UR. Antes se materializaba todo de golpe: un
// QR pequeño muy comprimido podía colgar el navegador.
const MAX = 4000000;
const ds = new DecompressionStream("deflate-raw");
const lector = new Blob([bytes]).stream().pipeThrough(ds).getReader();
const trozos = []; let total = 0;
for (;;) {
const { done, value } = await lector.read();
if (done) break;
total += value.length;
if (total > MAX) { try { await lector.cancel(); } catch {} throw new Error("BBQr: al descomprimirlo supera los 4 MB; no se lee."); }
trozos.push(value);
}
const out = new Uint8Array(total); let o = 0;
for (const t of trozos) { out.set(t, o); o += t.length; }
return out;
}
// ── El colector: recibe lo que lee la cámara, trozo a trozo ─────────────
// `recibir(texto)` → { estado: "nada" | "progreso" | "listo" | "secreto" | "error", formato, hechos, total, mensaje }
// `resultado()` (async) → lo mismo que clasificarQR, ya reconstruido.
function crearColectorQR() {
let formato = null, ur = null, urTipo = null, urSimple = null, bb = null, sp = null, final = null;
const reiniciar = () => { formato = null; ur = null; urTipo = null; urSimple = null; bb = null; sp = null; final = null; };
const estado = (e, extra) => ({ estado: e, formato, ...extra });
const progreso = (hechos, total) => estado("progreso", { hechos, total });
const recibir = (texto) => {
const t = String(texto ?? "").trim();
if (final) return estado("listo");
try {
// UR
let m = t.match(/^ur:([a-z0-9-]+)\/(?:(\d+)-(\d+)\/)?([a-z]+)$/i);
if (m) {
const tipo = m[1].toLowerCase();
if (UR_SECRETOS.has(tipo)) { reiniciar(); return estado("secreto"); }
if (formato !== "ur" || (urTipo && urTipo !== tipo)) { reiniciar(); formato = "ur"; urTipo = tipo; ur = crearDecodificadorUR(); }
if (!m[2]) { urSimple = desdeBytewords(m[4]); final = true; return estado("listo"); }
const n = Number(m[2]), parte = leerCbor(desdeBytewords(m[4]));
if (ur.recibir(n, parte)) { reiniciar(); formato = "ur"; urTipo = tipo; ur = crearDecodificadorUR(); ur.recibir(n, parte); }
if (ur.listo()) { final = true; return estado("listo"); }
return progreso(ur.hechos, ur.total);
}
// BBQr: B$ + codificación + tipo + total (2, base36) + número (2, base36)
m = t.match(/^B\$([2HZ])([A-Z])([0-9A-Z]{2})([0-9A-Z]{2})(.*)$/s);
if (m) {
const [, cod, arch, tt, nn, datos] = m, total = parseInt(tt, 36), n = parseInt(nn, 36);
if (!(total >= 1) || n >= total) throw new Error("BBQr: la numeración del trozo no es válida.");
if (formato !== "bbqr" || bb.cod !== cod || bb.arch !== arch || bb.total !== total) { reiniciar(); formato = "bbqr"; bb = { cod, arch, total, partes: new Map() }; }
bb.partes.set(n, datos);
if (bb.partes.size === total) { final = true; return estado("listo"); }
return progreso(bb.partes.size, total);
}
// Specter: pNofM <trozo>
// (el trozo se toma sin recortar: un espacio al final puede ser parte
// del contenido, y perderlo podría disfrazar una semilla en palabras)
m = String(texto ?? "").replace(/^\s+/, "").replace(/[\r\n]+$/, "").match(/^p(\d+)of(\d+) (.*)$/is);
if (m) {
const n = Number(m[1]), total = Number(m[2]);
if (!(total >= 1) || n < 1 || n > total) throw new Error("Specter: la numeración del trozo no es válida.");
if (formato !== "specter" || sp.total !== total) { reiniciar(); formato = "specter"; sp = { total, partes: new Map() }; }
sp.partes.set(n, m[3]);
if (sp.partes.size === total) { final = true; return estado("listo"); }
return progreso(sp.partes.size, total);
}
return estado("nada");
} catch (e) { reiniciar(); return estado("error", { mensaje: e.message }); }
};
const resultado = async () => {
if (!final) throw new Error("Todavía faltan trozos.");
if (formato === "ur") return interpretarUR(urTipo, urSimple || ur.mensaje());
if (formato === "specter") return clasificarQR(Array.from({ length: sp.total }, (_, i) => sp.partes.get(i + 1)).join(""));
// BBQr
const trozos = Array.from({ length: bb.total }, (_, i) => bb.partes.get(i));
let bytes;
if (bb.cod === "H") {
const h = trozos.join("");
if (!/^[0-9A-Fa-f]*$/.test(h) || h.length % 2) throw new Error("BBQr: el hexadecimal no es válido.");
bytes = Uint8Array.from(h.match(/../g) || [], x => parseInt(x, 16));
} else {
bytes = base32Bytes(trozos.join(""));
if (bb.cod === "Z") bytes = await inflarCrudo(bytes);
}
if (bb.arch === "P") { if (!esPsbtBytes(bytes)) throw new Error("BBQr: dice ser una PSBT pero no lo es."); return { tipo: "psbt", valor: base64De(bytes), bytes }; }
if (bb.arch === "T") { if (!pareceTxBytes(bytes)) throw new Error("BBQr: dice ser una transacción pero no lo es."); return { tipo: "tx", valor: hexDe(bytes), bytes }; }
if (bb.arch === "U" || bb.arch === "J") { let s; try { s = new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { throw new Error("BBQr: el texto no es UTF-8 válido."); } return clasificarQR(s); }
return { tipo: "noAdmitido", mensaje: `Es un BBQr de tipo «${bb.arch}», que Txoko no usa.` };
};
return { recibir, resultado, reiniciar, get formato() { return formato; } };
}
// ── fin QR animado ──────────────────────────────────────────────────────