v1.35.0: QR animados, xpub de SeedSigner y lo firmado frente a lo auditado
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
This commit is contained in:
@@ -10,6 +10,23 @@ y el versionado sigue [Versionado Semántico](https://semver.org/lang/es/):
|
||||
- **MENOR** — características nuevas que no rompen lo anterior
|
||||
- **PARCHE** — arreglos de errores
|
||||
|
||||
---
|
||||
## [1.35.0] — 2026-10-22
|
||||
|
||||
### Añadido
|
||||
- **QR animados.** El lector junta los trozos mientras la cámara sigue abierta, con barra de progreso («7 de 12 trozos»), y no hace falta leerlos en orden. Lee los tres formatos que usan los monederos: **UR** (Sparrow, SeedSigner, Keystone, Jade, Passport, Krux), con sus códigos «fountain» —los trozos que se escapan los reponen las mezclas siguientes—; **BBQr** (Coldcard Q, Sparrow, Krux), en hexadecimal, base32 o comprimido; y el antiguo de **Specter** (`p1of3 …`). Si a mitad aparece otro QR animado, empieza de nuevo con el nuevo. Una foto suelta de un QR animado no basta y se explica.
|
||||
- **La xpub animada de SeedSigner** (UR `crypto-account`; también `crypto-output`). Se convierte en la zpub (o ypub/xpub según el tipo de cuenta) con su huella maestra y su ruta, y se ofrece para cargar la wallet. Si la cuenta solo trae Taproot o multifirma, lo dice en vez de inventar.
|
||||
- **¿Lo firmado es lo auditado?** En la auditoría de PSBT, después del análisis: lee el QR de la PSBT firmada (o pega la PSBT o la transacción final, o abre el archivo) y compara versión, locktime, monedas gastadas con su secuencia, destinos e importes con la PSBT auditada. Si algo cambia, dice qué y aconseja no difundirla; si coincide, dice qué entradas llevan firma y si ya está terminada. No verifica las firmas matemáticamente: eso lo hace el nodo al difundirla.
|
||||
- **Secretos también en los animados.** Un UR de semilla (`crypto-seed`, `crypto-bip39`, `crypto-sskr`…) se rechaza desde el primer trozo sin reconstruir nada; una cuenta con una clave privada dentro, o un texto reconstruido que es una semilla, también.
|
||||
|
||||
### Código
|
||||
- Pieza nueva `src/06-qr-animado.js` (lógica pura, sin DOM): bytewords, CRC32, CBOR mínimo, Xoshiro256**, el decodificador «fountain» de UR, BBQr, Specter, `crypto-account` → xpub y el colector que usa el lector. Escrita desde cero, sin librerías nuevas: `vendor/` no cambia.
|
||||
- `compararFirmada()` en `src/71-psbt.js`; `leerTxPrevia()` apunta además si cada entrada lleva scriptSig o testigos.
|
||||
- Pruebas en `tests/test23.js` (57 casos): los vectores oficiales de Blockchain Commons (bc-ur: CRC32, generador, elección de trozos, UR de 1 y de 9 trozos, reconstrucción solo con mezclas; BCR-2020-010/015: la cuenta de ejemplo da la zpub correcta), BBQr hecho con la implementación de referencia de Coinkite a partir de sus archivos de prueba (`tests/fixtures/qr-animado-bbqr.json`, dominio público) y la comparación de firmada y auditada.
|
||||
|
||||
### Para actualizar
|
||||
- Solo `dist/dashboard.html`. La librería del lector (`vendor/qr/`) es la misma de la v1.34.0.
|
||||
|
||||
---
|
||||
## [1.34.0] — 2026-10-22
|
||||
|
||||
|
||||
@@ -109,10 +109,11 @@ Consecuencia práctica: **el dashboard funciona sin conexión a internet**. Solo
|
||||
|
||||
**Leer QR con la cámara**
|
||||
- Botón **⌗ QR** junto a cada campo: direcciones (también los QR de pago `bitcoin:…`), txids, tu xpub/zpub (incluido el QR que muestra SeedSigner) y PSBT
|
||||
- **QR animados**: las PSBT que pasan en bucle Sparrow, SeedSigner, Keystone, Jade, Passport o Krux (UR), Coldcard Q (BBQr) y el formato antiguo de Specter, con barra de progreso. No hace falta leer los trozos en orden, y en UR los que se escapan los reponen los siguientes
|
||||
- La **xpub animada de SeedSigner** (UR `crypto-account`): se convierte en la zpub con su huella y su ruta
|
||||
- Te enseña lo leído y pide confirmar antes de rellenar nada; si el QR no encaja en ese campo, te lo dice
|
||||
- **Si lo que escaneas es una semilla o una clave privada** (SeedQR, palabras, xprv, WIF), no se muestra ni se guarda: Txoko no la necesita nunca
|
||||
- La imagen se procesa en tu navegador: no sale del aparato. Sin cámara, puedes hacer una foto o elegir una imagen
|
||||
- Los QR animados (UR, BBQr) se reconocen pero aún no se leen
|
||||
|
||||
**Auditoría de PSBT — antes de firmar**
|
||||
|
||||
@@ -123,7 +124,8 @@ pasó, esta te avisa cuando todavía puedes cambiar la transacción.
|
||||
- **Todo offline**: una PSBT ya lleva dentro los importes y scripts de sus entradas, así que no se consulta el nodo. Funciona con el nodo sincronizando
|
||||
- Avisa de las **claves públicas maestras incrustadas**: las PSBT suelen llevarlas dentro y están hechas para compartirse — quien reciba el archivo puede ver todas tus direcciones, tu saldo y tu historial. No puede gastar, pero lo ve todo
|
||||
- Detecta cambio identificable por tipo de dirección, importes redondos que delatan cuál es el pago, envíos a tu propia cartera, carteras multifirma y PSBTs incompletas
|
||||
- Acepta base64, hexadecimal o el archivo `.psbt` que exporta Sparrow
|
||||
- Acepta base64, hexadecimal, el archivo `.psbt` que exporta Sparrow o su QR (también animado)
|
||||
- **Después de firmar, comprueba que lo firmado es lo auditado**: lee el QR de la PSBT firmada que enseña SeedSigner (o la transacción final) y confirma que gasta las mismas monedas y paga lo mismo a los mismos sitios. Dice qué entradas llevan firma; no verifica las firmas matemáticamente (eso lo hace tu nodo al difundirla)
|
||||
|
||||
**Peritaje forense**
|
||||
- Rastreo de fondos robados o perdidos hacia adelante, salto a salto, desde una transacción de origen hasta un punto de parada natural (custodio identificado, dilución, CoinJoin, o fondos aún sin gastar)
|
||||
@@ -267,6 +269,7 @@ Lo que se sirve es un único archivo HTML, `dist/dashboard.html`. El código est
|
||||
```
|
||||
src/
|
||||
├── 00-04 base: formato, lo que se guarda en el navegador, temas, datos de ejemplo
|
||||
├── 05-06 QR: qué es lo leído y la reconstrucción de los QR animados (UR, BBQr, Specter)
|
||||
├── 10 índice de entidades (exchanges, lista OFAC…): casi todo datos
|
||||
├── 11-14 motor: huellas de wallet, criptografía BIP32/bech32, informe de wallet, analizador
|
||||
├── 20-22 red y caché del nodo, piezas de pantalla comunes, informe de privacidad
|
||||
@@ -278,7 +281,7 @@ src/
|
||||
└── 79-90 pestañas, Ayuda y la aplicación
|
||||
```
|
||||
|
||||
Los `.js` son lógica pura; los `.jsx` llevan pantalla. Para revisar la criptografía basta con `src/12-cripto-bip32.js` (derivación watch-only) y `src/71-psbt.js` (lectura de PSBT).
|
||||
Los `.js` son lógica pura; los `.jsx` llevan pantalla. Para revisar la criptografía basta con `src/12-cripto-bip32.js` (derivación watch-only) y `src/71-psbt.js` (lectura de PSBT); para los QR animados, `src/06-qr-animado.js`.
|
||||
|
||||
Sin bundler y sin npm: `construir.js` une las piezas con `montar.js` y las traduce con el mismo Babel que verificas al instalar. Las piezas no se importan entre sí; se leen en el orden de su número. La construcción es reproducible: el mismo código da siempre la misma huella, así que puedes comprobar que el archivo de tu nodo corresponde al código construyéndolo tú y comparando.
|
||||
|
||||
|
||||
+6
-3
@@ -42,7 +42,8 @@
|
||||
}
|
||||
if (/^lightning:|^ln(bc|tb|bcrt)\d*[a-z]?1/i.test(t)) return { tipo: "lightning" };
|
||||
// QR animados (varias partes): UR (Sparrow, SeedSigner), BBQr (Coldcard,
|
||||
// Sparrow…) y el antiguo de Specter. Se reconocen; leerlos es la fase 2.
|
||||
// Sparrow…) y el antiguo de Specter. Un trozo suelto se reconoce aquí; el
|
||||
// lector los junta con crearColectorQR (06-qr-animado.js).
|
||||
if (/^ur:/i.test(t)) { const m = t.match(/^ur:([a-z0-9-]+)\//i); return { tipo: "ur", urTipo: m ? m[1].toLowerCase() : null }; }
|
||||
if (/^B\$[2HZ][A-Z][0-9A-Z]{4}/.test(t)) return { tipo: "bbqr", archivo: t[3] };
|
||||
if (/^p\d+of\d+\s/i.test(t)) return { tipo: "specter" };
|
||||
@@ -67,20 +68,22 @@
|
||||
xpub: ["xpub"],
|
||||
psbt: ["psbt"],
|
||||
tx: ["tx"],
|
||||
firmada: ["psbt", "tx"],
|
||||
};
|
||||
const QR_NOMBRE = {
|
||||
direccion: "una dirección", txid: "un identificador de transacción (txid)", xpub: "una clave pública extendida (xpub)",
|
||||
psbt: "una PSBT", tx: "una transacción en crudo", lightning: "una factura de Lightning",
|
||||
ur: "un QR animado (UR)", bbqr: "un QR animado (BBQr)", specter: "un QR animado (Specter)",
|
||||
vacio: "un QR vacío", desconocido: "algo que Txoko no reconoce",
|
||||
vacio: "un QR vacío", desconocido: "algo que Txoko no reconoce", noAdmitido: "algo que Txoko no usa",
|
||||
};
|
||||
function encajaQR(r, campo) {
|
||||
const acepta = QR_CAMPOS[campo] || [];
|
||||
if (!r || r.tipo === "secreto") return { ok: false, mensaje: "" };
|
||||
if (acepta.includes(r.tipo)) return { ok: true, mensaje: "" };
|
||||
if (r.tipo === "noAdmitido") return { ok: false, mensaje: r.mensaje };
|
||||
const espera = acepta.map(a => QR_NOMBRE[a]).join(" o ");
|
||||
if (["ur", "bbqr", "specter"].includes(r.tipo))
|
||||
return { ok: false, mensaje: `Es ${QR_NOMBRE[r.tipo]}, de los que pasan varias imágenes seguidas. Txoko todavía no lee QR animados. Mientras tanto, guarda la PSBT como archivo y ábrela con «…o abrir archivo .psbt».` };
|
||||
return { ok: false, mensaje: `Es ${QR_NOMBRE[r.tipo]}, de los que pasan varias imágenes seguidas. Para leerlo hace falta la cámara en directo.` };
|
||||
return { ok: false, mensaje: `Has leído ${QR_NOMBRE[r.tipo] || QR_NOMBRE.desconocido}, pero aquí va ${espera}.` };
|
||||
}
|
||||
// Bytes del QR → texto. Si son 16 o 32 bytes que no son texto, es una
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
// ── 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;
|
||||
const VER = { p2wpkh: [0x04b24746, 0x045f1cf6], "p2sh-p2wpkh": [0x049d7cb2, 0x044a5262], p2pkh: [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 };
|
||||
if (esTag(o, 409)) return { noAdmitido: "Taproot (bc1p…)" };
|
||||
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", "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;
|
||||
return { tipo: "xpub", valor: buena.valor, huella, ruta: buena.ruta, script: buena.script, sinPadre: buena.sinPadre, otras: leidas.filter(l => l.valor && l !== buena).length };
|
||||
}
|
||||
|
||||
// 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.");
|
||||
const ds = new DecompressionStream("deflate-raw");
|
||||
const buf = await new Response(new Blob([bytes]).stream().pipeThrough(ds)).arrayBuffer();
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
// ── 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 ──────────────────────────────────────────────────────
|
||||
+47
-8
@@ -1,4 +1,4 @@
|
||||
// ── Leer QR con la cámara (v1.34) ─────────────────────────────────────
|
||||
// ── 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.
|
||||
@@ -40,15 +40,19 @@
|
||||
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 => {
|
||||
const procesar = texto => mostrar(clasificarQR(texto));
|
||||
const mostrar = r => {
|
||||
pararCamara();
|
||||
setAviso("");
|
||||
const r = clasificarQR(texto);
|
||||
setAviso(""); setProgreso(null);
|
||||
if (r.tipo === "secreto") { setLeido(null); setFase("secreto"); return; }
|
||||
const e = encajaQR(r, campo);
|
||||
setLeido(r);
|
||||
@@ -65,8 +69,30 @@
|
||||
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); setFase("cargando");
|
||||
setAviso(""); setLeido(null); setProgreso(null); setFase("cargando");
|
||||
colectorRef.current = crearColectorQR();
|
||||
let decode;
|
||||
try { decode = await cargarLectorQR(); }
|
||||
catch { if (vivoRef.current) setFase("sin-lector"); return; }
|
||||
@@ -91,7 +117,7 @@
|
||||
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) { procesar(t); return; }
|
||||
if (t != null && recibir(t, false)) return;
|
||||
}
|
||||
requestAnimationFrame(bucle);
|
||||
};
|
||||
@@ -114,7 +140,7 @@
|
||||
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) procesar(t);
|
||||
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.");
|
||||
@@ -149,7 +175,19 @@
|
||||
{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" && <div style={{ fontSize: "0.66rem", color: C.t2, lineHeight: 1.5 }}>Apunta al QR. La imagen no sale de este aparato.</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 }}>
|
||||
@@ -167,6 +205,7 @@
|
||||
<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>
|
||||
)}
|
||||
|
||||
+65
-3
@@ -156,13 +156,13 @@
|
||||
const vin = [];
|
||||
const nIn = vi();
|
||||
for (let i = 0; i < nIn; i++) {
|
||||
const prev = take(36); take(vi());
|
||||
vin.push({ txid: Array.from(prev.slice(0, 32)).reverse().map(x => x.toString(16).padStart(2,"0")).join(""), vout: (prev[32]|(prev[33]<<8)|(prev[34]<<16)|(prev[35]<<24))>>>0, sequence: u32() });
|
||||
const prev = take(36); const largoScriptSig = take(vi()).length;
|
||||
vin.push({ txid: Array.from(prev.slice(0, 32)).reverse().map(x => x.toString(16).padStart(2,"0")).join(""), vout: (prev[32]|(prev[33]<<8)|(prev[34]<<16)|(prev[35]<<24))>>>0, sequence: u32(), largoScriptSig, testigos: 0 });
|
||||
}
|
||||
const outs = []; const nOut = vi();
|
||||
for (let i = 0; i < nOut; i++) { const value = u64(); outs.push({ value, script: take(vi()) }); }
|
||||
partes.push(b.slice(iniCuerpo, q));
|
||||
if (segwit) for (let i = 0; i < nIn; i++) { const n = vi(); for (let j = 0; j < n; j++) take(vi()); }
|
||||
if (segwit) for (let i = 0; i < nIn; i++) { const n = vi(); vin[i].testigos = n; for (let j = 0; j < n; j++) take(vi()); }
|
||||
const iniLock = q; const locktime = u32(); partes.push(b.slice(iniLock, q));
|
||||
if (q !== b.length) throw new Error("sobran bytes");
|
||||
const sinTestigos = new Uint8Array(partes.reduce((n, x) => n + x.length, 0));
|
||||
@@ -344,3 +344,65 @@
|
||||
};
|
||||
}
|
||||
|
||||
// ── ¿Lo firmado es lo auditado? (v1.35) ─────────────────────────────────
|
||||
// Después de firmar, el monedero de firma (SeedSigner, Coldcard…) devuelve
|
||||
// la PSBT firmada o la transacción ya terminada. Aquí se compara con la
|
||||
// PSBT que se auditó: mismas monedas gastadas, mismos destinos, mismos
|
||||
// importes, mismo locktime. Si algo cambia, lo firmado NO es lo revisado.
|
||||
//
|
||||
// Qué NO hace: comprobar matemáticamente que las firmas son válidas. Dice
|
||||
// si están puestas; que sean correctas lo comprueba tu nodo al difundirla
|
||||
// (y la rechaza si no lo son).
|
||||
function compararFirmada(antes, bytes) {
|
||||
let forma, vin, vout, version, locktime, firmas, txid = null, segwit = null;
|
||||
const esPsbt = bytes.length > 5 && bytes[0]===0x70 && bytes[1]===0x73 && bytes[2]===0x62 && bytes[3]===0x74 && bytes[4]===0xff;
|
||||
if (esPsbt) {
|
||||
const p = parsePsbt(bytes);
|
||||
forma = "psbt"; ({ vin, vout, version, locktime } = p);
|
||||
firmas = p.inputs.map(m => {
|
||||
if (m.some(e => e.type === 0x07 || e.type === 0x08)) return { estado: "final" };
|
||||
const n = m.filter(e => e.type === 0x02 || e.type === 0x13 || e.type === 0x14).length;
|
||||
return n ? { estado: "firmada", n } : { estado: "sin" };
|
||||
});
|
||||
} else {
|
||||
let t;
|
||||
try { t = leerTxPrevia(bytes); }
|
||||
catch { throw new Error("Lo leído no es ni una PSBT ni una transacción completa: no se puede comparar."); }
|
||||
forma = "tx"; vin = t.vin; vout = t.outs; version = t.version; locktime = t.locktime; txid = t.txid; segwit = t.segwit;
|
||||
firmas = t.vin.map(i => (i.largoScriptSig > 0 || i.testigos > 0) ? { estado: "final" } : { estado: "sin" });
|
||||
}
|
||||
const hx = a => Array.from(a).map(b => b.toString(16).padStart(2,"0")).join("");
|
||||
const dif = [];
|
||||
if (version !== antes.version) dif.push(`La versión de la transacción cambia (${antes.version} → ${version}).`);
|
||||
if (locktime !== antes.locktime) dif.push(`El locktime cambia (${antes.locktime} → ${locktime}).`);
|
||||
if (vin.length !== antes.vin.length) dif.push(`El número de entradas cambia (${antes.vin.length} → ${vin.length}).`);
|
||||
antes.vin.forEach((a, i) => {
|
||||
const b = vin[i]; if (!b) return;
|
||||
if (a.txid !== b.txid || a.vout !== b.vout) dif.push(`La entrada ${i+1} gasta otra moneda (${a.txid.slice(0,10)}…:${a.vout} → ${b.txid.slice(0,10)}…:${b.vout}).`);
|
||||
else if (a.sequence !== b.sequence) dif.push(`La entrada ${i+1} cambia su número de secuencia (afecta a RBF o al locktime).`);
|
||||
});
|
||||
if (vout.length !== antes.vout.length) dif.push(`El número de salidas cambia (${antes.vout.length} → ${vout.length}).`);
|
||||
antes.vout.forEach((a, i) => {
|
||||
const b = vout[i]; if (!b) return;
|
||||
const mismoScript = hx(a.script) === hx(b.script);
|
||||
if (!mismoScript) dif.push(`La salida ${i+1} va a OTRO destino.`);
|
||||
if (a.value !== b.value) dif.push(`La salida ${i+1} cambia de importe (${fmtBtc(a.value)} → ${fmtBtc(b.value)}).`);
|
||||
});
|
||||
// Mismo contenido en otro orden: no es la misma transacción (otro txid),
|
||||
// aunque el dinero vaya a los mismos sitios.
|
||||
let soloOrden = false;
|
||||
if (dif.length && vin.length === antes.vin.length && vout.length === antes.vout.length && version === antes.version && locktime === antes.locktime) {
|
||||
const k = (lista, f) => lista.map(f).sort().join("|");
|
||||
soloOrden = k(antes.vin, x => `${x.txid}:${x.vout}:${x.sequence}`) === k(vin, x => `${x.txid}:${x.vout}:${x.sequence}`)
|
||||
&& k(antes.vout, x => `${x.value}:${hx(x.script)}`) === k(vout, x => `${x.value}:${hx(x.script)}`);
|
||||
}
|
||||
const finales = firmas.filter(f => f.estado === "final").length;
|
||||
const sin = firmas.filter(f => f.estado === "sin").length;
|
||||
return {
|
||||
igual: dif.length === 0, soloOrden, diferencias: dif, forma, firmas,
|
||||
todasFirmadas: sin === 0, completa: finales === firmas.length,
|
||||
sinFirmar: firmas.map((f, i) => f.estado === "sin" ? i + 1 : null).filter(Boolean),
|
||||
txid, segwit,
|
||||
};
|
||||
}
|
||||
// ── fin comparar ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -3,27 +3,20 @@
|
||||
const [input, setInput] = useState("");
|
||||
const [result, setResult] = useState(null);
|
||||
const [err, setErr] = useState(null);
|
||||
const [auditada, setAuditada] = useState(null); // la PSBT ya leída, para comparar luego con la firmada
|
||||
// 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); };
|
||||
const cambiarTexto = (v) => { setInput(v); setResult(null); setErr(null); setAuditada(null); };
|
||||
const limpiar = () => { setInput(""); setResult(null); setErr(null); setAuditada(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);
|
||||
setErr(null); setResult(null); setAuditada(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));
|
||||
const psbt = parsePsbt(bytesDeTextoPsbt(raw));
|
||||
setResult(analyzePsbt(psbt)); setAuditada(psbt);
|
||||
} catch(e) {
|
||||
setErr(e.message);
|
||||
}
|
||||
@@ -34,8 +27,8 @@
|
||||
const r = new FileReader();
|
||||
r.onload = (e) => {
|
||||
const bytes = new Uint8Array(e.target.result);
|
||||
setErr(null); setResult(null);
|
||||
try { setResult(analyzePsbt(parsePsbt(bytes))); }
|
||||
setErr(null); setResult(null); setAuditada(null);
|
||||
try { const psbt = parsePsbt(bytes); setResult(analyzePsbt(psbt)); setAuditada(psbt); }
|
||||
catch(err2) { setErr(err2.message); }
|
||||
};
|
||||
r.readAsArrayBuffer(file);
|
||||
@@ -112,6 +105,8 @@
|
||||
</div>
|
||||
))}
|
||||
|
||||
{auditada && <ComprobarFirmada key={auditada.huella} auditada={auditada}/>}
|
||||
|
||||
<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>
|
||||
@@ -121,6 +116,87 @@
|
||||
);
|
||||
}
|
||||
|
||||
// Texto pegado o leído (base64 o hexadecimal) → bytes.
|
||||
function bytesDeTextoPsbt(texto) {
|
||||
const raw = String(texto).trim().replace(/\s/g,"");
|
||||
if (/^[0-9a-fA-F]+$/.test(raw) && raw.length % 2 === 0) return new Uint8Array(raw.match(/../g).map(h=>parseInt(h,16)));
|
||||
let bin;
|
||||
try { bin = atob(raw); } catch { throw new Error("No es base64 ni hexadecimal: no se puede leer."); }
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i=0;i<bin.length;i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// ── ¿Lo firmado es lo auditado? (v1.35) ──────────────────────────────
|
||||
// Después de firmar con SeedSigner (u otro), su QR con la PSBT firmada se
|
||||
// lee aquí y se compara con la que se acaba de auditar.
|
||||
function ComprobarFirmada({ auditada }) {
|
||||
const [texto, setTexto] = useState("");
|
||||
const [res, setRes] = useState(null);
|
||||
const [err, setErr] = useState(null);
|
||||
const comparar = (bytes) => {
|
||||
setErr(null); setRes(null);
|
||||
try { setRes(compararFirmada(auditada, bytes)); } catch (e) { setErr(e.message); }
|
||||
};
|
||||
const desdeTexto = (v) => {
|
||||
setTexto(v); setRes(null); setErr(null);
|
||||
if (!v.trim()) return;
|
||||
try { comparar(bytesDeTextoPsbt(v)); } catch (e) { setErr(e.message); }
|
||||
};
|
||||
const archivo = (f) => {
|
||||
if (!f) return;
|
||||
const r = new FileReader();
|
||||
r.onload = (e) => {
|
||||
let b = new Uint8Array(e.target.result);
|
||||
// Algunos monederos guardan la PSBT o la transacción como texto.
|
||||
const t = new TextDecoder().decode(b).trim();
|
||||
if (/^(cHNidP8|70736274ff|0[1-3]000000)/i.test(t)) { try { b = bytesDeTextoPsbt(t); } catch {} }
|
||||
setTexto(""); comparar(b);
|
||||
};
|
||||
r.readAsArrayBuffer(f);
|
||||
};
|
||||
const n = auditada.vin.length;
|
||||
return (
|
||||
<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:6}}>DESPUÉS DE FIRMAR: ¿LO FIRMADO ES LO AUDITADO?</div>
|
||||
<div style={{fontSize:"0.64rem",color:C.t2,lineHeight:1.6,marginBottom:8}}>
|
||||
Cuando el monedero de firma (SeedSigner, Coldcard, Jade…) te enseñe la PSBT firmada, léela aquí antes de llevarla a Sparrow. Txoko comprueba que gasta las mismas monedas y envía lo mismo a los mismos sitios que la que acabas de revisar.
|
||||
</div>
|
||||
<div style={{display:"flex",gap:8,alignItems:"stretch",flexWrap:"wrap"}}>
|
||||
<input value={texto} onChange={e=>desdeTexto(e.target.value)} placeholder="Pega la PSBT firmada o la transacción final"
|
||||
style={{flex:"1 1 200px",minWidth:0,background:C.bgCard,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"8px 10px",color:C.t1,fontFamily:C.mono,fontSize:"0.7rem",outline:"none"}}/>
|
||||
<BotonQR campo="firmada" color={C.blue} onLeido={v=>desdeTexto(v)}/>
|
||||
<label style={{padding:"8px 12px",background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.t2,fontFamily:C.mono,fontSize:"0.66rem",cursor:"pointer",display:"flex",alignItems:"center"}}>
|
||||
archivo
|
||||
<input type="file" accept=".psbt,.txn,.txt,application/octet-stream" style={{display:"none"}} onChange={e=>{ archivo(e.target.files[0]); e.target.value=""; }}/>
|
||||
</label>
|
||||
</div>
|
||||
{err&&<div style={{marginTop:8,fontSize:"0.66rem",color:C.red,fontFamily:C.mono,lineHeight:1.6}}>{err}</div>}
|
||||
{res&&(res.igual ? (
|
||||
<div style={{marginTop:10,padding:"10px 12px",background:C.greenMuted,border:`1px solid ${C.green}40`,borderRadius:6,fontSize:"0.68rem",color:C.t1,lineHeight:1.7}}>
|
||||
<div style={{color:C.green,fontFamily:C.mono,fontWeight:700,marginBottom:4}}>✓ Es la misma transacción que has auditado</div>
|
||||
Mismas monedas, mismos destinos, mismos importes, mismo locktime.{" "}
|
||||
{res.completa
|
||||
? <>{res.forma==="tx" ? "Es la transacción final, lista para difundir" : "Todas las entradas están terminadas (firma final puesta)"}.</>
|
||||
: res.todasFirmadas
|
||||
? <>Las {n===1?"entrada lleva":`${n} entradas llevan`} firma{res.firmas.some(f=>f.n>1)?"s":""}; falta que el monedero la termine (Sparrow lo hace al cargarla).</>
|
||||
: <span style={{color:C.amber}}>Todavía {res.sinFirmar.length===1?`falta la firma de la entrada ${res.sinFirmar[0]}`:`faltan las firmas de las entradas ${res.sinFirmar.join(", ")}`}.</span>}
|
||||
{res.txid&&<div style={{marginTop:6,fontFamily:C.mono,fontSize:"0.6rem",color:C.t2,wordBreak:"break-all"}}>txid {res.txid}</div>}
|
||||
<div style={{marginTop:6,fontSize:"0.6rem",color:C.t2}}>Txoko comprueba que las firmas están, no que sean matemáticamente válidas: eso lo hace tu nodo al difundirla, y la rechaza si no lo son.</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{marginTop:10,padding:"10px 12px",background:C.redMuted,border:`1px solid ${C.red}60`,borderRadius:6,fontSize:"0.68rem",color:C.t1,lineHeight:1.7}}>
|
||||
<div style={{color:C.red,fontFamily:C.mono,fontWeight:700,marginBottom:4}}>✗ {res.soloOrden ? "Es otra transacción: mismas monedas y destinos, en otro orden" : "NO es la transacción que has auditado"}</div>
|
||||
<ul style={{margin:"4px 0 6px 18px",padding:0}}>{res.diferencias.slice(0,8).map((d,i)=><li key={i}>{d}</li>)}{res.diferencias.length>8&&<li>…y {res.diferencias.length-8} diferencias más.</li>}</ul>
|
||||
{res.soloOrden
|
||||
? "El dinero va a los mismos sitios, pero no es el archivo que revisaste. Puede deberse a que el monedero reordena; si no lo esperabas, no la difundas."
|
||||
: <strong>No la difundas.</strong>}{!res.soloOrden&&" Lo firmado no coincide con lo que revisaste: vuelve a crear la transacción en Sparrow y audítala de nuevo. Si se repite, sospecha del ordenador o del monedero."}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Decodificador Tx Raw ───────────────────────────────────────────────
|
||||
function ToolRawTx() {
|
||||
const [input, setInput] = useState("");
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@
|
||||
<footer style={{borderTop:`1px solid ${C.border}`,padding:"10px 18px",display:"flex",alignItems:"center",justifyContent:"center",gap:6}}>
|
||||
<span style={{fontSize:"0.95rem",color:C.amber}}>₿</span>
|
||||
<span style={{fontFamily:C.mono,fontSize:"0.62rem",color:C.amber,letterSpacing:"0.12em"}}>txoko</span>
|
||||
<span style={{fontFamily:C.mono,fontSize:"0.62rem",color:C.t2,letterSpacing:"0.05em"}}>· tu nodo, tus reglas · v1.34.0</span>
|
||||
<span style={{fontFamily:C.mono,fontSize:"0.62rem",color:C.t2,letterSpacing:"0.05em"}}>· tu nodo, tus reglas · v1.35.0</span>
|
||||
</footer>
|
||||
{showConfig&&<ConfigModal config={config} themeId={themeId} onTheme={switchTheme} onSave={cfg=>{setConfig(cfg);setShowConfig(false);}} onClose={()=>setShowConfig(false)}/>}
|
||||
</div>
|
||||
|
||||
@@ -33,6 +33,7 @@ node tests/test19.js # «lo más importante» y pistas del cambio
|
||||
node tests/test20.js # transacciones reales (Whirlpool, Stonewall, coinbase…) e índice de entidades
|
||||
node tests/test21.js # dirección con saldo pero sin historial (Fulcrum): no es «sin usar»
|
||||
node tests/test22.js # leer QR: qué es lo leído, si encaja y que nunca pase una semilla
|
||||
node tests/test23.js # QR animados (UR, BBQr, Specter), xpub de SeedSigner y lo firmado frente a lo auditado
|
||||
```
|
||||
|
||||
Las de criptografía también se extraen solas. `test7` lo hace por su cuenta, y
|
||||
|
||||
Vendored
+88
File diff suppressed because one or more lines are too long
+1
-1
@@ -71,7 +71,7 @@ ok("txid en el campo de búsqueda", Q.encajaQR(Q.clasificarQR(TXID), "busqueda")
|
||||
}
|
||||
{
|
||||
const e = Q.encajaQR(Q.clasificarQR("UR:CRYPTO-PSBT/1-3/LPADAXCSOEDTHY"), "psbt");
|
||||
ok("PSBT animada → se avisa de que aún no se lee y qué hacer", !e.ok && /animad/.test(e.mensaje) && /archivo/.test(e.mensaje), e.mensaje);
|
||||
ok("un trozo suelto de PSBT animada (p. ej. en una foto) → no encaja, y dice que hace falta la cámara en directo", !e.ok && /animad/.test(e.mensaje) && /cámara en directo/.test(e.mensaje), e.mensaje);
|
||||
}
|
||||
ok("xpub en el campo de wallet", Q.encajaQR(Q.clasificarQR(ZPUB), "xpub").ok);
|
||||
ok("PSBT en el campo de PSBT", Q.encajaQR(Q.clasificarQR(PSBT), "psbt").ok);
|
||||
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
// v1.35 — QR animados (UR, BBQr, Specter), la xpub animada de SeedSigner
|
||||
// y la comparación de lo firmado con lo auditado.
|
||||
//
|
||||
// Uso: node tests/test23.js
|
||||
//
|
||||
// La parte UR se prueba con los vectores oficiales de Blockchain Commons
|
||||
// (bc-ur, test/test.cpp, y BCR-2020-010/015). La parte BBQr, con trozos
|
||||
// hechos con la implementación de referencia de Coinkite a partir de sus
|
||||
// propios archivos de prueba (tests/fixtures/qr-animado-bbqr.json).
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const lines = require("./fuente.js")().split("\n");
|
||||
const cut = (desde, hasta) => {
|
||||
const s = lines.findIndex(l => l.includes(desde));
|
||||
const e = lines.findIndex((l, i) => i > s && l.includes(hasta));
|
||||
if (s === -1 || e === -1) { console.error(`No se localiza ${desde}`); process.exit(1); }
|
||||
return lines.slice(s, e).join("\n");
|
||||
};
|
||||
// Una función entera, por su sangría.
|
||||
const fn = (cabecera) => {
|
||||
const s = lines.findIndex(l => l.startsWith(cabecera));
|
||||
if (s === -1) { console.error(`No se localiza ${cabecera}`); process.exit(1); }
|
||||
const sangria = cabecera.match(/^\s*/)[0];
|
||||
const e = lines.findIndex((l, i) => i > s && l === sangria + "}");
|
||||
return lines.slice(s, e + 1).join("\n");
|
||||
};
|
||||
const Q = new Function(`
|
||||
const fmtBtc = s => (s / 1e8).toFixed(8) + " BTC";
|
||||
${fn(" function sha256Bytes(")}
|
||||
${cut("// ── QR: lógica pura", "// ── fin QR ──")}
|
||||
${cut("// ── QR animado: lógica pura", "// ── fin QR animado")}
|
||||
${cut("// ── Parser PSBT (BIP174)", "const PSBT_TIPOS")}
|
||||
${fn(" function leerTxPrevia(")}
|
||||
${cut("// ── ¿Lo firmado es lo auditado?", "// ── fin comparar")}
|
||||
return { crc32QR, crearXoshiro, elegirFragmentos, desdeBytewords, leerCbor, crearColectorQR, interpretarUR, encajaQR, clasificarQR, parsePsbt, compararFirmada, BYTEWORDS };`)();
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c && x !== undefined) console.log(" " + x); c ? pass++ : fail++; };
|
||||
const hex = a => Buffer.from(a).toString("hex");
|
||||
const igual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
// ── Utilidades de prueba: un codificador UR mínimo (para generar QR) ────────
|
||||
const sha = b => new Uint8Array(crypto.createHash("sha256").update(b).digest());
|
||||
const xoshiroDe = s => Q.crearXoshiro(sha(Buffer.from(s)));
|
||||
const mensaje = (n, semilla = "Wolf") => { const r = xoshiroDe(semilla); return Uint8Array.from({ length: n }, () => r.nextInt(0, 255)); };
|
||||
const cborCab = (mt, n) => n < 24 ? [mt << 5 | n] : n < 256 ? [mt << 5 | 24, n] : n < 65536 ? [mt << 5 | 25, n >> 8, n & 255] : [mt << 5 | 26, n >>> 24, n >> 16 & 255, n >> 8 & 255, n & 255];
|
||||
const cborBytes = b => Uint8Array.from([...cborCab(2, b.length), ...b]);
|
||||
const u32 = n => [n >>> 24, n >> 16 & 255, n >> 8 & 255, n & 255];
|
||||
const aBytewords = b => { const crc = u32(Q.crc32QR(b)); return [...b, ...crc].map(x => Q.BYTEWORDS.slice(x * 4, x * 4 + 4)).map(w => w[0] + w[3]).join(""); };
|
||||
function codificarUR(tipo, cbor, tamFrag, cuantos) {
|
||||
const total = Math.ceil(cbor.length / tamFrag), suma = Q.crc32QR(cbor);
|
||||
const frags = Array.from({ length: total }, (_, i) => { const f = new Uint8Array(tamFrag); f.set(cbor.slice(i * tamFrag, (i + 1) * tamFrag)); return f; });
|
||||
const partes = [];
|
||||
for (let n = 1; n <= cuantos; n++) {
|
||||
const datos = new Uint8Array(tamFrag);
|
||||
for (const i of Q.elegirFragmentos(n, total, suma)) for (let k = 0; k < tamFrag; k++) datos[k] ^= frags[i][k];
|
||||
const parte = Uint8Array.from([0x85, ...cborCab(0, n), ...cborCab(0, total), ...cborCab(0, cbor.length), ...cborCab(0, suma), ...cborCab(2, tamFrag), ...datos]);
|
||||
partes.push(`ur:${tipo}/${n}-${total}/${aBytewords(parte)}`);
|
||||
}
|
||||
return partes;
|
||||
}
|
||||
const recoger = async (partes) => {
|
||||
const c = Q.crearColectorQR(); let e;
|
||||
for (const p of partes) { e = c.recibir(p); if (e.estado === "listo" || e.estado === "error" || e.estado === "secreto") break; }
|
||||
return { e, r: e.estado === "listo" ? await c.resultado() : null };
|
||||
};
|
||||
|
||||
(async () => {
|
||||
console.log("=== UR: piezas básicas contra los vectores oficiales (bc-ur) ===\n");
|
||||
ok("CRC32 de «Hello, world!» = ebe6c6e6", Q.crc32QR(Buffer.from("Hello, world!")).toString(16) === "ebe6c6e6");
|
||||
ok("CRC32 de «Wolf» = 598c84dc", Q.crc32QR(Buffer.from("Wolf")).toString(16) === "598c84dc");
|
||||
{
|
||||
const r = xoshiroDe("Wolf"), v = Array.from({ length: 100 }, () => Number(r.next() % 100n));
|
||||
ok("Xoshiro256** («Wolf»): los 100 primeros números", igual(v.slice(0, 12), [42, 81, 85, 8, 82, 84, 76, 73, 70, 88, 2, 74]) && v[99] === 52 && v[50] === 1);
|
||||
const r3 = xoshiroDe("Wolf"), v3 = Array.from({ length: 100 }, () => r3.nextInt(1, 10));
|
||||
ok("Xoshiro256** next_int(1,10)", igual(v3.slice(0, 12), [6, 5, 8, 4, 10, 5, 7, 10, 4, 9, 10, 9]) && v3[99] === 5);
|
||||
const r2 = Q.crearXoshiro(sha(Uint8Array.from(u32(Q.crc32QR(Buffer.from("Wolf")))))), v2 = Array.from({ length: 8 }, () => Number(r2.next() % 100n));
|
||||
ok("Xoshiro256** sembrado con un CRC32", igual(v2, [88, 44, 94, 74, 0, 99, 7, 77]));
|
||||
ok("datos aleatorios («Wolf», 10 bytes) = 916ec65cf77cadf55cd7", hex(mensaje(10)) === "916ec65cf77cadf55cd7");
|
||||
}
|
||||
{
|
||||
const m = mensaje(1024), suma = Q.crc32QR(m), n = Math.ceil(1024 / 94); // longitud nominal 94 → 11 trozos
|
||||
const esperado = [[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[9],[2,5,6,8,9,10],[8],[1,5],[1],[0,2,4,5,8,10],[5],[2],[2],[0,1,3,4,5,7,9,10],[0,1,2,3,5,6,8,9,10],[0,2,4,5,7,8,9,10],[3,5],[4],[0,1,2,3,4,5,6,7,8,9,10],[0,1,3,4,5,6,7,9,10],[6],[5,6],[7]];
|
||||
const sale = Array.from({ length: 30 }, (_, i) => Q.elegirFragmentos(i + 1, n, suma));
|
||||
ok("qué trozos lleva cada mezcla: los 30 del vector oficial", n === 11 && igual(sale, esperado), JSON.stringify(sale.slice(12, 18)));
|
||||
}
|
||||
|
||||
console.log("\n=== UR: mensajes completos ===\n");
|
||||
const UR50 = "ur:bytes/hdeymejtswhhylkepmykhhtsytsnoyoyaxaedsuttydmmhhpktpmsrjtgwdpfnsboxgwlbaawzuefywkdplrsrjynbvygabwjldapfcsdwkbrkch";
|
||||
ok("UR de un solo trozo (vector oficial) → los 50 bytes", hex(Q.leerCbor(Q.desdeBytewords(UR50.split("/")[1]))) === hex(mensaje(50)));
|
||||
ok("…y en MAYÚSCULAS, como suele ir en el QR", hex(Q.leerCbor(Q.desdeBytewords(UR50.toUpperCase().split("/")[1]))) === hex(mensaje(50)));
|
||||
{
|
||||
const malo = UR50.slice(0, -6) + "aeaeae";
|
||||
let err = null; try { Q.desdeBytewords(malo.split("/")[1]); } catch (e) { err = e.message; }
|
||||
ok("un trozo dañado se rechaza (la suma no cuadra)", /suma de comprobación/.test(err || ""));
|
||||
}
|
||||
const UR256 = ["lpadascfadaxcywenbpljkhdcahkadaemejtswhhylkepmykhhtsytsnoyoyaxaedsuttydmmhhpktpmsrjtdkgslpgh","lpaoascfadaxcywenbpljkhdcagwdpfnsboxgwlbaawzuefywkdplrsrjynbvygabwjldapfcsgmghhkhstlrdcxaefz","lpaxascfadaxcywenbpljkhdcahelbknlkuejnbadmssfhfrdpsbiegecpasvssovlgeykssjykklronvsjksopdzmol","lpaaascfadaxcywenbpljkhdcasotkhemthydawydtaxneurlkosgwcekonertkbrlwmplssjtammdplolsbrdzcrtas","lpahascfadaxcywenbpljkhdcatbbdfmssrkzmcwnezelennjpfzbgmuktrhtejscktelgfpdlrkfyfwdajldejokbwf","lpamascfadaxcywenbpljkhdcackjlhkhybssklbwefectpfnbbectrljectpavyrolkzczcpkmwidmwoxkilghdsowp","lpatascfadaxcywenbpljkhdcavszmwnjkwtclrtvaynhpahrtoxmwvwatmedibkaegdosftvandiodagdhthtrlnnhy","lpayascfadaxcywenbpljkhdcadmsponkkbbhgsoltjntegepmttmoonftnbuoiyrehfrtsabzsttorodklubbuyaetk","lpasascfadaxcywenbpljkhdcajskecpmdckihdyhphfotjojtfmlnwmadspaxrkytbztpbauotbgtgtaeaevtgavtny","lpbkascfadaxcywenbpljkhdcahkadaemejtswhhylkepmykhhtsytsnoyoyaxaedsuttydmmhhpktpmsrjtwdkiplzs","lpbdascfadaxcywenbpljkhdcahelbknlkuejnbadmssfhfrdpsbiegecpasvssovlgeykssjykklronvsjkvetiiapk","lpbnascfadaxcywenbpljkhdcarllaluzmdmgstospeyiefmwejlwtpedamktksrvlcygmzemovovllarodtmtbnptrs","lpbtascfadaxcywenbpljkhdcamtkgtpknghchchyketwsvwgwfdhpgmgtylctotzopdrpayoschcmhplffziachrfgd","lpbaascfadaxcywenbpljkhdcapazewnvonnvdnsbyleynwtnsjkjndeoldydkbkdslgjkbbkortbelomueekgvstegt","lpbsascfadaxcywenbpljkhdcaynmhpddpzmversbdqdfyrehnqzlugmjzmnmtwmrouohtstgsbsahpawkditkckynwt","lpbeascfadaxcywenbpljkhdcawygekobamwtlihsnpalnsghenskkiynthdzotsimtojetprsttmukirlrsbtamjtpd","lpbyascfadaxcywenbpljkhdcamklgftaxykpewyrtqzhydntpnytyisincxmhtbceaykolduortotiaiaiafhiaoyce","lpbgascfadaxcywenbpljkhdcahkadaemejtswhhylkepmykhhtsytsnoyoyaxaedsuttydmmhhpktpmsrjtntwkbkwy","lpbwascfadaxcywenbpljkhdcadekicpaajootjzpsdrbalpeywllbdsnbinaerkurspbncxgslgftvtsrjtksplcpeo","lpbbascfadaxcywenbpljkhdcayapmrleeleaxpasfrtrdkncffwjyjzgyetdmlewtkpktgllepfrltataztksmhkbot"].map((b, i) => `ur:bytes/${i + 1}-9/${b}`);
|
||||
const esperado256 = hex(Uint8Array.from([0x59, 0x01, 0x00, ...mensaje(256)])); // CBOR: bytes(256)
|
||||
{
|
||||
const reconstruye = (lista) => {
|
||||
const c = Q.crearColectorQR(); let e;
|
||||
for (const p of lista) e = c.recibir(p);
|
||||
return e;
|
||||
};
|
||||
// Para comprobar el mensaje sin pasar por interpretarUR (no es PSBT ni texto),
|
||||
// se mira el CBOR: interpretarUR('bytes') sobre bytes aleatorios → desconocido.
|
||||
const e9 = reconstruye(UR256.slice(0, 9));
|
||||
ok("UR de 9 trozos (vector oficial): con los 9 primeros, listo", e9.estado === "listo");
|
||||
const c = Q.crearColectorQR(); let prog = [];
|
||||
for (const p of UR256.slice(0, 5)) prog.push(c.recibir(p));
|
||||
ok("progreso: «5 de 9»", prog[4].estado === "progreso" && prog[4].hechos === 5 && prog[4].total === 9);
|
||||
ok("un trozo repetido no cuenta dos veces", c.recibir(UR256[4]).hechos === 5);
|
||||
// Decodificador directo para mirar el mensaje
|
||||
const dec = (lista) => {
|
||||
const c2 = Q.crearColectorQR(); let e;
|
||||
for (const p of lista) { e = c2.recibir(p); if (e.estado === "listo") break; }
|
||||
return { e, c2 };
|
||||
};
|
||||
const salteados = [UR256[0], UR256[2], UR256[4], UR256[6], UR256[8], ...UR256.slice(9)];
|
||||
const { e } = dec(salteados);
|
||||
ok("faltando los trozos 2, 4, 6 y 8, las mezclas los reponen", e.estado === "listo");
|
||||
// En los trozos 10 a 20 del vector no aparece nunca el trozo original 5:
|
||||
// con ellos solos no se puede, y hay que decirlo con el progreso, no fallar.
|
||||
const sinCinco = dec(UR256.slice(9));
|
||||
ok("con las mezclas 10 a 20 (ninguna lleva el trozo 5) → sigue esperando", sinCinco.e.estado === "progreso" && sinCinco.e.hechos === 8);
|
||||
const mezclas = dec([...UR256.slice(9), UR256[4]]);
|
||||
ok("…y con el trozo 5 al final, se reconstruye todo", mezclas.e.estado === "listo");
|
||||
// El mensaje en sí: interpretamos como «bytes» → no es PSBT → desconocido, pero sin error
|
||||
ok("lo reconstruido, sin PSBT dentro, se clasifica como desconocido (sin error)", (await mezclas.c2.resultado()).tipo === "desconocido");
|
||||
// Comprobación byte a byte con un UR propio del mismo mensaje
|
||||
const propio = codificarUR("bytes", Uint8Array.from(Buffer.from(esperado256, "hex")), 29, 20);
|
||||
ok("nuestro codificador de prueba reproduce los 20 trozos oficiales", igual(propio, UR256));
|
||||
}
|
||||
|
||||
console.log("\n=== UR: PSBT animada (crypto-psbt, como Sparrow y SeedSigner) ===\n");
|
||||
const PSBT = fs.readFileSync(path.join(__dirname, "fixtures", "qr-animado-bbqr.json"), "utf8");
|
||||
const BB = JSON.parse(PSBT);
|
||||
const psbt20 = Uint8Array.from(Buffer.from(BB.psbt_2.esperado, "base64"));
|
||||
{
|
||||
const partes = codificarUR("crypto-psbt", cborBytes(psbt20), 100, 40);
|
||||
// Se empieza a mitad de la animación y se pierde uno de cada tres trozos.
|
||||
const leidos = partes.slice(5).filter((_, i) => i % 3 !== 1).map(p => p.toUpperCase());
|
||||
const { e, r } = await recoger(leidos);
|
||||
ok(`crypto-psbt de ${Math.ceil((psbt20.length + 3) / 100)} trozos, empezando a mitad y perdiendo trozos → PSBT`, e.estado === "listo" && r.tipo === "psbt" && r.valor === BB.psbt_2.esperado);
|
||||
ok("encaja en el campo de PSBT", Q.encajaQR(r, "psbt").ok);
|
||||
ok("y en el de «comprobar la firmada»", Q.encajaQR(r, "firmada").ok);
|
||||
const viejo = codificarUR("psbt", cborBytes(psbt20), 100, 20);
|
||||
ok("el tipo nuevo «psbt» (UR v2) también", (await recoger(viejo)).r?.valor === BB.psbt_2.esperado);
|
||||
const unico = `ur:crypto-psbt/${aBytewords(cborBytes(Uint8Array.from(Buffer.from(BB.psbt_H.esperado, "base64"))))}`;
|
||||
ok("crypto-psbt de un solo QR", (await recoger([unico])).r?.valor === BB.psbt_H.esperado);
|
||||
// Si a mitad de lectura aparece OTRA PSBT, se empieza de nuevo con la nueva.
|
||||
const otra = codificarUR("crypto-psbt", cborBytes(Uint8Array.from(Buffer.from(BB.psbt_Z.esperado, "base64"))), 100, 30);
|
||||
const mezcla = [...partes.slice(0, 4), ...otra];
|
||||
const m2 = await recoger(mezcla);
|
||||
ok("si cambia el QR a mitad (otra PSBT), se empieza de cero con la nueva", m2.r?.valor === BB.psbt_Z.esperado);
|
||||
}
|
||||
|
||||
console.log("\n=== UR: xpub animada (crypto-account, como SeedSigner) ===\n");
|
||||
// BCR-2020-015: cuenta #0 de «shield group erode awake lock sausage cash glare wave crew flame glove».
|
||||
const CUENTA = "ur:crypto-account/oeadcyemrewytyaolttaadeetaadmutaaddloxaxhdclaxwmfmdeiamecsdsemgtvsjzcncygrkowtrontzschgezokstswkkscfmklrtauteyaahdcxiehfonurdppfyntapejpproypegrdawkgmaewejlsfdtsrfybdehcaflmtrlbdhpamtaaddyoeadlncsdwykaeykaeykaocyemrewytyaycynlytsnyltaadeetaadmhtaadmwtaaddloxaxhdclaostvelfemdyynwydwyaievosrgmambklovabdgypdglldvespsthysadamhpmjeinaahdcxntdllnaaeykoytdacygegwhgjsiyonpywmcmrpwphsvodsrerozsbyaxluzcoxdpamtaaddyoeadlncsehykaeykaeykaocyemrewytyaycypdbskeuytaadeetaadmwtaaddloxaxhdclaxzcfxeegdrpmogrgwkbzctlttweadkiengrwlhtprremouoluutqdpfbncedkynfhaahdcxjpwevdeogthttkmeswzcolcpsaahcfnshkhtehytclmnteatmoteadtlwynnftloamtaaddyoeadlncsghykaeykaeykaocyemrewytyaycybthlvytstaadeetaadmhtaadnytaaddloxaxhdclaxhhsnhdrpftdwuocntilydibehnecmovdfekpjkclcslasbhkpawsaddmcmmnahnyaahdcxlotedtndfymyltclhlmtpfsadscnhtztaolbnnkistaedegwfmmedreetnwmcycnamtaaddyoeadlfcsdpykaocyemrewytyaycyemrewytytaadeetaadmhtaadmetaadnytaaddloxaxhdclaxdwkswmztpytnswtsecnblfbayajkdldeclqzzolrsnhljedsgminetytbnahatbyaahdcxkkguwsvyimjkvwteytwztyswvendtpmncpasfrrylprnhtkblndrgrmkoyjtbkrpamtaaddyoeadlocsdyykaeykaeykadykaocyemrewytyaycyhkrpnddrtaadeetaadmetaadnytaaddloxaxhdclaohnhffmvsbndslrfgclpfjejyatbdpebacnzokotofxntaoemvskpaowmryfnotfgaahdcxdlnbvecentssfsssgylnhkrstoytecrdlyadrekirfaybglahltalsrfcaeerobwamtaaddyoeadlocsdyykaeykaeykaoykaocyemrewytyaycyhkrpnddrtaadeetaadnltaaddloxaxhdclaorkrhkeytwsoykorletwstbwycagtbsotmeptjkesgwrfcmveskvdmngujzttgtdpaahdcxgrfgmuvyylmwcxjtttechplslgoegagaptdniatidmhdmebdwfryfsnsdkcplyvaamtaaddyoeadlncshfykaeykaeykaocyemrewytyaycytostatbngmdavolk";
|
||||
// La xpub de wpkh del vector, con los bytes de versión de zpub (04b24746).
|
||||
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||
const b58dec = s => { let n = 0n; for (const c of s) n = n * 58n + BigInt(B58.indexOf(c)); let h = n.toString(16); if (h.length % 2) h = "0" + h; return Buffer.from(h, "hex"); };
|
||||
const b58enc = b => { const h = crypto.createHash("sha256"); const c = crypto.createHash("sha256").update(h.update(b).digest()).digest().subarray(0, 4); let n = BigInt("0x" + Buffer.concat([b, c]).toString("hex")); let s = ""; while (n > 0n) { s = B58[Number(n % 58n)] + s; n /= 58n; } return s; };
|
||||
const cambiaVersion = (x, v) => { const b = b58dec(x).subarray(0, 78); return b58enc(Buffer.concat([Buffer.from(v, "hex"), b.subarray(4)])); };
|
||||
const XPUB84 = "xpub6BkU445MSEBXbPjD3g2c2ch6mn8yy1SXXQUM7EwjgYiq6Wt1NDwDZ45npqWcV8uQC5oi2gHuVukoCoZZyT4HKq8EpotPMqGqxdZRuapCQ23";
|
||||
{
|
||||
const { e, r } = await recoger([CUENTA]);
|
||||
ok("crypto-account (vector BCR-2020-015) → elige la de SegWit nativa", e.estado === "listo" && r.tipo === "xpub" && r.script === "p2wpkh");
|
||||
ok("…y da la zpub correcta", r.valor === cambiaVersion(XPUB84, "04b24746"), r.valor);
|
||||
ok("…con la huella maestra 37b5eed4 y la ruta m/84'/0'/0'", r.huella === "37b5eed4" && r.ruta === "m/84'/0'/0'");
|
||||
ok("encaja en el campo de xpub", Q.encajaQR(r, "xpub").ok);
|
||||
// Animada: la misma cuenta en trozos
|
||||
const cbor = Q.desdeBytewords(CUENTA.split("/")[1]);
|
||||
const anim = codificarUR("crypto-account", cbor, 60, 30);
|
||||
const a = await recoger(anim.slice(3));
|
||||
ok(`la misma cuenta animada (${Math.ceil(cbor.length / 60)} trozos) → misma zpub`, a.r?.valor === r.valor);
|
||||
}
|
||||
{
|
||||
// BCR-2020-010, vector 1: wpkh con una clave suelta (no HD) → no admitido, sin error.
|
||||
const r1 = (await recoger(["ur:crypto-output/taadmutaadeyoyaxhdclaoswaalbmwfpwekijndyfefzjtmdrtketphhktmngrlkwsfnospypsasrhhhjonnvwtsqzwljy"])).r;
|
||||
ok("crypto-output con una clave suelta (no HD) → «no admitido», con explicación", r1?.tipo === "noAdmitido" && r1.mensaje.length > 20, JSON.stringify(r1));
|
||||
// Vector 5 (multifirma) → no admitido
|
||||
const r5 = (await recoger(["ur:crypto-output/taadmetaadmtoeadadaolftaaddloxaxhdclaxsbsgptsolkltkndsmskiaelfhhmdimcnmnlgutzotecpsfveylgrbdhptbpsveosaahdcxhnganelacwldjnlschnyfxjyplrllfdrplpswdnbuyctlpwyfmmhgsgtwsrymtldamtaaddyoeadlaaxaeattaaddyoyadlnadwkaewklawktaaddloxaxhdclaoztnnhtwtpslgndfnwpzedrlomnclchrdfsayntlplplojznslfjejecpptlgbgwdaahdcxwtmhnyzmpkkbvdpyvwutglbeahmktyuogusnjonththhdwpsfzvdfpdlcndlkensamtaaddyoeadlfaewkaocyrycmrnvwattaaddyoyadlnaewkaewklawktdbsfttn"])).r;
|
||||
ok("crypto-output multifirma → «no admitido» (la auditoría de wallet es de una firma)", r5?.tipo === "noAdmitido" && /multifirma/.test(r5.mensaje), JSON.stringify(r5));
|
||||
// Una cuenta que solo trae Taproot
|
||||
const cb = Q.desdeBytewords(CUENTA.split("/")[1]);
|
||||
const v = Q.leerCbor(cb);
|
||||
ok("una cuenta solo con Taproot → «no admitido» con «Taproot» en el mensaje", (() => { const soloTr = new Map([[1, v.get(1)], [2, v.get(2).filter(o => o.valor.tag === 409)]]); return Q.interpretarUR("crypto-account", cborCodificar(soloTr)); })().mensaje?.includes("Taproot"));
|
||||
// Clave PRIVADA dentro de una cuenta → secreto
|
||||
const privatiza = x => x instanceof Map ? (x.has(3) ? new Map([...x, [2, true]]) : new Map([...x].map(([k, y]) => [k, privatiza(y)]))) : Array.isArray(x) ? x.map(privatiza) : x && typeof x === "object" && "tag" in x ? { tag: x.tag, valor: privatiza(x.valor) } : x;
|
||||
const conPriv = privatiza(v);
|
||||
ok("una cuenta con una clave PRIVADA dentro → secreto, no se muestra", Q.interpretarUR("crypto-account", cborCodificar(conPriv)).tipo === "secreto");
|
||||
}
|
||||
|
||||
console.log("\n=== Secretos en QR animados ===\n");
|
||||
for (const t of ["crypto-seed", "seed", "crypto-bip39", "crypto-sskr"]) {
|
||||
const c = Q.crearColectorQR();
|
||||
ok(`ur:${t} → secreto desde el primer trozo, sin reconstruir nada`, c.recibir(`ur:${t}/1-3/lpadaxcsencylobemohsgmoyadhdeynteelblrcygldwvarflojtcywyjydmylgdsa`).estado === "secreto");
|
||||
}
|
||||
{
|
||||
const frase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
|
||||
const r = (await recoger([`ur:bytes/${aBytewords(cborBytes(Buffer.from(frase)))}`])).r;
|
||||
ok("ur:bytes con una semilla en palabras → secreto", r?.tipo === "secreto");
|
||||
const enc = Buffer.from(frase).toString("base64");
|
||||
const sp = (await recoger([`p1of2 ${frase.slice(0, 40)}`, `p2of2 ${frase.slice(40)}`])).r;
|
||||
ok("Specter con una semilla en palabras → secreto", sp?.tipo === "secreto");
|
||||
}
|
||||
|
||||
{
|
||||
// Un BBQr que dice ser una transacción pero lleva una semilla en texto:
|
||||
// no se convierte en hexadecimal (que la llevaría escondida al campo).
|
||||
const frase = Buffer.from("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about").toString("hex").toUpperCase();
|
||||
let err = null; try { await recoger([`B$HT0100${frase}`]); } catch (e) { err = e.message; }
|
||||
ok("BBQr «transacción» que no lo es (una semilla en texto) → error, no hexadecimal", /no lo es/.test(err || ""));
|
||||
const c = Q.crearColectorQR();
|
||||
ok("UR que dice tener un millón de trozos → error, sin colgarse", c.recibir(`ur:bytes/1-1000000/${aBytewords(Uint8Array.from([0x85, 0x01, 0x1a, 0x00, 0x0f, 0x42, 0x40, 0x1a, 0x00, 0x0f, 0x42, 0x40, 0x00, 0x41, 0x00]))}`).estado === "error");
|
||||
}
|
||||
|
||||
console.log("\n=== BBQr (Coldcard Q, Sparrow, Krux) ===\n");
|
||||
for (const [k, nombre] of [["psbt_Z", "PSBT comprimida (Z)"], ["psbt_H", "PSBT en hexadecimal (H)"], ["psbt_2", "PSBT en base32 (2)"], ["psbt_grande_Z", "PSBT de 100 salidas (Z)"]]) {
|
||||
const partes = BB[k].partes;
|
||||
const desorden = [...partes.slice(1), partes[0], partes[1]]; // empieza a mitad, con un repetido
|
||||
const { e, r } = await recoger(desorden);
|
||||
ok(`${nombre}, ${partes.length} trozos en desorden → PSBT`, e.estado === "listo" && r.tipo === "psbt" && r.valor === BB[k].esperado, e.mensaje);
|
||||
}
|
||||
{
|
||||
const { r } = await recoger(BB.txn_Z.partes);
|
||||
ok("transacción (T, comprimida) → tx en hexadecimal", r?.tipo === "tx" && r.valor === BB.txn_Z.esperado);
|
||||
const c = Q.crearColectorQR(); const e = c.recibir(BB.psbt_Z.partes[0]);
|
||||
ok(`progreso BBQr: «1 de ${BB.psbt_Z.partes.length}»`, e.estado === "progreso" && e.hechos === 1 && e.total === BB.psbt_Z.partes.length);
|
||||
const t = await recoger(BB.texto_real.partes);
|
||||
ok(`escaneo real del repositorio BBQr (${BB.texto_real.partes.length} trozos, texto) → se lee, desconocido`, t.e.estado === "listo" && t.r.tipo === "desconocido");
|
||||
const roto = [...BB.psbt_Z.partes]; roto[2] = roto[2].slice(0, -8) + "AAAAAAAA";
|
||||
let err = null, sale = null; try { sale = (await recoger(roto)).r; } catch (x) { err = x.message; }
|
||||
ok("un BBQr comprimido dañado da error, no la PSBT buena", err !== null || sale?.valor !== BB.psbt_Z.esperado, err);
|
||||
}
|
||||
|
||||
console.log("\n=== Specter (pNofM) ===\n");
|
||||
{
|
||||
const b64 = BB.psbt_H.esperado, n = 4, tam = Math.ceil(b64.length / n);
|
||||
const partes = Array.from({ length: n }, (_, i) => `p${i + 1}of${n} ${b64.slice(i * tam, (i + 1) * tam)}`);
|
||||
const { r } = await recoger([partes[2], partes[0], partes[3], partes[1]]);
|
||||
ok("Specter de 4 trozos en desorden → PSBT", r?.tipo === "psbt" && r.valor === b64);
|
||||
}
|
||||
|
||||
console.log("\n=== Lo que no es animado no se toca ===\n");
|
||||
{
|
||||
const c = Q.crearColectorQR();
|
||||
ok("una dirección → «nada» (lo trata el lector normal)", c.recibir("bc1q8pmuc2v0cku2ty0rfxp2jyvrhv6lpsjzq9y6s8").estado === "nada");
|
||||
ok("un trozo UR con letras que no son bytewords → error", c.recibir("ur:bytes/1-3/zzzzzzzzzzzzzz").estado === "error");
|
||||
}
|
||||
|
||||
console.log("\n=== ¿Lo firmado es lo auditado? ===\n");
|
||||
{
|
||||
const antes = Q.parsePsbt(psbt20);
|
||||
const r0 = Q.compararFirmada(antes, psbt20);
|
||||
ok("la misma PSBT → igual", r0.igual && r0.forma === "psbt");
|
||||
// Una PSBT «firmada»: la misma con una firma parcial en la entrada 1.
|
||||
const firmada = conFirma(psbt20);
|
||||
const r1 = Q.compararFirmada(antes, firmada);
|
||||
ok("la misma con una firma añadida → igual, y la entrada aparece firmada", r1.igual && r1.firmas[0].estado === "firmada" && r1.todasFirmadas === (antes.vin.length === 1));
|
||||
// Cambia el importe de la salida 2
|
||||
const otra = cambiaSalida(psbt20, 1, 1000);
|
||||
const r2 = Q.compararFirmada(antes, otra);
|
||||
ok("si cambia el importe de una salida → distinta, y lo dice", !r2.igual && r2.diferencias.some(d => /salida 2 cambia de importe/.test(d)), JSON.stringify(r2.diferencias));
|
||||
// Transacción final (BBQr txn) contra una PSBT que no tiene nada que ver
|
||||
const tx = Uint8Array.from(Buffer.from(BB.txn_Z.esperado, "hex"));
|
||||
const r3 = Q.compararFirmada(antes, tx);
|
||||
ok("una transacción final que no es la auditada → distinta", r3.forma === "tx" && !r3.igual && r3.txid && r3.txid.length === 64);
|
||||
let err = null; try { Q.compararFirmada(antes, Uint8Array.of(1, 2, 3)); } catch (e) { err = e.message; }
|
||||
ok("basura → error claro", /ni una PSBT ni una transacción/.test(err || ""));
|
||||
}
|
||||
|
||||
console.log(`\n${pass} correctas, ${fail} fallidas`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
})();
|
||||
|
||||
// ── Ayudas: CBOR mínimo para fabricar casos, y PSBT retocadas ─────────────
|
||||
function cborCodificar(v) {
|
||||
const out = [];
|
||||
const w = x => {
|
||||
if (typeof x === "number") out.push(...cborCab(0, x));
|
||||
else if (typeof x === "boolean") out.push(x ? 0xf5 : 0xf4);
|
||||
else if (x instanceof Uint8Array) out.push(...cborCab(2, x.length), ...x);
|
||||
else if (Array.isArray(x)) { out.push(...cborCab(4, x.length)); x.forEach(w); }
|
||||
else if (x instanceof Map) { out.push(...cborCab(5, x.size)); for (const [k, y] of x) { w(k); w(y); } }
|
||||
else if (x && "tag" in x) { out.push(...cborCab(6, x.tag)); w(x.valor); }
|
||||
else throw new Error("no sé codificar " + typeof x);
|
||||
};
|
||||
w(v); return Uint8Array.from(out);
|
||||
}
|
||||
// Recorre una PSBT por sus mapas: devuelve [inicio, fin] de cada mapa.
|
||||
function mapas(b) {
|
||||
let p = 5; const vi = () => { const v = b[p++]; if (v < 0xfd) return v; if (v === 0xfd) { const r = b[p] | b[p + 1] << 8; p += 2; return r; } if (v === 0xfe) { const r = b.readUInt32LE(p); p += 4; return r; } throw 0; };
|
||||
b = Buffer.from(b);
|
||||
const lista = [];
|
||||
while (p < b.length) { const ini = p; for (;;) { const k = vi(); if (k === 0) break; p += k; const l = vi(); p += l; } lista.push([ini, p]); }
|
||||
return lista;
|
||||
}
|
||||
function conFirma(psbt) {
|
||||
const m = mapas(psbt); const [, finIn1] = m[1]; // fin del mapa de la entrada 1 (incluye el 0x00)
|
||||
const clave = [0x02, ...Array(33).fill(0).map((_, i) => i === 0 ? 0x02 : i)];
|
||||
const firma = [0x30, ...Array(70).fill(7)];
|
||||
const extra = [clave.length, ...clave, firma.length, ...firma];
|
||||
return Uint8Array.from([...psbt.slice(0, finIn1 - 1), ...extra, ...psbt.slice(finIn1 - 1)]);
|
||||
}
|
||||
function cambiaSalida(psbt, idx, delta) {
|
||||
// Dentro de la tx sin firmar (global 0x00). Se reconstruye con parsePsbt.
|
||||
const p = Q.parsePsbt(psbt);
|
||||
const b = Buffer.from(psbt);
|
||||
const utx = Buffer.from(p.global.find(e => e.type === 0).value);
|
||||
const pos = b.indexOf(utx);
|
||||
// localizar la salida idx en la tx
|
||||
let q = 4; const vi = () => { const v = utx[q++]; if (v < 0xfd) return v; const r = utx[q] | utx[q + 1] << 8; q += 2; return r; };
|
||||
const nIn = vi(); for (let i = 0; i < nIn; i++) { q += 36; const l = vi(); q += l + 4; }
|
||||
vi(); for (let i = 0; i < idx; i++) { q += 8; const l = vi(); q += l; }
|
||||
const v = utx.readBigUInt64LE(q) + BigInt(delta); utx.writeBigUInt64LE(v, q);
|
||||
utx.copy(b, pos);
|
||||
return Uint8Array.from(b);
|
||||
}
|
||||
Reference in New Issue
Block a user