UTXOs a SegWit: Malleabilidad y Tarifas

SegWit reduce malleabilidad y tarifas, facilitando Lightning. Guía rápida de UTXO y scripts con ejemplo en Rust; servicios de Q2BSTUDIO.

28 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: Si trabajas con Bitcoin o Lightning en Rust es clave entender la transición de UTXOs y scripts desde las transacciones legacy a SegWit. En este artículo reviso cómo funcionan los UTXO y los scripts, los problemas de las transacciones legacy, cómo SegWit solucionó esos problemas y por qué esto es importante para Lightning Network. Además encontrarás información sobre Q2BSTUDIO, empresa especializada en desarrollo de software a medida, aplicaciones a medida, inteligencia artificial y ciberseguridad.

UTXOs y scripts: En Bitcoin cada salida sin gastar o UTXO contiene un script de bloqueo que especifica cómo puede gastarse. El emisor crea una salida que contiene la cantidad y el script de bloqueo, y el que gasta debe presentar un script de desbloqueo que satisfaga las condiciones del script de bloqueo. Este modelo hace posible construir variadas condiciones de pago utilizando primitives como OP_DUP, OP_HASH160, OP_EQUALVERIFY y OP_CHECKSIG.

Transacciones legacy P2PKH: En el esquema original P2PKH Alice gasta una salida proporcionando en la entrada un scriptSig con la firma y la clave pública. La salida de Bob contiene el hash de su clave pública. En forma resumida la entrada aporta <firma> <clavePublica> y la salida contiene OP_DUP OP_HASH160 <hashClavePublicaBob> OP_EQUALVERIFY OP_CHECKSIG. Los mineros comprueban que la clave pública de Alice al ser hasheada coincide con el hash almacenado y que la firma es válida.

Problemas de las transacciones legacy: Malleabilidad: el identificador de transacción txid incluía la firma. Si alguien modificaba ligeramente la firma el txid cambiaba, lo que rompía dependencias que necesitaban txids estables, como Lightning. Tarifas altas: las firmas y las claves públicas ocupan bytes; transacciones más grandes implican mayores tarifas.

SegWit P2WPKH: Segregated Witness trasladó la data de desbloqueo, es decir la firma y la clave pública, fuera de scriptSig hacia un nuevo campo witness. El scriptSig queda vacío o mínimo. Lo crítico es que los datos del witness no participan en el cálculo del txid, con lo que se resolvió la malleabilidad y además se aplica un descuento al tamaño efectivo de la transacción, reduciendo tarifas.

Por qué importa: SegWit solucionó malleabilidad eliminando las modificaciones del txid debidas a firmas y redujo el costo por transacción al descontar el witness. Esto permitió que soluciones de capa 2 como Lightning Network funcionen con txids estables, aumentó la capacidad por bloque y facilitó futuras mejoras como Taproot, que se apoya en SegWit.

Impacto en Lightning Network: Lightning requiere txids estables para crear compromisos fuera de cadena que luego se puedan resolver on chain si es necesario. La desaparición de la malleabilidad y la reducción de costes por transacción hicieron viable la red de micropagos y la escalabilidad de pagos instantáneos.

Ejemplo simplificado en Rust: El siguiente fragmento muestra de forma simplificada cómo difieren los cálculos de sighash para legacy y SegWit usando crates comunes sin imprimir literales de texto. Nota que los detalles prácticos requieren manejo de errores y construcción completa de la transacción.

use bitcoin::blockdata::transaction::Transaction; use bitcoin::consensus::encode::serialize; use bitcoin::util::sighash::SighashCache; use bitcoin::{Amount,EcdsaSighashType}; // firma legacy P2PKH fn sign_legacy(tx:&Transaction,input_index:usize,script_pubkey:&bitcoin::Script,value:u64,privkey:&secp256k1::SecretKey){let secp=secp256k1::Secp256k1::new();let mut cache=SighashCache::new(tx);let sighash=cache.legacy_signature_hash(input_index,script_pubkey,value,EcdsaSighashType::All).unwrap();let msg=secp256k1::Message::from_slice(&sighash).unwrap();let sig=secp.sign_ecdsa(&msg,privkey);let _=_sig_to_bytes(sig);} // firma SegWit P2WPKH fn sign_segwit(tx:&Transaction,input_index:usize,script_code:&bitcoin::Script,value:u64,privkey:&secp256k1::SecretKey){let secp=secp256k1::Secp256k1::new();let mut cache=SighashCache::new(tx);let sighash=cache.p2wpkh_signature_hash(input_index,script_code,Amount::from_sat(value),EcdsaSighashType::All).unwrap();let msg=secp256k1::Message::from_slice(&sighash[..]).unwrap();let sig=secp.sign_ecdsa(&msg,privkey);let _=_sig_to_bytes(sig);} // la implementación real debe construir la tx completa y serializar

Conclusión y servicios: Mover las firmas al witness hizo Bitcoin más seguro y económico y habilitó capas de escalado como Lightning. En Q2BSTUDIO combinamos conocimiento técnico en blockchain con experiencia en desarrollo de aplicaciones a medida para empresas. Si buscas construir soluciones financieras, integrar IA o desplegar infraestructura en la nube podemos ayudar. Ofrecemos desarrollo de software a medida y aplicaciones a medida y servicios de software a medida, además de soluciones de inteligencia artificial e ia para empresas, expertos en ciberseguridad y pentesting, servicios cloud aws y azure, servicios inteligencia de negocio y agentes IA. También trabajamos con Power BI y automatización de procesos para mejorar eficiencia y toma de decisiones.

Palabras clave: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi. Contacta con Q2BSTUDIO para diseñar soluciones seguras y escalables que aprovechen las ventajas de SegWit, Lightning y la inteligencia artificial aplicada al negocio.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.