Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explains denial-of-service (DoS) attacks against smart contracts.

You may already be familiar with the term DoS attack, since it is a common form of attack in Web2.

Smart contracts are also susceptible to denial of service if their design does not account for these vulnerabilities.

Understanding these issues is essential for Solidity developers who want to improve their security skills and for aspiring bug bounty hunters.

If you are unfamiliar with bug bounty programs, start with the following article.

[Solidity Bug Bounty] An Introduction to Bug Bounties

What Is a DoS Attack?

Overview of denial-of-service attacks

First, let's establish what DoS means.

Terminology

DoS stands for denial of service.

DoS describes a type of security attack; the spellings Dos and DoS in this article refer to the same concept.

A denial-of-service attack is an attack on availability in information security.

It disrupts a service by deliberately overloading resources such as servers or networks that run a web service, or by exploiting vulnerabilities.

https://ja.wikipedia.org/wiki/DoS攻撃

The above is a translation of the Japanese Wikipedia definition.

In short, a DoS attack overloads a service or exploits a vulnerability so that the service cannot handle requests from legitimate users.

A denial-of-service attack against a smart contract may prevent legitimate users from accessing it temporarily or permanently.

DoS and DDoS attacks are common beyond smart contracts, so you may already have heard of them.

Distributed denial-of-service attacks have historically been associated with the international hacking collective Anonymous.

A form of flooding-based DoS attack is the distributed denial-of-service (DDoS) attack, in which many machines simultaneously launch a DoS attack against a single service.

https://ja.wikipedia.org/wiki/DoS攻撃#DDoS.E6.94.BB.E6.92.83

The above is a translation of the Japanese Wikipedia description of DDoS attacks.

A DDoS attack is essentially a denial-of-service attack originating from multiple machines.

Denial of Service on a Blockchain

What forms can denial of service take on a blockchain?

Types of DoS attacks

  • Unexpected Revert
  • Block Gas Limit
  • Block Stuffing

These are three important categories of denial of service on blockchains.

Consider each in turn.

Unexpected Revert

The name refers to an unexpected revert.

In a smart contract, a revert stops execution of the affected call, rolls back its state changes, and returns unused gas to the caller. Gas already consumed is not refunded simply because execution reverted.

An unexpected revert in part of a contract can prevent the contract from executing its intended operation. The following section illustrates this with code.

Block Gas Limit

Ethereum imposes gas limits on execution.

The original example mentions 21,000Gas. More precisely, 21,000 gas is the intrinsic gas cost of a standard ETH transfer with no calldata; it is not the block gas limit. A block has a separate gas limit that bounds the total gas consumed by its transactions.

If an operation can be made to exceed the applicable gas limit, it may become impossible to execute, potentially leaving all funds locked.

Block Stuffing

Ethereum block producers can prioritize transactions offering higher effective fees.

If block space is occupied by a party's transactions, other users' transactions may be delayed or excluded from blocks during that period. Higher fees do not guarantee inclusion or ordering.

DoS Vulnerabilities

Overview of smart contract DoS vulnerabilities

This section examines denial-of-service vulnerabilities through smart contract code.

Unexpected Revert

First, consider unexpected reverts.

Code Walkthrough

The previous section introduced unexpected reverts. Here is how they can interfere with a contract's behavior.

Imagine a contract for a contest in which each new participant must deposit more than the current leading participant. After a specified period or number of rounds, the largest depositor receives a reward of 1 ether. The following code illustrates the deposit mechanism rather than the complete contest or reward logic.

solidity
contract Dos {
    address public winner;
    uint public balance;

    /// @notice 現在のwinnerよりも多くの資金を預けた場合、現在のwinnerに預けた資金を戻し
    ///         winnerにmsg.senderが設定される関数。
    function deposit() public payable {
        require(msg.value > balance, "Deposit more funds than you currently have on deposit.");

        (bool sent, ) = winner.call{value: balance}("");
        require(sent, "Failed to send Ether");

        balance = msg.value;
        winner = msg.sender;
    }
}
winner

Stores the address of the user who currently has the largest deposit.

balance

Stores the value deposited by the current leading user.

deposit

Checks whether the incoming deposit exceeds the value of the largest current deposit.

If the condition is true, the function refunds the previous leader and updates balance and winner.

Although the contract is designed for deposits from users, another contract can deposit funds as well.

A contract-based depositor can cause an unexpected revert when the protocol tries to refund it.

The following test contract demonstrates the vulnerability in the example.

solidity
contract Attack {
    Dos dos;

    constructor (Dos _dos) {
        dos = Dos(_dos);
    }

    /// @notice Dosコントラクトのdeposit関数を呼び出す関数。
    function attack() public payable {
        dos.deposit{value: msg.value}();
    }
}
dos

Stores a reference to the Dos contract.

attack

Calls the Dos contract's deposit function and forwards the supplied funds.

Execution

Run the contracts in a test environment to observe their behavior.

Recording of the unexpected revert demonstration

What changed during execution?

The deposit function works normally before attack is called. After the call to attack, subsequent deposits fail.

Why does this happen?

The receiving contract has no payable receive or fallback function.

When a contract receives ETH through an empty-calldata call, Solidity invokes its payable receive function, or its payable fallback function when applicable.

The Attack contract implements neither function, so the attempted refund fails.

The following call inside deposit fails on each subsequent attempt, and the accompanying require reverts the deposit. In the hypothetical contest, this would leave Attack as the leader until the deadline.

javascript
(bool sent, ) = winner.call{value: balance}("");

Full Code

Here is the complete example.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Dos {
    address public winner;
    uint public balance;

    /// @notice 現在のwinnerよりも多くの資金を預けた場合、現在のwinnerに預けた資金を戻し
    ///         winnerにmsg.senderが設定される関数。
    function deposit() public payable {
        require(msg.value > balance, "Deposit more funds than you currently have on deposit.");

        (bool sent, ) = winner.call{value: balance}("");
        require(sent, "Failed to send Ether");

        balance = msg.value;
        winner = msg.sender;
    }
}

contract Attack {
    Dos dos;

    constructor (Dos _dos) {
        dos = Dos(_dos);
    }

    /// @notice Dosコントラクトのdeposit関数を呼び出す関数。
    function attack() public payable {
        dos.deposit{value: msg.value}();
    }
}

Mitigation

One way to address this vulnerability is to provide a withdrawal function and let each user claim their own funds rather than refunding the previous leader during a new deposit.

solidity
contract Dos {
    address public winner;
    uint public balance;
    mapping(address=>uint) public balances;

    /// @notice 現在のwinnerよりも多くの資金を預けた場合、現在のwinnerに預けた資金を戻し
    ///         winnerにmsg.senderが設定される関数。
    function deposit() public payable {
        require(msg.value > balance, "Deposit more funds than you currently have on deposit.");

        // (bool sent, ) = winner.call{value: balance}("");
        // require(sent, "Failed to send Ether");

        balances[winner] += balance;

        balance = msg.value;
        winner = msg.sender;
    }

    function widthdraw() public {
        require(msg.sender != winner, "Current king cannot withdraw");

        uint amount = balances[msg.sender];
        balances[msg.sender] = 0;

        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Failed to send Ether");
    }
}
balance

The balances mapping records the amount owed to each user.

deposit

Instead of immediately refunding the previous winner, the function records the amount in storage.

widthdraw

Transfers the amount recorded for the caller in the balances mapping.

If the Attack contract attempts to withdraw, it still cannot receive the refund without a suitable payable entry point. However, its own withdrawal failure no longer blocks other users from depositing. The provided attack function itself only calls deposit.

Block Gas Limit

There is a limit to the amount of gas a transaction can consume.

This bounds execution and lets users specify the maximum gas they are prepared to provide.

An operation may nevertheless become unusable if its gas requirement grows beyond the applicable limit, either through malicious activity or normal use.

The following example illustrates the issue.

Code Walkthrough

solidity
contract Dos {
    address[] public users;
    uint[] public balances;

    /// @notice 資金を預ける関数。
    function deposit() public payable {
        users.push(msg.sender);
        balances.push(msg.value);
    }

    function shar() public {
        for (uint i; i < users.length; i++) {
            (bool sent, ) = users[i].call{value: balances[i]}("");
            require(sent, "Failed to send Ether");
        }
    }
}

Consider the simple contract above.

users

An array of addresses of users who deposited funds.

balances

An array that records deposit amounts.

deposit

Accepts funds and appends the sender and the deposited amount to the users and balances arrays.

shar

Iterates over the users and balances arrays in a for loop and sends each user the corresponding amount.

Execution

Run the example in a test environment.

Recording of the distribution demonstration

Each call to deposit appends values to the users and balances arrays.

Calling shar returns the funds held by the contract to the users who deposited them.

What is wrong with this implementation?

If the users and balances arrays grow very large, calling shar may exceed the gas limit.

Because shar uses a for loop, longer arrays require more execution time and gas.

A growing number of deposits can therefore make the distribution loop too expensive to execute, denying users access to refunds.

This can happen even without malicious activity: a sufficiently large number of legitimate deposits has the same effect.

Full Code

Here is the complete example.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Dos {
    address[] public users;
    uint[] public balances;

    /// @notice 資金を預ける関数。
    function deposit() public payable {
        users.push(msg.sender);
        balances.push(msg.value);
    }

    /// @notice 資金を分配する関数。
    function shar() public {
        for (uint i; i < users.length; i++) {
            (bool sent, ) = users[i].call{value: balances[i]}("");
            require(sent, "Failed to send Ether");
        }
    }
}

Mitigation

One possible design checks the remaining gas and stores progress so that a distribution can resume in a later transaction, as the following historical example attempts to do.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Dos {
    address[] public users;
    uint[] public balances;
    uint nextIndex;

    /// @notice 資金を預ける関数。
    function deposit() public payable {
        users.push(msg.sender);
        balances.push(msg.value);
    }

    /// @notice 資金を分配する関数。
    function shar() public {
        // for (uint i; i < users.length; i++) {
        //     (bool sent, ) = users[i].call{value: balances[i]}("");
        //     require(sent, "Failed to send Ether");
        // }
        uint i = nextIndex;
        while (i < users.length && gasleft() < 10000) {
            (bool sent, ) = users[i].call{value: balances[i]}("");
            require(sent, "Failed to send Ether");
            i++;
        }
        nextIndex = i;
    }
}

The intended behavior of shar is to continue its while loop until it reaches the end of the users array or the remaining gas falls below 10000. However, the original code uses gasleft() < 10000, which reverses that condition. The snippet is retained for fidelity to the original and is not a working production mitigation.

Recording the processed position in nextIndex lets a subsequent call resume from that point rather than starting over.

This is a rough illustration of resumable processing. A production design also needs explicit bounds on work per transaction, adequate gas for external calls and storage writes, and a strategy for failed recipients and reentrancy. A pull-payment model avoids requiring every recipient to succeed in one distribution.

Block Stuffing

Pending transactions compete for inclusion in blocks.

Transactions are not guaranteed to be processed in submission order; block producers can prioritize transactions offering higher effective fees.

This creates a risk for contracts that determine a payout at a fixed deadline: interference with other users' timely inclusion may affect the result.

Example

Suppose users deposit at least 1 ether, and the user with the largest ETH deposit after a specified period receives all the funds.

Scenario

  • Users deposit funds.
  • A malicious participant deposits funds.
  • If competing transactions are excluded or delayed until the deadline, the contest's outcome may be distorted.
  • Other users cannot have their intended deposits included before the deadline.
  • The malicious participant may receive all the funds in the contract when the period ends.

The economic risk depends on whether the potential reward exceeds the cost of interfering with transaction inclusion.

Mitigation

Consider the relationship between transaction fees and the potential profit. A design can reduce the incentive for interference by making its cost exceed the available reward.

It is also important to evaluate whether a deadline-based model remains fair and functional if transaction inclusion is disrupted.

Conclusion

Summary of smart contract DoS vulnerabilities

This article covered denial-of-service attacks against smart contracts.

Here are the main points to take away.

Key points

  • Understand what denial of service means.
  • Recognize vulnerabilities that can cause denial of service.
  • Understand ways to mitigate denial-of-service vulnerabilities.

Keep these considerations in mind when designing and auditing contracts.

I regularly write about Solidity, blockchain, and Web3.

I also share interesting articles on Twitter.

References

https://www.somish.com/all-about-smart-contract-auditing-denial-of-service-attacks-on-smart-contracts-2020/

https://github.com/kadenzipfel/smart-contract-attack-vectors/blob/master/attacks/dos-gas-limit.md

https://consensys.github.io/smart-contract-best-practices/attacks/denial-of-service/

https://coinsbench.com/denial-of-service-hack-solidity-6-2ce2243f41d1