Prevent reentrancy attacks using ReentrancyGuard.sol

There is a type of attack pattern where an attacker can call the function of a contract repeatedly. This is called a reentrancy attack. Using these types of attacks, an attacker may steal funds from the contract or perform unsafe operations on it. To prevent these types of attacks, the ReentrancyGuard.sol contract is used, which ensures that a function should be called only once per transaction.

However, it is the developer's responsibility to write code that isn't prone to reentrancy attacks. If there is still a chance of reentrancy attacks that cannot be stopped by code, then the modifier provided by this contract could be helpful.

The OpenZeppelin contract present at Chapter09/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol is defined as follows:

contract ReentrancyGuard {
uint256 private _guardCounter;

constructor () internal {
_guardCounter = 1;
}

modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}

Let's review the preceding code in more detail. The contract contains the following state variable, constructor, and modifier:

  • State variable:
  • _guardCounter: This is an internal counter variable that increases per successive calls.
  • Constructor:
  • In the constructor, the _guardCounter variable is initialized and set to 1 as a value.
  • Modifier:
  • nonReentrant: This modifier can be used in a function to guard that function against reentrancy attacks.

You can refer Chapter 14, Tips, Tricks and Security Best PracticesReentrancy attacks, for more details on reentrancy attacks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.184.155