elasticdao/contracts

[Audit Fix] Reentrancy gas costs

Closed this issue · 1 comments

dmvt commented

The reentrancy guard implementation using toggling boolean values is expensive.

Risk Rating

Impact = High
Vulnerability Details

The reentrancy guard implementation using toggling boolean values is expensive as explained (see below comment) in OpenZeppelin’s ReentrancyGuard library:

// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.

Also see reference: https://eips.ethereum.org/EIPS/eip-1283
Impact

Given that the reentrancy guard modifier preventReentry is used extensively, the gas usage impact will be significant.

Proof of Concept

https://github.com/elasticdao/code-contests/blob/e643cce4bbec683765e3b9a1ab576542ac61000f/contests/02-elasticdao/contracts/services/ReentryProtection.sol#L9-L26
Tools Used

Manual review.

Recommended Mitigation Steps

Use an implementation based on enum Mutex {UNUSED, OPEN, LOCKED} or OpenZeppelin’s optimized ReentrancyGuard library.

Definition of Done

  • POC contract and functions using both methods proving which is cheaper
  • Use whichever method is cheaper

Our Reentry Protection Gas Costs:
image

OpenZeppelin Implementation Gas Costs:
image