为什么合约里尽量避免使用 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);
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容