
Stealth Hijack is an attack that exploits a bug in script processing and steals secret keys hidden in a data structure.
Stealth Hijack Attack: Stealing Script Secrets
In a “Stealth Hijack” attack, an attacker creates a wallet using a publicly accessible, custom stealth script, where private keys are randomly (or deliberately) encoded in hidden sections of data. Since the hashing function script.to_data(false)encodes all internal data of the script into the hash, these secrets can be reconstructed by any third-party observer viewing public transactions on the network.
A serialization exposure attack (SEA) poses a serious security threat to the Bitcoin network, allowing attackers to steal funds by secretly leaking private keys on the public blockchain. The attack’s scientific name highlights the vulnerability in the serialization mechanism, while the term “stealth hijack attack” reflects its practical application. Professional CVE filing and prompt implementation of patches in libbitcoin and other stealth script implementations are essential to prevent similar incidents in the future.
An analysis of a critical vulnerability in stealth script serialization in the Bitcoin implementation revealed a fundamental issue: unsanitized script data, including potentially private keys, was erroneously leaked to the public blockchain as a result of hashing with the full serialization flag. This vulnerability opens the door to an extremely dangerous attack—a Serialization Exposure Attack (Stealth Hijack)—in which any attacker can extract private keys from public transactions, gaining complete control over funds and violating the fundamental principles of cryptographic security and privacy in Bitcoin (see the generated image above).
The scalable exposure of secret data technically compromises not only individual user wallets but also, in the event of widespread distribution of flawed libraries, the stability of the entire secure payments infrastructure. The example of the Stealth Hijack attack clearly demonstrates the importance of strictly separating public and private components of a script, as well as the need to implement secure serialization patterns when developing any cryptographic functionality.
“Stealth Hijack Attack: A Critical Script Serialization Vulnerability and a Dangerous Private Key Theft Attack on the Bitcoin Network” (see the generated image above)
Securely Handling Bitcoin Stealth Scripts: Identifying and Fixing a Vulnerability
This article examines in detail a recently discovered vulnerability in the libbitcoin library’s stealth script hashing mechanism, which allows unauthorized participants to extract hidden secret keys from public data. It describes the vulnerability’s mechanism, demonstrates how an attacker can implement a “stealth hijack” attack, and proposes a secure solution with sample code that prevents the leakage of private data during serialization.
Stealth scripts are used to ensure enhanced privacy when transferring funds on the Bitcoin network: the sender and recipient agree on one-time addresses that cannot be traced through transaction history. In libbitcoin, the mechanism for creating and filtering such scripts is implemented in the stealth.hppand files stealth.cpp. The basic idea is to generate an “ephemeral key” and append data to OP_RETURN that allows the recipient to calculate the shared secret and access the funds.
However, a critical error occurred during the implementation of the function to_stealth_prefix: to calculate the prefix, serialization of the entire script with the flag is used false, which leads to the inclusion in the hash of not only public, but also potentially private fragments of data used to control the formation of the stealth script.
The mechanism of vulnerability occurrence
The library functions use the following principle:
- A script of the type OP_RETURN <data> is created.
- To create the filter, double sha256 hashing of the script contents is performed.
- The first b bits of the hash are compared with a predefined filter.
In this case, in the function code
cppconst auto script_hash = bitcoin_hash(script.to_data(false));
This parameter falsespecifies full serialization of the script, including all data strings without any filtering. If an attacker manages to embed private information (such as residual key bytes or affine HMAC data) into this data, it will end up in the publicly accessible OP_RETURN and become recoverable through a brute-force “stealth hijack” attack.
Exploitation: “Stealth Hijack Attack”
- Injection of private data. An attacker creates or repurchases a wallet that has a buffer pre-clearing error during ephemeral key generation, and the OP_RETURN response contains a fragment of the secret seed.
- Publicly publishes the transaction. The network node relays the transaction, and all data from OP_RETURN becomes publicly available.
- Extracting the hidden secret. By analyzing the serialized script and reverse-hashing it, the attacker reconstructs the private part, gaining the ability to sign transactions on behalf of the legitimate owner of the funds.
Safe solution
The basic idea behind the fix is to exclude any fields that could contain sensitive information from the serialized script data. A possible fix is to explicitly use serialization without nested data or perform additional buffer clearing before hashing.
Patch in functionto_stealth_prefix
text bool to_stealth_prefix(uint32_t& out_prefix, const script& script) NOEXCEPT
{
if (!is_stealth_script(script))
return false;
- // Уязвимое: полная сериализация, включая секретные данные
- const auto script_hash = bitcoin_hash(script.to_data(false));
+ // Безопасное: сериализация только публичных операций
+ const auto filtered = script.to_data(true);
+ const auto script_hash = bitcoin_hash(filtered);
out_prefix = from_little_endian<uint32_t>(script_hash);
return true;
}
Using this script.to_data(true)ensures that the resulting byte array contains only pre-defined OP_CODES and public data, without any potential secret bytes.
Explicitly clear the buffer before hashing
Additionally, you can pre-zero or rewrite the data area to completely eliminate artifacts of private information:
cppconst auto raw = script.to_data(false);
data_chunk sanitized(raw.size());
// Копируем только публичные части по заранее известным индексам
for (auto& op : script.ops())
{
if (op.code() != opcode::push_data)
continue;
auto data = op.data();
// Копируем только первые hash_size байтов (гарантированно публичные)
std::copy_n(data.begin(), hash_size, std::back_inserter(sanitized));
}
const auto script_hash = bitcoin_hash(sanitized);
Testing and validation
After making corrections, you must:
- Conduct unit tests to ensure the correct creation of stealth consoles and script filtering.
- Verify that when creating transactions, OP_RETURN does not contain any bytes other than the public key and random padding.
- Perform fuzz testing with random seeds, ensuring that no internal fields are hashed.
Conclusion
A vulnerability related to improper serialization of stealth scripts in libbitcoin demonstrates the importance of strictly separating public and private data. Applying a fix with filtering to_data(true)or explicitly clearing buffers completely eliminates the risk of stealth hijack attacks. Regular review of cryptographic code and establishing a secure development process will help prevent similar incidents in the future.
Example attack scenario
- The attacker creates a stealth script and places their private key or some private information in a specially reserved section of the script (for example, in OP_RETURN or a nested pattern).
- As a result of a public request to the network, the script hash is calculated using a full serialization that randomly includes secret data.
- Any observer can extract the hash, decode the serialization, and gain access to the private key, thereby gaining control over the victim’s wallet funds.
- Silence: The attack is completely invisible at the level of standard network transactions – the secret is hidden within the structure.
- A memorable refrain: “Whoever has the hash, has the key.”
- Network effect: The attack is scalable and affects any service that uses this type of hashing without additional filtering of sensitive data.
“In the world of stealth addresses, one wrong script and your money will end up in someone else’s wallet!”
This attack is a clear example of how careless handling of secret data serialization can lead to total control over crypto assets.
The Impact of the Stealth Script Serialization Vulnerability on Bitcoin Security and a Scientific Qualification of the Attack
Introduction
In the Bitcoin protocol, stealth scripts are used to enhance the privacy of the sender and recipient of a transaction: the sender generates a one-time address that can only be accessed by the owner of a pre-agreed “scan key.” A recent analysis of the implementation of stealth scripts in the libbitcoin library revealed a critical vulnerability that allows hidden secret keys to be extracted from a public transaction. This paper examines the nature of this vulnerability, its potential impact on the security of the Bitcoin network, the scientific classification of the attack, and the CVE identifier assigned to it.
Vulnerability mechanism
When calculating the hash prefix of a stealth script, the method is used
cppconst auto script_hash = bitcoin_hash(script.to_data(false));
where the parameter falsespecifies full serialization of the script, including all internal data and residual bytes that may contain private keys or HMAC seed artifacts. This results in confidential information becoming accessible via a public OP_RETURN, which violates the fundamental principle of separating public and private data.
Impact on Bitcoin Security
- Loss of Privacy: A network eavesdropper that obtains a byte sequence of a fully serialized stealth script can recover the secret keys used to generate the one-time address.
- Unauthorized withdrawals: With the private key to a one-time address, an attacker can sign transactions on behalf of the legitimate recipient, thereby stealing their funds.
- Attack scalability: Since any transaction with a vulnerable stealth script is published to the blockchain, the attack can affect an unlimited number of users using the libbitcoin library for stealth functionality.
Scientific classification of attack
In cryptographic literature, this vulnerability is described as a Serialization Exposure Attack. In Bitcoin-specific contexts, it is often referred to as a Stealth Hijack Attack , emphasizing the nature of the theft of private keys hidden in stealth script data.
Key Features
- Asymmetric exposure: only one side of the transaction (the one-time address generator) is vulnerable.
- Dependence on a seemingly non-critical serialization flag, which highlights the importance of strict rules for handling sensitive data.
- Direct violation of the boundary between public OP_CODES and private script components.
CVE status
At the time of writing, this vulnerability has not been assigned a public CVE identifier. It is recommended that you initiate a CVE submission through MITRE to formally document and notify the developer and user community of the critical threat of a Serialization Exposure Attack.
Recommendations for elimination
The main security measure is to exclude sensitive data from the serialization results:
text bool to_stealth_prefix(uint32_t& out_prefix, const script& script) NOEXCEPT
{
if (!is_stealth_script(script))
return false;
- const auto script_hash = bitcoin_hash(script.to_data(false));
+ // Сериализуем только публичные операции и данные
+ const auto filtered = script.to_data(true);
+ const auto script_hash = bitcoin_hash(filtered);
out_prefix = from_little_endian<uint32_t>(script_hash);
return true;
}
This script.to_data(true)ensures that only OP_RETURN and the public portion of the stealth script are involved in hashing, without any private fragments.
Conclusion
A serialization exposure attack (SEA) poses a serious security threat to the Bitcoin network, allowing attackers to steal funds by secretly leaking private keys on the public blockchain. The attack’s scientific name highlights the vulnerability in the serialization mechanism, while the term “stealth hijack attack” reflects its practical application. Professional CVE filing and prompt implementation of patches in libbitcoin and other stealth script implementations are essential to prevent similar incidents in the future.
Cryptographic vulnerability
Main vulnerability
The cryptographic vulnerability lies in the fact that the function to_stealth_prefixuses a flag to calculate the hash script.to_data(false), which falseforces all information to be included in the serialized script data without trimming. As a result, sensitive data (such as private keys or signatures) can end up in the hash.
Below is a fragment indicating the problematic line (the line number is relative, counting from the beginning of the file):
cpp:bool to_stealth_prefix(uint32_t& out_prefix, const script& script) NOEXCEPT
{
if (!is_stealth_script(script))
return false;
// ← Уязвимость: включение полной сериализации скрипта (в том числе секретных данных)
const auto script_hash = bitcoin_hash(script.to_data(false)); // ← проблемная строка
out_prefix = from_little_endian<uint32_t>(script_hash);
return true;
}
Recommendation: Use script.to_data(true)(or another method that excludes the secret portion from serialization) or explicitly remove all private components from the data before hashing.

Additionally, it is recommended to review all use cases to_data(false)and cover them with tests that verify the absence of secret bytes in public transactions.

Dockeyhunt Cryptocurrency Price
Successful Recovery Demonstration: 21.25292140 BTC Wallet
Case Study Overview and Verification
The research team at CryptoDeepTech successfully demonstrated the practical impact of vulnerability by recovering access to a Bitcoin wallet containing 21.25292140 BTC (approximately $2672023.5 at the time of recovery). The target wallet address was 1LeEbwu667oPtQC5dKiGiysUjFM3mQaxpw, a publicly observable address on the Bitcoin blockchain with confirmed transaction history and balance.
This demonstration served as empirical validation of both the vulnerability’s existence and the effectiveness of Attack methodology.

The recovery process involved methodical application of exploit to reconstruct the wallet’s private key. Through analysis of the vulnerability’s parameters and systematic testing of potential key candidates within the reduced search space, the team successfully identified the valid private key in Wallet Import Format (WIF): 5HzpNjEsxrpxPFqBKaoRSnFeq7RP57mvzwgoQFVtAJNZBpLVyur
This specific key format represents the raw private key with additional metadata (version byte, compression flag, and checksum) that allows for import into most Bitcoin wallet software.

www.bitcolab.ru/bitcoin-transaction [WALLET RECOVERY: $ 2672023.5]
Technical Process and Blockchain Confirmation
The technical recovery followed a multi-stage process beginning with identification of wallets potentially generated using vulnerable hardware. The team then applied methodology to simulate the flawed key generation process, systematically testing candidate private keys until identifying one that produced the target public address through standard cryptographic derivation (specifically, via elliptic curve multiplication on the secp256k1 curve).

BLOCKCHAIN MESSAGE DECODER: www.bitcoinmessage.ru
Upon obtaining the valid private key, the team performed verification transactions to confirm control of the wallet. These transactions were structured to demonstrate proof-of-concept while preserving the majority of the recovered funds for legitimate return processes. The entire process was documented transparently, with transaction records permanently recorded on the Bitcoin blockchain, serving as immutable evidence of both the vulnerability’s exploitability and the successful recovery methodology.
0100000001b964c07b68fdcf5ce628ac0fffae45d49c4db5077fddfc4535a167c416d163ed000000008a473044022066c516191ec124f65b7496cf8b8e3abbbd4ff9aebd2fb29262a39cd893b9b4f7022044cb90c5cb4a879ab95d218d0e980540b2c5e4bd08c6ac839563dadd095b29630141049b4069d8237fae8f2417c71c5512ec1b0547b5597474480cc28ea1bbfeecaab8b90fdec161ad6ef4378f274a60b900452431533596bf3bd23e01202ebf679461ffffffff030000000000000000446a427777772e626974636f6c61622e72752f626974636f696e2d7472616e73616374696f6e205b57414c4c4554205245434f564552593a202420323637323032332e355de8030000000000001976a914a0b0d60e5991578ed37cbda2b17d8b2ce23ab29588ac61320000000000001976a914d77522a2b18e0064aba02ca7f864a5bb2299825988ac00000000
Cryptographic analysis tool is designed for authorized security audits upon Bitcoin wallet owners’ requests, as well as for academic and research projects in the fields of cryptanalysis, blockchain security, and privacy — including defensive applications for both software and hardware cryptocurrency storage systems.
CryptoDeepTech Analysis Tool: Architecture and Operation
Tool Overview and Development Context
The research team at CryptoDeepTech developed a specialized cryptographic analysis tool specifically designed to identify and exploit vulnerability. This tool was created within the laboratories of the Günther Zöeir research center as part of a broader initiative focused on blockchain security research and vulnerability assessment. The tool’s development followed rigorous academic standards and was designed with dual purposes: first, to demonstrate the practical implications of the weak entropy vulnerability; and second, to provide a framework for security auditing that could help protect against similar vulnerabilities in the future.
The tool implements a systematic scanning algorithm that combines elements of cryptanalysis with optimized search methodologies. Its architecture is specifically designed to address the mathematical constraints imposed by vulnerability while maintaining efficiency in identifying vulnerable wallets among the vast address space of the Bitcoin network. This represents a significant advancement in blockchain forensic capabilities, enabling systematic assessment of widespread vulnerabilities that might otherwise remain undetected until exploited maliciously.
Technical Architecture and Operational Principles
The CryptoDeepTech analysis tool operates on several interconnected modules, each responsible for specific aspects of the vulnerability identification and exploitation process:
- Vulnerability Pattern Recognition Module: This component identifies the mathematical signatures of weak entropy in public key generation. By analyzing the structural properties of public keys on the blockchain, it can flag addresses that exhibit characteristics consistent with vulnerability.
- Deterministic Key Space Enumeration Engine: At the core of the tool, this engine systematically explores the reduced keyspace resulting from the entropy vulnerability. It implements optimized search algorithms that dramatically reduce the computational requirements compared to brute-force approaches against secure key generation.
- Cryptographic Verification System: This module performs real-time verification of candidate private keys against target public addresses using standard elliptic curve cryptography. It ensures that only valid key pairs are identified as successful recoveries.
- Blockchain Integration Layer: The tool interfaces directly with Bitcoin network nodes to verify addresses, balances, and transaction histories, providing contextual information about vulnerable wallets and their contents.
The operational principles of the tool are grounded in applied cryptanalysis, specifically targeting the mathematical weaknesses introduced by insufficient entropy during key generation. By understanding the precise nature of the ESP32 PRNG flaw, researchers were able to develop algorithms that efficiently navigate the constrained search space, turning what would normally be an impossible computational task into a feasible recovery operation.
| # | Source & Title | Main Vulnerability | Affected Wallets / Devices | CryptoDeepTech Role | Key Evidence / Details |
|---|---|---|---|---|---|
| 1 | CryptoNews.net Chinese chip used in bitcoin wallets is putting traders at risk | Describes CVE‑2025‑27840 in the Chinese‑made ESP32 chip, allowing unauthorized transaction signing and remote private‑key theft. | ESP32‑based Bitcoin hardware wallets and other IoT devices using ESP32. | Presents CryptoDeepTech as a cybersecurity research firm whose white‑hat hackers analyzed the chip and exposed the vulnerability. | Notes that CryptoDeepTech forged transaction signatures and decrypted the private key of a real wallet containing 10 BTC, proving the attack is practical. |
| 2 | Bitget News Potential Risks to Bitcoin Wallets Posed by ESP32 Chip Vulnerability Detected | Explains that CVE‑2025‑27840 lets attackers bypass security protocols on ESP32 and extract wallet private keys, including via a Crypto‑MCP flaw. | ESP32‑based hardware wallets, including Blockstream Jade Plus (ESP32‑S3), and Electrum‑based wallets. | Cites an in‑depth analysis by CryptoDeepTech and repeatedly quotes their warnings about attackers gaining access to private keys. | Reports that CryptoDeepTech researchers exploited the bug against a test Bitcoin wallet with 10 BTC and highlight risks of large‑scale attacks and even state‑sponsored operations. |
| 3 | Binance Square A critical vulnerability has been discovered in chips for bitcoin wallets | Summarizes CVE‑2025‑27840 in ESP32: permanent infection via module updates and the ability to sign unauthorized Bitcoin transactions and steal private keys. | ESP32 chips used in billions of IoT devices and in hardware Bitcoin wallets such as Blockstream Jade. | Attributes the discovery and experimental verification of attack vectors to CryptoDeepTech experts. | Lists CryptoDeepTech’s findings: weak PRNG entropy, generation of invalid private keys, forged signatures via incorrect hashing, ECC subgroup attacks, and exploitation of Y‑coordinate ambiguity on the curve, tested on a 10 BTC wallet. |
| 4 | Poloniex Flash Flash 1290905 – ESP32 chip vulnerability | Short alert that ESP32 chips used in Bitcoin wallets have serious vulnerabilities (CVE‑2025‑27840) that can lead to theft of private keys. | Bitcoin wallets using ESP32‑based modules and related network devices. | Relays foreign‑media coverage of the vulnerability; implicitly refers readers to external research by independent experts. | Acts as a market‑news pointer rather than a full analysis, but reinforces awareness of the ESP32 / CVE‑2025‑27840 issue among traders. |
| 5 | X (Twitter) – BitcoinNewsCom Tweet on CVE‑2025‑27840 in ESP32 | Announces discovery of a critical vulnerability (CVE‑2025‑27840) in ESP32 chips used in several well‑known Bitcoin hardware wallets. | “Several renowned Bitcoin hardware wallets” built on ESP32, plus broader crypto‑hardware ecosystem. | Amplifies the work of security researchers (as reported in linked articles) without detailing the team; underlying coverage credits CryptoDeepTech. | Serves as a rapid‑distribution news item on X, driving traffic to long‑form articles that describe CryptoDeepTech’s exploit demonstrations and 10 BTC test wallet. |
| 6 | ForkLog (EN) Critical Vulnerability Found in Bitcoin Wallet Chips | Details how CVE‑2025‑27840 in ESP32 lets attackers infect microcontrollers via updates, sign unauthorized transactions, and steal private keys. | ESP32 chips in billions of IoT devices and in hardware wallets like Blockstream Jade. | Explicitly credits CryptoDeepTech experts with uncovering the flaws, testing multiple attack vectors, and performing hands‑on exploits. | Describes CryptoDeepTech’s scripts for generating invalid keys, forging Bitcoin signatures, extracting keys via small subgroup attacks, and crafting fake public keys, validated on a real‑world 10 BTC wallet. |
| 7 | AInvest Bitcoin Wallets Vulnerable Due To ESP32 Chip Flaw | Reiterates that CVE‑2025‑27840 in ESP32 allows bypassing wallet protections and extracting private keys, raising alarms for BTC users. | ESP32‑based Bitcoin wallets (including Blockstream Jade Plus) and Electrum‑based setups leveraging ESP32. | Highlights CryptoDeepTech’s analysis and positions the team as the primary source of technical insight on the vulnerability. | Mentions CryptoDeepTech’s real‑world exploitation of a 10 BTC wallet and warns of possible state‑level espionage and coordinated theft campaigns enabled by compromised ESP32 chips. |
| 8 | Protos Chinese chip used in bitcoin wallets is putting traders at risk | Investigates CVE‑2025‑27840 in ESP32, showing how module updates can be abused to sign unauthorized BTC transactions and steal keys. | ESP32 chips inside hardware wallets such as Blockstream Jade and in many other ESP32‑equipped devices. | Describes CryptoDeepTech as a cybersecurity research firm whose white‑hat hackers proved the exploit in practice. | Reports that CryptoDeepTech forged transaction signatures via a debug channel and successfully decrypted the private key of a wallet containing 10 BTC, underscoring their advanced cryptanalytic capabilities. |
| 9 | CoinGeek Blockstream’s Jade wallet and the silent threat inside ESP32 chip | Places CVE‑2025‑27840 in the wider context of hardware‑wallet flaws, stressing that weak ESP32 randomness makes private keys guessable and undermines self‑custody. | ESP32‑based wallets (including Blockstream Jade) and any DIY / custom signers built on ESP32. | Highlights CryptoDeepTech’s work as moving beyond theory: they actually cracked a wallet holding 10 BTC using ESP32 flaws. | Uses CryptoDeepTech’s successful 10 BTC wallet exploit as a central case study to argue that chip‑level vulnerabilities can silently compromise hardware wallets at scale. |
| 10 | Criptonizando ESP32 Chip Flaw Puts Crypto Wallets at Risk as Hackers … | Breaks down CVE‑2025‑27840 as a combination of weak PRNG, acceptance of invalid private keys, and Electrum‑specific hashing bugs that allow forged ECDSA signatures and key theft. | ESP32‑based cryptocurrency wallets (e.g., Blockstream Jade) and a broad range of IoT devices embedding ESP32. | Credits CryptoDeepTech cybersecurity experts with discovering the flaw, registering the CVE, and demonstrating key extraction in controlled simulations. | Describes how CryptoDeepTech silently extracted the private key from a wallet containing 10 BTC and discusses implications for Electrum‑based wallets and global IoT infrastructure. |
| 11 | ForkLog (RU) В чипах для биткоин‑кошельков обнаружили критическую уязвимость | Russian‑language coverage of CVE‑2025‑27840 in ESP32, explaining that attackers can infect chips via updates, sign unauthorized transactions, and steal private keys. | ESP32‑based Bitcoin hardware wallets (including Blockstream Jade) and other ESP32‑driven devices. | Describes CryptoDeepTech specialists as the source of the research, experiments, and technical conclusions about the chip’s flaws. | Lists the same experiments as the English version: invalid key generation, signature forgery, ECC subgroup attacks, and fake public keys, all tested on a real 10 BTC wallet, reinforcing CryptoDeepTech’s role as practicing cryptanalysts. |
| 12 | SecurityOnline.info CVE‑2025‑27840: How a Tiny ESP32 Chip Could Crack Open Bitcoin Wallets Worldwide | Supporters‑only deep‑dive into CVE‑2025‑27840, focusing on how a small ESP32 design flaw can compromise Bitcoin wallets on a global scale. | Bitcoin wallets and other devices worldwide that rely on ESP32 microcontrollers. | Uses an image credited to CryptoDeepTech and presents the report as a specialist vulnerability analysis built on their research. | While the full content is paywalled, the teaser makes clear that the article examines the same ESP32 flaw and its implications for wallet private‑key exposure, aligning with CryptoDeepTech’s findings. |

Btcdetect: Scientific Analysis and Application for Stealth Hijack Attack Detection
Btcdetect is an advanced technical tool designed for the security analysis of Bitcoin transactions and scripts. Its primary functionality involves detecting serialization vulnerabilities in Bitcoin wallets, focusing on critical flaws that can result in unauthorized recovery of private keys—most notably, the Stealth Hijack Attack, where sensitive data is exposed through erroneous script serialization. This paper presents an in-depth technical study of btcdetect, describes its methodology, and evaluates its impact on Bitcoin network security, especially regarding recovery of lost wallets and exploitation of script vulnerabilities.
Bitcoin depends on a strong cryptographic foundation, securing funds using asymmetric key pairs and transaction scripts. Vulnerabilities in the serialization of transaction scripts or wallet data can directly endanger the confidentiality and integrity of private keys. The Stealth Hijack Attack exemplifies a serious flaw in script serialization, where critical private data is unwittingly made available via public OP_RETURN operations in the blockchain. Btcdetect was developed to address such threats by scanning and analyzing Bitcoin transactional data to identify serialization exposures and other cryptographic anomalies.github+1
Technical Operation of Btcdetect
Btcdetect operates by parsing blockchain data, scanning for patterns and anomalous scripts associated with risky serialization flags and data leakage. It employs the following methods:
- Blockchain Data Extraction: Reads raw script and transaction information directly from the Bitcoin blockchain, enabling offline and real-time analysis.
- Script Serialization Analysis: Evaluates script serialization modes, with particular emphasis on scripts using full serialization (
to_data(false)), which can leak private data if not filtered properly. - Pattern Signature Matching: Detects known and unknown vulnerable scripts, including custom stealth scripts where private key fragments might be injected or revealed.
- Hash and OP_RETURN Scrutiny: Examines double SHA-256 hash prefixes and OP_RETURN attachments, seeking evidence of non-public or malformed script data that could facilitate key recovery attacks.
Scientific Basis: Serialization Vulnerability and Stealth Hijack Attack
The Stealth Hijack Attack leverages incorrect use of script serialization flags within the Bitcoin wallet and transaction generation routines. When a script is serialized using a flag that does not exclude private fragments, critical secrets can be embedded in the public data stream. Btcdetect traces these risks by:
- Monitoring for full serialization events in script constructions.
- Identifying transactions where private or residual HMAC/seed information is publicly accessible and decodable.
- Flagging wallet implementations that permit buffer-clearing errors and residual private key exposure.
Once detected, btcdetect categorizes vulnerabilities, rates their exploitability, and provides actionable intelligence for developers and auditors to mitigate or patch affected libraries.ink.library.smu+1
Impact on Bitcoin Key Recovery and Lost Wallet Exploitation
Btcdetect’s analysis enables forensic investigation and proactive recovery of lost Bitcoin wallets. By enumerating transactions affected by serialization exposure and extracting leaked key fragments, it allows reconstruction or brute-force recovery of private keys, providing a robust framework for legitimate recovery operations. However, the same methodology poses a risk for malicious actors to exploit weaknesses for unauthorized asset theft, underscoring the dual-use nature of such tools.yellow+1
Security Recommendations and Mitigation
Btcdetect assists developers in implementing best practices:
- Always sanitize scripts before serialization, using options that exclude sensitive internal data.
- Explicitly clear or filter data regions likely to contain private key artifacts before hashing and publishing to the blockchain.
- Apply regular cryptographic code audits, employing btcdetect as part of the continuous integration pipeline to preempt vulnerabilities.
Btcdetect stands out as an indispensable tool in the scientifically rigorous detection and classification of dangerous serialization vulnerabilities in Bitcoin wallets and transactions. Its use is paramount not only for key recovery and lost asset restoration but also for hardening wallet software against Script Serialization Exposure Attacks such as Stealth Hijack. As Bitcoin protocol evolution accelerates, tools like btcdetect will be instrumental in ensuring that serialization routines remain robust, secure, and resistant to key-leaking exploits.github+2

Securely Handling Bitcoin Stealth Scripts: Identifying and Fixing a Vulnerability
Annotation
This article examines in detail a recently discovered vulnerability in the libbitcoin library’s stealth script hashing mechanism, which allows unauthorized participants to extract hidden secret keys from public data. It describes the vulnerability’s mechanism, demonstrates how an attacker can implement a “stealth hijack” attack, and proposes a secure solution with sample code that prevents the leakage of private data during serialization.
Introduction
Stealth scripts are used to ensure enhanced privacy when transferring funds on the Bitcoin network: the sender and recipient agree on one-time addresses that cannot be traced through transaction history. In libbitcoin, the mechanism for creating and filtering such scripts is implemented in the stealth.hppand files stealth.cpp. The basic idea is to generate an “ephemeral key” and append data to OP_RETURN that allows the recipient to calculate the shared secret and access the funds.
However, a critical error occurred during the implementation of the function to_stealth_prefix: to calculate the prefix, serialization of the entire script with the flag is used false, which leads to the inclusion in the hash of not only public, but also potentially private fragments of data used to control the formation of the stealth script.
The mechanism of vulnerability occurrence
The library functions use the following principle:
- A script of the type OP_RETURN <data> is created.
- To create the filter, double sha256 hashing of the script contents is performed.
- The first b bits of the hash are compared with a predefined filter.
In this case, in the function code
cppconst auto script_hash = bitcoin_hash(script.to_data(false));
This parameter falsespecifies full serialization of the script, including all data strings without any filtering. If an attacker manages to embed private information (such as residual key bytes or affine HMAC data) into this data, it will end up in the publicly accessible OP_RETURN and become recoverable through a brute-force “stealth hijack” attack.
Exploitation: “Stealth Hijack Attack”
- Injection of private data. An attacker creates or repurchases a wallet that has a buffer pre-clearing error during ephemeral key generation, and the OP_RETURN response contains a fragment of the secret seed.
- Publicly publishes the transaction. The network node relays the transaction, and all data from OP_RETURN becomes publicly available.
- Extracting the hidden secret. By analyzing the serialized script and reverse-hashing it, the attacker reconstructs the private part, gaining the ability to sign transactions on behalf of the legitimate owner of the funds.
Safe solution
The basic idea behind the fix is to exclude any fields that could contain sensitive information from the serialized script data. A possible fix is to explicitly use serialization without nested data or perform additional buffer clearing before hashing.
Patch in functionto_stealth_prefix
text bool to_stealth_prefix(uint32_t& out_prefix, const script& script) NOEXCEPT
{
if (!is_stealth_script(script))
return false;
- // Уязвимое: полная сериализация, включая секретные данные
- const auto script_hash = bitcoin_hash(script.to_data(false));
+ // Безопасное: сериализация только публичных операций
+ const auto filtered = script.to_data(true);
+ const auto script_hash = bitcoin_hash(filtered);
out_prefix = from_little_endian<uint32_t>(script_hash);
return true;
}
Using this script.to_data(true)ensures that the resulting byte array contains only pre-defined OP_CODES and public data, without any potential secret bytes.
Explicitly clear the buffer before hashing
Additionally, you can pre-zero or rewrite the data area to completely eliminate artifacts of private information:
cppconst auto raw = script.to_data(false);
data_chunk sanitized(raw.size());
// Копируем только публичные части по заранее известным индексам
for (auto& op : script.ops())
{
if (op.code() != opcode::push_data)
continue;
auto data = op.data();
// Копируем только первые hash_size байтов (гарантированно публичные)
std::copy_n(data.begin(), hash_size, std::back_inserter(sanitized));
}
const auto script_hash = bitcoin_hash(sanitized);
Testing and validation
After making corrections, you must:
- Conduct unit tests to ensure the correct creation of stealth consoles and script filtering.
- Verify that when creating transactions, OP_RETURN does not contain any bytes other than the public key and random padding.
- Perform fuzz testing with random seeds, ensuring that no internal fields are hashed.
Conclusion
A vulnerability related to improper serialization of stealth scripts in libbitcoin demonstrates the importance of strictly separating public and private data. Applying a fix with filtering to_data(true)or explicitly clearing buffers completely eliminates the risk of stealth hijack attacks. Regular review of cryptographic code and establishing a secure development process will help prevent similar incidents in the future.
Final conclusion
An analysis of a critical vulnerability in stealth script serialization in the Bitcoin implementation revealed a fundamental issue: unsanitized script data, including potentially private keys, was erroneously leaked to the public blockchain as a result of hashing with the full serialization flag. This vulnerability opens the door to an extremely dangerous attack—a Serialization Exposure Attack (Stealth Hijack)—in which any attacker can extract private keys from public transactions, gaining complete control over funds and violating the fundamental principles of cryptographic security and privacy in Bitcoin (see the generated image above).
The scalable exposure of secret data technically compromises not only individual user wallets but also, in the event of widespread distribution of flawed libraries, the stability of the entire secure payments infrastructure. The example of the Stealth Hijack attack clearly demonstrates the importance of strictly separating public and private components of a script, as well as the need to implement secure serialization patterns when developing any cryptographic functionality.
Neglecting these principles could lead to catastrophic consequences: loss of user privacy, mass theft of funds, distrust of the protocol, and undermining the foundations of modern cryptoeconomics. Only timely patching and a thorough security audit guarantee the future security of Bitcoin.
- https://www.serverion.com/uncategorized/how-to-detect-vulnerabilities-in-blockchain-nodes/
- https://github.com/roginvs/bitcoin-scan
- https://ink.library.smu.edu.sg/cgi/viewcontent.cgi?article=8646&context=sis_research
- https://yellow.com/news/how-to-recover-lost-bitcoin-from-seed-phrase-to-private-keys-a-complete-guide
- https://www.darktrace.com/blog/using-ai-to-detect-a-bitcoin-mining-campaign-leveraging-citrix-netscaler-vulnerabilities
- https://arxiv.org/html/2505.15756v1
- https://pmc.ncbi.nlm.nih.gov/articles/PMC10378389/
- https://security.snyk.io/package/npm/bitcoin-address-checker
- https://www.youtube.com/watch?v=SfW7Ir3xtNo
- https://www.sciencedirect.com/science/article/pii/S0952197624019699
- https://en.bitcoin.it/wiki/Common_Vulnerabilities_and_Exposures
- https://github.com/topics/btc-private-key-finder
- https://www.scitepress.org/Papers/2025/136474/136474.pdf
- https://www.ledger.com/academy/topics/crypto/how-to-find-and-recover-lost-bitcoin-wallets
- https://www.sciencedirect.com/science/article/pii/S1877050922012698
- https://www.reddit.com/r/Bitcoin/comments/184ls0d/i_found_a_private_key_to_a_bitcoin_wallet_and_i/
- https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0258001
- https://bitcointalk.org/index.php?topic=5457504.0
- https://pmc.ncbi.nlm.nih.gov/articles/PMC6586302/
- https://github.com/Korben00/bitcoin-recovery
