v1.48.1: auditoría en frío, parche 3 — validaciones de formato, fuera el motor automático, transacciones reales como pruebas

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
2026-10-25 18:11:09 +01:00
co-authored by Claude Opus 5.5
parent b7856c7b91
commit a2fb0d9b94
19 changed files with 826 additions and 373 deletions
+38 -6
View File
@@ -7,6 +7,27 @@
// importes y scripts de sus entradas, así que no hace falta consultar el
// nodo. Eso significa que puedes auditar una transacción antes de firmarla
// aunque el nodo esté sincronizando — y que el nodo no se entera.
// ── Utilidades de formato (v1.48.1) ──
const MAX_SATS = 2100000000000000n;
// CompactSize de Bitcoin: 1, 3, 5 o 9 bytes. Devuelve { n, bytes } o null.
function leerCompactSize(b, pos) {
if (pos >= b.length) return null;
const x = b[pos];
if (x < 0xfd) return { n: x, bytes: 1 };
const largo = x === 0xfd ? 2 : x === 0xfe ? 4 : 8;
if (pos + 1 + largo > b.length) return null;
let v = 0n; for (let i = largo - 1; i >= 0; i--) v = (v << 8n) | BigInt(b[pos + 1 + i]);
if (v > BigInt(Number.MAX_SAFE_INTEGER)) return null;
return { n: Number(v), bytes: 1 + largo };
}
// final_scriptwitness: nº de elementos (≥1) y cada elemento con su
// longitud; tiene que ocupar exactamente el campo.
function testigoFinalValido(v) {
let pos = 0; const cab = leerCompactSize(v, pos); if (!cab || cab.n < 1) return false; pos += cab.bytes;
for (let i = 0; i < cab.n; i++) { const el = leerCompactSize(v, pos); if (!el) return false; pos += el.bytes + el.n; if (pos > v.length) return false; }
return pos === v.length;
}
function parsePsbt(bytes) {
let p = 0;
const need = (n) => { if (p + n > bytes.length) throw new Error("PSBT truncada: el archivo se acaba antes de tiempo."); };
@@ -56,7 +77,9 @@
const tx = utxRec.value; let q = 0;
const tneed=(n)=>{ if(q+n>tx.length) throw new Error("La transacción que hay dentro está truncada."); };
const tu32=()=>{ tneed(4); const v=tx[q]|(tx[q+1]<<8)|(tx[q+2]<<16)|(tx[q+3]<<24); q+=4; return v>>>0; };
const tu64=()=>{ tneed(8); let v=0n; for(let i=7;i>=0;i--) v=(v<<8n)|BigInt(tx[q+i]); q+=8; return Number(v); };
// v1.48.1 (auditoría A2-05): un importe de más de 21 millones de BTC no
// existe; antes se convertía a Number y perdía precisión en silencio.
const tu64=()=>{ tneed(8); let v=0n; for(let i=7;i>=0;i--) v=(v<<8n)|BigInt(tx[q+i]); q+=8; if (v > MAX_SATS) throw new Error("PSBT inválida: un importe de la transacción supera los 21 millones de BTC."); return Number(v); };
const tvar=()=>{ tneed(1); const v=tx[q++]; if(v<0xfd) return v; if(v===0xfd){const r=tx[q]|(tx[q+1]<<8);q+=2;return r;} if(v===0xfe) return tu32(); return tu64(); };
const ttake=(n)=>{ tneed(n); return tx.slice(q, q+=n); };
const hx=(a)=>Array.from(a).map(b=>b.toString(16).padStart(2,"0")).join("");
@@ -99,10 +122,17 @@
const d = `la entrada ${i}`;
for (const e of m) {
if (e.type === 0x01) { // witness_utxo: importe (8) + longitud + script
if (e.key.length || e.value.length < 9 || e.value[8] >= 0xfd || e.value.length !== 9 + e.value[8]) mal(d, "el importe de la moneda (witness_utxo)");
// v1.48.1 (A2-06): la longitud del script es un CompactSize, que
// puede ocupar 1, 3, 5 o 9 bytes; antes solo se aceptaba 1.
const cs = e.value.length >= 9 ? leerCompactSize(e.value, 8) : null;
if (e.key.length || !cs || e.value.length !== 8 + cs.bytes + cs.n) mal(d, "el importe de la moneda (witness_utxo)");
if (lee8(e.value) > 21e14) mal(d, "el importe de la moneda (más de 21 millones de BTC)");
}
if (e.type === 0x02 && (!esPub(e.key) || e.value.length < 9 || e.value.length > 73)) mal(d, "una firma parcial");
// v1.48.1 (A2-03): los campos de firma final tienen su estructura;
// un testigo vacío ya no cuenta como «firma final puesta».
if (e.type === 0x08 && (e.key.length || !testigoFinalValido(e.value))) mal(d, "la firma final (final_scriptwitness)");
if (e.type === 0x07 && e.key.length) mal(d, "la firma final (final_scriptSig)");
if (e.type === 0x06 && (!esPub(e.key) || e.value.length < 4 || e.value.length % 4)) mal(d, "una ruta de derivación");
if (e.type === 0x13 && (e.key.length || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "la firma Taproot");
if (e.type === 0x14 && (e.key.length !== 64 || (e.value.length !== 64 && e.value.length !== 65))) mal(d, "una firma de script Taproot");
@@ -145,7 +175,7 @@
let q = 0;
const need = n => { if (q + n > b.length) throw new Error("truncada"); };
const u32 = () => { need(4); const v = (b[q]|(b[q+1]<<8)|(b[q+2]<<16)|(b[q+3]<<24))>>>0; q += 4; return v; };
const u64 = () => { need(8); let v = 0n; for (let i = 7; i >= 0; i--) v = (v<<8n)|BigInt(b[q+i]); q += 8; return Number(v); };
const u64 = () => { need(8); let v = 0n; for (let i = 7; i >= 0; i--) v = (v<<8n)|BigInt(b[q+i]); q += 8; if (v > MAX_SATS) throw new Error("importe imposible"); return Number(v); };
const vi = () => { need(1); const v = b[q++]; if (v < 0xfd) return v; if (v === 0xfd) { need(2); const r = b[q]|(b[q+1]<<8); q += 2; return r; } if (v === 0xfe) return u32(); return u64(); };
const take = n => { need(n); return b.slice(q, q += n); };
const partes = [];
@@ -235,8 +265,8 @@
const tiposIn = new Set(psbt.inputs.map((m, i) => {
const w = m.find(e=>e.type===0x01);
if (!w) return previas[i] ? psbtScriptType(previas[i].script) : null;
const l = w.value[8];
return psbtScriptType(w.value.slice(9, 9+l));
const cs = leerCompactSize(w.value, 8);
return psbtScriptType(w.value.slice(8 + cs.bytes, 8 + cs.bytes + cs.n));
}).filter(Boolean));
const tiposOut = psbt.vout.map(o => psbtScriptType(o.script));
@@ -360,7 +390,9 @@
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" };
// Final de verdad: un testigo con al menos un elemento, o un
// scriptSig no vacío (A2-03). Un campo vacío no es una firma.
if (m.some(e => (e.type === 0x08 && testigoFinalValido(e.value)) || (e.type === 0x07 && e.value.length > 0))) 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" };
});