Reentrancy Attacks: Detection Methods

Wallet Finder

October 1, 2025

Reentrancy attacks are a major threat to smart contracts. They exploit a contract's external calls to repeatedly execute malicious actions before the contract updates its state. This can drain funds or disrupt operations.

Key Points:

  • How it works: Attackers use fallback functions to re-enter vulnerable contracts during external calls.
  • Why it matters: DeFi platforms manage billions, and a single vulnerability can lead to massive losses. Example: The DAO hack in 2016 ($150M stolen).
  • Detection methods:
    • Manual reviews: Focus on risky patterns like external calls before state updates. Example: msg.sender.call.
    • Automated tools: Tools like Slither, Mythril, and Echidna analyze code for vulnerabilities.
    • Advanced techniques: Combine static and dynamic analysis, symbolic execution, and machine learning for better accuracy.
  • Prevention: Use the Checks-Effects-Interactions (CEI) pattern and tools like OpenZeppelin's nonReentrant modifier.

Quick Tip:

Integrate automated tools into your development pipeline and validate results with manual reviews for maximum security.

How To Find Smart Contract Vulnerabilities Automatically: Slither Complete Tutorial

Slither

Manual Detection Methods for Reentrancy Vulnerabilities

Manual code reviews play a critical role in spotting reentrancy vulnerabilities in smart contracts. These reviews allow developers and auditors to dive deep into the contract's logic, uncovering subtle issues that automated tools might overlook. The focus is on identifying specific risky patterns and understanding how they could be exploited.

Identifying Vulnerable Code Patterns

One of the key tasks during a manual review is identifying code patterns that make reentrancy attacks possible. A common issue is performing external calls before updating the contract's state.

Here’s an example of a vulnerable withdrawal function:

contract VulnerableContract {
    mapping(address => uint) public balances;
    function withdraw(uint _amount) public {
        require(balances[msg.sender] >= _amount, "Insufficient balance");
        // Transfer the requested amount to the caller
        (bool success, ) = msg.sender.call{value: _amount}(""); // Interaction before Effect
        require(success, "Transfer failed");
        // Update the balance only after transferring
        balances[msg.sender] -= _amount;
    }
}

This function demonstrates a classic mistake: making an external call (via msg.sender.call) before updating the user's balance. Attackers can exploit this by using a malicious fallback function that calls withdraw again before the balance is reduced.

When reviewing smart contracts manually, it’s crucial to focus on low-level calls and token callback functions. Functions like address.call{value: amount}("") or address.call() should raise immediate red flags if they aren’t protected by proper security mechanisms.

ERC token functions also deserve close attention. Some token standards include built-in external calls that attackers can exploit:

  • safeTransferFrom and _safeMint in ERC721 tokens trigger the onERC721Received hook.
  • safeTransferFrom, _mint, and _mintBatch in ERC1155 tokens invoke onERC1155Received.
  • transfer functions in ERC223, ERC777, and ERC1363 tokens often include callback mechanisms.

A real-world example of this vulnerability can be found in the HypercertMinter contract. Its _splitValue function called _mintBatch() before updating the tokenValues[_tokenID] state variable, allowing attackers to exploit the onERC1155BatchReceived() hook and mint excessive fractions for the same token ID.

Another tricky issue is cross-function and cross-contract reentrancy. These vulnerabilities occur when multiple functions share the same state variables. If an external call in one function leaves a shared state temporarily inconsistent, attackers can exploit other functions relying on that state. For example, the QuickNode vulnerability involved interactions between withdrawalAll() and transfer() functions, which shared state variables and created an opening for reentrancy attacks.

Using the Checks-Effects-Interactions Pattern

The Checks-Effects-Interactions (CEI) pattern is a valuable tool for both detecting and preventing reentrancy vulnerabilities. It provides a clear framework for structuring secure functions.

"Reentrancy vulnerabilities typically stem from the violation of the secure Check-Effect-Interaction (C-E-I) pattern, with attackers exploiting the smart contract's fallback mechanism." - Zexu Wang et al., Sun Yat-sen University / Peng Cheng Laboratory

The CEI pattern breaks down function logic into three steps:

  • Checks: Validate all conditions and permissions before proceeding.
  • Effects: Update internal state variables, such as balances or contract status.
  • Interactions: Perform external calls, send Ether, or trigger other contracts.

Here’s an example of a secure withdrawal function following the CEI pattern:

function secureWithdraw(uint _amount) public {
    // CHECKS: Validate conditions
    require(balances[msg.sender] >= _amount, "Insufficient balance");
    require(_amount > 0, "Amount must be positive");

    // EFFECTS: Update state first
    balances[msg.sender] -= _amount;

    // INTERACTIONS: External calls last
    (bool success, ) = msg.sender.call{value: _amount}("");
    require(success, "Transfer failed");
}

Functions that perform external interactions before updating state should be flagged for further review. As Ciara Nightingale explains, "Reentrancy is a state synchronization problem occurring when the state is not updated before making an external call".

Limitations of Manual Code Reviews

While manual reviews are incredibly useful, they aren’t perfect. Human error is a major limitation - auditors can overlook subtle vulnerabilities, especially in large or complex codebases.

Modern DeFi protocols often involve multiple interconnected contracts, making it hard to manually trace all possible execution paths. For example, the QuickNode case highlighted how cross-function interactions could create vulnerabilities that weren’t immediately obvious.

Additionally, attackers are constantly developing new techniques, which means manual reviewers must stay up-to-date with the latest attack methods. Early cross-contract reentrancy attacks caught many auditors by surprise because they were primarily focused on single-contract vulnerabilities.

Despite these challenges, manual reviews remain an essential part of a strong security strategy. They are particularly effective for uncovering complex logic issues and interaction patterns that automated tools might miss. However, to achieve the best results, manual reviews should be combined with automated tools for a more thorough analysis. Together, these methods provide a stronger defense against reentrancy vulnerabilities.

Automated Tools for Detecting Reentrancy Attacks

Manual reviews are invaluable for in-depth insights, but automated tools bring speed and scalability to the table. These tools can analyze large codebases in just minutes, making them an essential part of modern smart contract development. Still, knowing their strengths and limitations is key to using them effectively.

Automated tools for reentrancy detection take different approaches, each offering unique benefits. Some rely on static analysis, which examines the code without running it, while others use symbolic execution to simulate execution paths and uncover vulnerabilities.

  • Slither: A widely-used static analysis tool with over 90 detectors. It’s particularly effective at spotting vulnerabilities like reentrancy, identifying 18 issues during tests.
  • Mythril: Combines symbolic execution, dynamic analysis, and static analysis. It examines EVM bytecode and uses techniques like SMT solving and taint analysis to detect vulnerabilities. Tests showed it identified 14 vulnerabilities. Its commercial version, MythX, can detect over 150 types of vulnerabilities and delivers results in under a minute for most contracts.
  • Echidna: A fuzzing tool that generates inputs to test how contracts behave under extreme conditions. It ensures invariants hold, making it a great choice for high-risk projects.
  • Diligence Fuzzing: Developed by ConsenSys, this tool achieves broad code coverage and integrates with Scribble for specifying contract behavior. It uses Harvey fuzzers for thorough EVM bytecode analysis.
  • SliSE: A specialized tool that pairs program slicing with symbolic execution. It achieved an impressive F1 score of 78.65% in reentrancy detection, far surpassing other tools that often score below 30%.
  • AWDNN: A machine learning-based tool using an attention mechanism to spot vulnerabilities. It optimizes smart contract code by removing unnecessary parts before analysis.

These tools are shaping the way developers approach security, making it easier to incorporate advanced detection methods into their workflows.

How to Use Automated Tools

Automated tools can be integrated into various stages of development, offering flexibility and real-time feedback.

  • CI/CD Integration: Tools like MythX can be added to GitHub Actions workflows. For example, a .github/workflows/security-analysis.yml file can be set up to analyze code on every push or pull request. This setup compiles contracts, runs mythx analyze contracts/, and flags any critical issues.
  • Custom Integration: Developers using Hardhat can create custom tasks, like mythx-analyze, to compile contracts, submit them for analysis, and report any critical vulnerabilities. This can also be configured to halt builds if severe issues are found.
  • Real-Time Monitoring: Some tools can continuously monitor contracts in DAO governance systems, analyzing key files like Governor.sol or Treasury.sol. If high-severity vulnerabilities are detected, these systems can notify security teams or even pause proposals to prevent deploying risky code.
  • IDE Plugins: Plugins for editors like VS Code and Remix provide instant feedback. For instance, MythX highlights security issues directly in the code editor as developers write smart contracts.

Pros and Cons of Automated Tools

Automated tools are known for their speed and scalability, processing large codebases quickly while reducing developers’ workload. They also deliver consistent results, minimizing human error, and can integrate seamlessly into development workflows like CI/CD pipelines.

"Automated tools quickly scan code for known vulnerabilities, offering efficiency and speed. However, manual reviews by experienced auditors can identify complex, context-specific issues that automated tools might miss. Combining both approaches ensures a thorough security assessment." - Coinmetro Editorial Team

But these tools aren’t without their challenges. False positives remain a significant issue, with some studies reporting rates as high as 99.8%. Many errors stem from incorrect permission control verification or inadequate analysis of external contract functions.

Detection accuracy is another concern. A study of 17 vulnerability scanners found F1 scores ranging from 0% to 73%, with reentrancy detection tools often scoring under 30%. On complex DApp datasets, success rates dropped below 11%.

The changing threat landscape adds further complexity. As vulnerabilities evolve, automated tools often struggle to keep up. Researchers have noted:

"Current Reentrancy detection tools suffer from high false positive rates. Even worse, recent years have witnessed the emergence of new Reentrancy attack patterns fueled by intricate and diverse vulnerability exploit mechanisms. Unfortunately, current tools face a significant limitation in their capacity to adapt and detect these evolving Reentrancy patterns." - Zexu Wang et al.

Some tools also demand substantial computational resources. For instance, Manticore can be slow with large contracts and may require expertise to interpret results effectively. Similarly, Mythril faces challenges with complex cross-contract interactions, often leading to missed vulnerabilities or timeouts.

Despite these drawbacks, automated tools remain an important part of the security process. As H-X Technologies explains:

"We emphasize that using the right tools is only part of a comprehensive smart contract security process. We always recommend an additional manual audit of each line of code to identify potential vulnerabilities that may have gone undetected by automated tools."

sbb-itb-a2160cf

Advanced Detection Methods

When it comes to uncovering vulnerabilities in smart contracts, advanced detection methods go beyond basic automated tools. These techniques dig deeper by analyzing the structure of the code and its behavior during execution, catching vulnerabilities that simpler tools might miss.

Static Analysis Methods

Static analysis focuses on reviewing the code itself without running it. By examining patterns, control flow, and data dependencies, it identifies potential issues like risky external calls before state changes. This method systematically checks all code paths, but it can sometimes flag false positives because it lacks the context of how the code behaves during execution.

Some common techniques include:

  • Code review
  • Abstract interpretation
  • Data flow analysis
  • Formal verification
  • Program slicing

While static analysis can be automated and is great for spotting vulnerabilities in fixed code, it struggles with the dynamic and unpredictable nature of blockchain environments. As noted in the Proceedings of the International Conference on Digital Economy, Blockchain and Artificial Intelligence:

"The advantage of static analysis is that it can be automated and effectively discover vulnerabilities in smart contracts fixed code. However, the limitation of static analysis lies in the complexity and dynamic characteristics of smart contracts. Vulnerabilities generated dynamically during contract execution cannot be discovered."

Interestingly, research highlights that 55% of false positives in static analysis come from incorrect permission control verification, while 41% stem from insufficient analysis of external contract functions.

Dynamic Analysis Methods

Dynamic analysis takes a different approach by monitoring the contract as it runs. This method observes state changes and interactions in real time, uncovering vulnerabilities that only appear during execution.

"Dynamic analysis is a method of monitoring and analyzing contracts at runtime." - Proceedings of the International Conference on Digital Economy, Blockchain and Artificial Intelligence

This approach shines in complex scenarios, detecting issues like abnormal state transfers or time-sensitive attacks that static analysis might overlook. By capturing the actual runtime state, dynamic analysis improves accuracy and helps predict potential threats. As explained in Information and Software Technology:

"Dynamic information is crucial for the security analysis of smart contracts. It captures the actual state of smart contract execution and thus can assist in enhancing vulnerability detection accuracy, mining real-world attacks, and predicting potential threats."

However, dynamic analysis has its challenges. It demands significant computational resources, especially for intricate contracts, and its effectiveness depends on the quality and variety of test inputs.

Combining Static and Dynamic Analysis

To get the best of both worlds, a hybrid approach combines static and dynamic analysis. This method creates a detection pipeline that reduces the weaknesses of each technique while improving overall accuracy.

For example, in May 2021, researchers Noama Fatima Samreen and Manar H. Alalfi from Ryerson University introduced a framework that starts with static analysis to identify potentially vulnerable functions, such as those using transfer(), call(), or send(). Then, it uses dynamic analysis by generating attacker contracts based on ABI specifications to test these vulnerabilities. When applied to five modified smart contracts from Etherscan, this approach successfully detected reentrancy in all cases, outperforming tools like ContractFuzzer by reducing false positives and improving performance.

"Our framework analyzes smart contracts statically to identify potentially vulnerable functions and then uses dynamic analysis to precisely confirm Reentrancy vulnerability, thus achieving increased performance and reduced false positives." - Noama Fatima Samreen and Manar H. Alalfi

The benefits of this hybrid approach are clear. In February 2024, researchers introduced a tool called ReEP, which applies this combined method to enhance existing detection tools. When used with eight leading reentrancy detection tools, ReEP boosted average precision from 0.5% to 73% without sacrificing recall. By combining six tools, ReEP achieved an impressive peak precision of 83.6%, compared to the best standalone performance of just 31.8%.

The typical workflow includes using static analysis to narrow down potential issues and collect reports, followed by dynamic analysis to confirm whether these issues are exploitable. This process often involves symbolic execution and SMT solver verification for cross-contract vulnerabilities.

"Static analysis techniques often collect incomplete program state information, which can lead to false positives due to the loss of the state in contract interactions. Conversely, dynamic vulnerability detection models frequently struggle with deep-state search and comprehensive state analysis in cross-contract vulnerability scenarios." - Zexu Wang et al.

Best Practices for Complete Detection

Tackling reentrancy attacks effectively requires more than just relying on a single tool. The most effective security teams use a mix of strategies, creating detection frameworks that combine various approaches, verify findings, and fit seamlessly into the development process.

Building a Detection Pipeline

A strong detection pipeline combines multiple methods like static analysis, dynamic testing, and symbolic execution. This layered approach helps catch vulnerabilities that individual tools might miss.

Start by integrating multiple tools for better results. Studies have shown that using combined tools can significantly improve detection accuracy. For example, the ReEP framework has proven to enhance precision without sacrificing detection capability.

Adopt multi-stage analysis for complex contracts. Tools like SliSE follow a two-step process: first, they search for warnings using program slicing and dependency graphs, and then they verify vulnerabilities through symbolic execution. This approach has led to an impressive F1 score of 78.65% for detecting reentrancy vulnerabilities, compared to just 9.26% achieved by other tools.

Focus on critical code paths with state-changing instructions. Instead of analyzing every code path, prioritize areas in the Control Flow Graph (CFG) that involve state operations, such as SSTORE, SLOAD, and CALL instructions.

Leverage machine learning for advanced detection. Deep learning models like AWDNN can recognize complex vulnerability patterns by analyzing code and learning from historical attack data. These models add a layer of precision, identifying threats that traditional tools might overlook.

Once your pipeline is set up, the next step is to validate the findings to ensure only genuine vulnerabilities are flagged.

Validating and Prioritizing Results

Even the best tools can generate false positives, so validation is key to maintaining productivity while ensuring no real threats are missed.

Use symbolic execution to verify exploitable paths. This method helps address static analysis weaknesses, such as failing to account for protective measures like mutex locks. SliSE, for instance, improved precision from 47.30% to 72.16% by including symbolic execution in its process.

Identify and address common causes of false positives. Misinterpreted permission controls and incomplete analysis of external contract functions are frequent culprits. Configuring validation processes to focus on these areas can reduce errors.

"Accurate permission control checks and cross-contract state analysis continue to challenge existing detection tools." - Zexu Wang et al., Sun Yat-sen University

Monitor external calls and fund transfers thoroughly. Use detailed logs to track call hierarchies, timestamps, sender addresses, and gas usage. Tools like Hardhat’s console.log or Tenderly can help monitor contract state changes before and after external calls, making it easier to detect recursive function entries.

Focus on high-risk contracts and functions. Give extra attention to contracts managing pooled funds, such as those in DeFi protocols, and contracts with complex token logic. These areas are frequent targets for attacks, with over 42% of historical breaches involving repeated callback execution.

Simulate attacks using unit tests and fuzzing tools. Tools like Echidna or Foundry can help achieve over 95% coverage of public and external functions during simulated exploits.

After validation, integrate these practices into your development process to ensure ongoing protection.

Adding Detection to Development Workflows

For secure smart contracts, security checks need to be part of the development process from the start.

Integrate scanners into your CI/CD pipeline for early detection. Tools like Slither can be set up with GitHub Actions, GitLab, or Jenkins to run automated security checks on every code change. For example, Slither offers a GitHub Actions workflow that analyzes code on pushes to main or develop branches, installs dependencies, runs checks, and uploads reports. IDE extensions for VS Code or Remix can also provide real-time feedback on vulnerabilities during coding.

Follow the "Run Automated Tools First" strategy. Begin with automated scans and then refine results through manual reviews. This approach ensures efficiency while addressing subtle issues that automated tools might miss.

Use AI for faster fixes. Modern scanners with AI integration can automate audits, suggest fixes, and explain vulnerabilities in detail. This reduces the manual workload while providing clear guidance for resolving issues.

Enforce secure coding patterns. Build practices like the Checks-Effects-Interactions pattern into your standards to ensure state changes occur before external calls. Use libraries like OpenZeppelin’s nonReentrant modifier to guard against reentrancy, and design secure withdrawal methods that separate fund transfers into protected functions.

Real-world results highlight the benefits of this integrated approach. For instance, a DeFi token launchpad that implemented an AI-powered smart contract scanner reduced scam tokens from over 30% to less than 5%, while increasing Total Value Locked (TVL) by 200% in six months.

"Integrating a smart contract scanner into a developer's workflow through APIs or CI/CD pipelines ensures continuous security checks throughout the development process. This integration helps businesses maintain high security standards without disrupting ongoing development efforts." - IdeaUsher

Conclusion and Key Takeaways

No single detection method is foolproof, but combining different approaches can create stronger security. Manual reviews are invaluable for spotting context-specific vulnerabilities, while automated tools excel at handling the vast scale of large codebases.

The urgency for robust security measures grows as breaches become more costly. For instance, reentrancy attacks have led to losses of approximately $350 million by 2023, with attackers increasingly targeting these vulnerabilities. A stark example is the Curve Finance hack in July 2023, where nearly $70 million was stolen due to a Vyper compiler bug - proving that even well-established protocols are not immune.

Advanced tools now integrate techniques like static analysis, dynamic testing, and symbolic execution, offering more thorough detection frameworks. These tools are particularly effective at identifying vulnerabilities in contracts of varying complexity.

Since smart contracts are immutable once deployed, addressing vulnerabilities beforehand is critical. As research highlights:

"Once deployed, smart contracts are immutable, which means that any vulnerabilities introduced during development cannot be easily addressed"

This makes it essential to embed detection tools into your CI/CD pipeline to catch issues early.

Emerging AI models are also making strides in identifying complex patterns within contract code. These models are especially effective at uncovering vulnerabilities in real-world contracts, which are often far more intricate than simplified test cases.

For teams committed to security, the way forward involves building detection pipelines that leverage multiple analytical methods, validating findings through symbolic execution, and maintaining continuous monitoring throughout development. Investing in these practices not only prevents expensive breaches but also helps maintain user trust in DeFi.

Beyond protecting assets, this approach aligns with evolving regulatory standards. With regulatory bodies beginning to set blockchain security requirements, adopting robust detection practices is becoming a necessity for compliance. By combining manual reviews with automated and advanced detection methods, teams can establish a well-rounded security strategy that meets both security and regulatory needs in the ever-changing smart contract landscape.

FAQs

What are some notable examples of reentrancy attacks, and how have they affected DeFi platforms?

Reentrancy attacks have proven to be a major challenge in the DeFi world. Take the case of GMX V1, a decentralized perpetual exchange - back in July 2025, it fell victim to a reentrancy attack, resulting in a staggering $42 million loss. Another example is Uniswap V1. In April 2020, hackers exploited a weakness in its system, making off with 1,278 ETH. These examples underline the serious financial risks tied to such vulnerabilities.

These events emphasize just how critical it is to build strong security measures into smart contracts. Protecting user funds and maintaining trust in DeFi platforms depends on it.

What’s the best way to use automated tools for detecting reentrancy attacks during smart contract development?

To make the most of automated tools for spotting reentrancy attacks, developers should add them to their continuous integration (CI) pipelines. This way, every time the code is updated, it gets automatically checked for vulnerabilities, including reentrancy issues. Tools such as MythX, Slither, and OpenZeppelin are great for catching problems early, helping to avoid deploying insecure contracts.

Using these tools alongside testing frameworks like Hardhat or Truffle makes it easy to fit them into the development workflow. On top of that, combining static analysis with fuzz testing boosts security, allowing developers to find and fix vulnerabilities before they escalate.

What challenges do manual code reviews face in identifying reentrancy vulnerabilities, and how can automated tools help?

Manual code reviews demand a lot of time and effort, and since they rely on humans, they can be affected by fatigue, missed details, or subjective decisions. This makes it easy for certain vulnerabilities, like tricky reentrancy issues, to slip through unnoticed.

Automated tools step in to help by quickly scanning through large amounts of code, spotting common security flaws, and cutting down on human mistakes. When you blend the careful eye of manual reviews with the speed and accuracy of automation, you get a stronger, more dependable way to catch vulnerabilities in smart contracts.

Copy Winning Trades Instantly

4.9 Rating based reviews on

Product of the Day Badge

"I've tried the beta version of Walletfinder.ai extensively and I was blown away by how you can filter through the data, and the massive profitable wallets available in the filter presets, unbelievably valuable for any trader or copy trader. This is unfair advantage."

Pablo Massa

Experienced DeFi Trader