ReentrancyGuard库是一个用来防御函数重入的工具库。函数被修饰器nonReentrant
修饰可确保其无法被嵌套(重入)调用。本库的代码逻辑上只实现了一个重入锁,所以被nonReentrant
修饰的函数之间也是无法相互调用的。
[openzeppelin]:v4.8.3,[forge-std]:v1.5.6
ReentrancyGuard库是一个用来防御函数重入的工具库。函数被修饰器nonReentrant
修饰可确保其无法被嵌套(重入)调用。本库的代码逻辑上只实现了一个重入锁,所以被nonReentrant
修饰的函数之间也是无法相互调用的。
继承ReentrancyGuard合约:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "openzeppelin-contracts/contracts/security/ReentrancyGuard.sol";
contract MockReentrancyGuard is ReentrancyGuard {
uint public counter;
function addWithoutNonReentrant() external {
_add();
}
function callWithoutNonReentrant(address target, bytes calldata calldata_) external {
_call(target, calldata_);
}
function addWithNonReentrant() external nonReentrant {
_add();
}
function callWithNonReentrant(address target, bytes calldata calldata_) external nonReentrant {
_call(target, calldata_);
}
function _call(address target, bytes calldata calldata_) private {
(bool ok, bytes memory returnData) = target.call(calldata_);
require(ok, string(returnData));
counter += 10;
}
function _add() private {
++counter;
}
}
全部foundry测试合约:
测试使用的物料合约:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract Reentrant {
address private target;
constructor(address targetAddress){
target = targetAddress;
}
function callback(bytes calldata calldata_) external {
(bool ok, bytes memory returnData) = target.call(calldata_);
if (!ok) {
// pull the revert msg out of the return data of the call
uint len = returnData.length;
if (len > 4 && bytes4(returnData) == bytes4(keccak256(bytes("Error(string)")))) {
// get returnData[4:] in memory bytes
bytes memory encodedRevertMsg = new bytes(len - 4);
for (uint i = 4; i < len; ++i) {
encodedRevertMsg[i - 4] = returnData[i];
}
revert(abi.decode(encodedRevertMsg, (string)));
} else {
revert();
}
}
}
}
// 常量标识,标志着合约方法"未被进入"的状态
uint256 private constant _NOT_ENTERED = 1;
// 常量标识,标志着合约方法"已被进入"的状态
uint256 private constant _ENTERED = 2;
// 标识合约被进入状态的全局变量
// 注:该处使用uint256类型而不是bool的原因见下
uint256 private _status;
// 初始化函数
constructor() {
// 将合约状态设置为"未被进入"
_status = _NOT_ENTERED;
}
为什么_status不选择bool类型而使用uint256类型?
答:更新bool类型的gas消耗要比uint256或者其他占满一个word(32字节)的类型都贵。每一个写操作都会携带额外的SLOAD
读出slot中的值,接着更新其中bool类型对应的bit,最后才进行slot的回写。这是编译器对合约升级和指针混叠的一种防御措施,无法禁用。
尽管将具有flag属性的状态变量设定为非0值会使得合约部署费用增高,但却可以减少每次调用被nonReentrant修饰方法的gas消耗。
用于防重入的修饰器,防止合约方法直接或间接调用自身。
注:合约内两个被该修饰器修饰的方法无法进行相互调用。可通过将各自逻辑封装成private函数,并用nonReentrant修饰的external函数封装以上private函数来解决部分需求。
modifier nonReentrant() {
// 进入方法前的准备工作
_nonReentrantBefore();
_;
// 执行完整个方法后的收尾工作
_nonReentrantAfter();
}
// 进入方法前的准备工作
function _nonReentrantBefore() private {
// 要求进入函数前合约标识状态为"未进入",即之前没有与本合约中被nonReentrant修饰的方法交互过
// 注:此处的检查会将产生重入的调用revert
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 将合约标识状态更改为"已进入"
_status = _ENTERED;
}
// 执行完整个方法后的收尾工作
function _nonReentrantAfter() private {
// 将合约标识状态更改回"未进入"。由于合约标识状态最后又改回了前值,
// 即本次方法调用的结果并没有导致该slot的值发生变化,此处将触发gas的返还。
// 具体细节参见:https://eips.ethereum.org/EIPS/eip-2200
_status = _NOT_ENTERED;
}
foundry代码验证:
contract ReentrancyGuardTest is Test {
MockReentrancyGuard private _testing = new MockReentrancyGuard();
Reentrant private _reentrant = new Reentrant(address(_testing));
function test_LocalCall() external {
// A and B are both local external methods in one contract
// case 1: A without nonReentrant -> B without nonReentrant
// [PASS]
// call {addWithoutNonReentrant} in {callWithoutNonReentrant}
assertEq(_testing.counter(), 0);
bytes memory calldata_ = abi.encodeCall(_testing.addWithoutNonReentrant, ());
_testing.callWithoutNonReentrant(address(_testing), calldata_);
uint counterValue = _testing.counter();
assertEq(counterValue, 1 + 10);
// case 2: A without nonReentrant -> B with nonReentrant
// [PASS]
// call {addWithNonReentrant} in {callWithoutNonReentrant}
calldata_ = abi.encodeCall(_testing.addWithNonReentrant, ());
_testing.callWithoutNonReentrant(address(_testing), calldata_);
assertEq(_testing.counter(), counterValue + 1 + 10);
counterValue = _testing.counter();
// case 3: A with nonReentrant -> B without nonReentrant
// [PASS]
// call {addWithoutNonReentrant} in {callWithNonReentrant}
calldata_ = abi.encodeCall(_testing.addWithoutNonReentrant, ());
_testing.callWithNonReentrant(address(_testing), calldata_);
assertEq(_testing.counter(), counterValue + 1 + 10);
// case 4: A with nonReentrant -> B with nonReentrant
// [REVERT]
// call {addWithNonReentrant} in {callWithNonReentrant}
calldata_ = abi.encodeCall(_testing.addWithNonReentrant, ());
// the provided string in `require(bool,string)` is abi-encoded as if it was a call to a function `Error(string)`
bytes memory encodedRevertMsg = abi.encodeWithSignature("Error(string)", "ReentrancyGuard: reentrant call");
vm.expectRevert(encodedRevertMsg);
_testing.callWithNonReentrant(address(_testing), calldata_);
}
function test_ExternalCall() external {
// A and B are both local external methods in one contract
// C is an external method in another contract
// case 1: A without nonReentrant -> B -> C without nonReentrant
// [PASS]
// {callWithoutNonReentrant} -> {Reentrant.callback} -> {addWithoutNonReentrant}
assertEq(_testing.counter(), 0);
bytes memory calldata_ = abi.encodeCall(
_reentrant.callback,
(
abi.encodeCall(_testing.addWithoutNonReentrant, ())
)
);
_testing.callWithoutNonReentrant(address(_reentrant), calldata_);
uint counterValue = _testing.counter();
assertEq(counterValue, 1 + 10);
// case 2: A without nonReentrant -> B -> C with nonReentrant
// [PASS]
// {callWithoutNonReentrant} -> {Reentrant.callback} -> {addWithNonReentrant}
calldata_ = abi.encodeCall(
_reentrant.callback,
(
abi.encodeCall(_testing.addWithNonReentrant, ())
)
);
_testing.callWithoutNonReentrant(address(_reentrant), calldata_);
assertEq(_testing.counter(), counterValue + 1 + 10);
counterValue = _testing.counter();
// case 3: A with nonReentrant -> B -> C without nonReentrant
// [PASS]
// {callWithNonReentrant} -> {Reentrant.callback} -> {addWithoutNonReentrant}
calldata_ = abi.encodeCall(
_reentrant.callback,
(
abi.encodeCall(_testing.addWithoutNonReentrant, ())
)
);
_testing.callWithNonReentrant(address(_reentrant), calldata_);
assertEq(_testing.counter(), counterValue + 1 + 10);
// case 4: A with nonReentrant -> B -> C with nonReentrant
// [REVERT]
// {callWithNonReentrant} -> {Reentrant.callback} -> {addWithNonReentrant}
calldata_ = abi.encodeCall(
_reentrant.callback,
(
abi.encodeCall(_testing.addWithNonReentrant, ())
)
);
// the provided string in `require(bool,string)` is abi-encoded as if it was a call to a function `Error(string)`
bytes memory encodedRevertMsg = abi.encodeWithSignature("Error(string)", "ReentrancyGuard: reentrant call");
vm.expectRevert(encodedRevertMsg);
_testing.callWithNonReentrant(address(_reentrant), calldata_);
}
}
ps: 本人热爱图灵,热爱中本聪,热爱V神。 以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。 同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下! 如果需要转发,麻烦注明作者。十分感谢!
公众号名称:后现代泼痞浪漫主义奠基人
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!