modifier的三种应用场景
- 权限控制,如example 1
- 入参校验,如example 2
- 防止重入,如example 3
pragma solidity ^0.8.0;
contract FunctionModifier{
address public owner;
bool public locked;
int public x;
constructor(){
owner = msg.sender;
locked = false;
}
//1
modifier onlyOwner(){
require(msg.sender == owner,"only owner");
_;
}
//2
modifier checkAddress(address _addr) {
require(_addr != address(0),"not valid addr");
_;
}
function changeOwner(address _addr)public onlyOwner checkAddress(_addr){
owner = _addr;
}
//3
modifier noReentrancy() {
require(!locked,"locked");
locked = true;
_;
locked = false;
}
function test(int i)public noReentrancy {
x-=i;
if (i >1 ){
test(i - 1); // will be revert,because of locked!
}
}
}
重入漏洞 在以太坊智能合约中,进行转账操作,一旦向被攻击者劫持的合约地址发起转账操作,迫使执行攻击合约的回调函数,回调函数中包含回调自身代码,将会导致代码执行“重新进入”合约。这种合约漏洞,被称为“重入漏洞”。
利用“重入漏洞”执行的攻击方式被用于臭名昭著的DAO攻击中
具体可参考: https://www.jianshu.com/p/601c9e759281
|