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:
+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>
|
||||
|
||||
Reference in New Issue
Block a user