Attacks on Smart Contract — Chapter 2
Denial of Service (DoS) Attack
So what is a Denial of Service attack aka DoS attack? Well, it is an attack that is performed to prevent your smart contract from executing its function accessible to its designated users.
Let us take the KingOfEther contract example:
The example has two contracts, one is the victim contract that is “KingOfEther.sol” the other one is the attacker contract “Attacker.sol”.
The purpose of KingOfEther is to conquer the previous king by transferring more Ether. The amount of Ether sent by the previous king will be refunded.
KingOfEther.sol :
Attacker.sol :
The contract expects the highest amount of Ether to maintain the position of King. If a user sends more Ether than the previous King, then he/she will be the new King and the previous King will be refunded.
This seems to be technically correct. However, when an attacker tries to interact with the contract and perform an attack, the attacker will create a contract to interact with your smart contract. The attacker’s contract can have either a fallback() function with a revert statement or the contract can be without a fallback() function. This would return a revert error when someone tries to send money to Attacker’s contract and the transaction fails.
In the above scenario, the attacker sends more Ether than the previous King and becomes the King. At this point, if another user comes and pays more than the Attacker to be the King, the contract will refund the attacker since it got the new highest price, but in this case, the transaction fails since the attacker’s contract does not have a fallback/receive function to receive money to the contract, which would revert the transaction and make the Attacker the King forever.
Solution
To prevent this attack we can create a withdraw function and let users to withdraw the money instead of the contract sending to them. In this case the affected users will be the Attacker when he tries to withdraw.
KingOfEther.sol :
Code Example: https://solidity-by-example.org/hacks/denial-of-service/