为什么合约里尽量避免使用 tx.origin

  • Ashton
  • 更新于 2019-07-31 23:37
  • 阅读 3780

为什么合约里尽量避免使用 tx.origin

  1. V 神说了, Do NOT assume that tx.origin will continue to be usable or meaningful.
  2. 由可以引发严重的安全问题,特别是用 tx.origin 做权限校验时,非常容易被绕过。看下面的经典代码示例:当 MyContract 实例的 owner 尝试往作为 receiver 的 AttachingContract 发送代币时,由于 AttachingContract 没有 transfer 方法,fallback 方法会被调用,AttachingContract 反过来又调用 MyContract 实例的 sendTo 方法,这个时候 tx.origin 还是当前的 owner,“require(tx.origin == owner);” 就成了摆设,可以很轻松的把 MyContract 里的以太币全部转走。
contract MyContract {

    address owner;

    function MyContract() public {
        owner = msg.sender;
    }

    function sendTo(address receiver, uint amount) public {
        require(tx.origin == owner);
        receiver.transfer(amount);
    }

}

contract AttackingContract {

    MyContract myContract;
    address attacker;

    function AttackingContract(address myContractAddress) public {
        myContract = MyContract(myContractAddress);
        attacker = msg.sender;
    }

    function() public {
        myContract.sendTo(attacker, msg.sender.balance);
    }

}
点赞 0
收藏 1
分享

0 条评论

请先 登录 后评论
Ashton
Ashton
0x53b3...c54F
专注于 EVM 和比特币生态的区块链开发者