【问题标题】:Check if msg.sender is a specific type of contract检查 msg.sender 是否是特定类型的合约
【发布时间】:2021-07-13 19:47:48
【问题描述】:

现在,任何人都可以调用FirstContract 中的setMyString 函数。我正在尝试将对该函数的访问限制为SecondContract 的实例。但不是一个特定的实例,任何SecondContract 类型的合约都应该能够调用setMyString

contract FirstContract{
    String public myString;

    function setMyString(String memory what) public {
        myString=what;
    }
}

contract SecondContract{
    address owner;
    address firstAddress;
    FirstContract firstContract;
    constructor(address _1st){
        owner=msg.sender;
        firstAddress=_1st;
        firstContract=FirstContract(firstAddress);
    }
    function callFirst(String memory what){
        require(msg.sender==owner);
        firstContract.setMyString("hello");
    }
}

【问题讨论】:

    标签: ethereum solidity smartcontracts web3


    【解决方案1】:

    Solidity 目前没有一种简单的方法来根据接口验证地址。

    您可以检查字节码,它是否包含(公共属性和方法的)指定签名。这需要比通常的 StackOverflow 答案更大的范围,所以我只描述步骤而不是编写代码。

    首先,定义您要查找的签名列表(名称和参数数据类型的前 4 个字节的 keccak256 哈希)。您可以在我的其他答案herehere 中找到有关签名的更多信息。

    documentation 中的一个示例显示了如何将任何地址的(在您的情况下为 msg.sender)字节码获取为 bytes(动态长度数组)。

    然后您需要遍历返回的 bytes 数组并搜索 4 字节的签名。

    如果您发现它们全部,则表示msg.sender“实现了接口”。如果外部合约中缺少任何个签名,则意味着它没有实现接口。


    但是...我真的建议您重新考虑您的白名单方法。是的,当new SecondContract 第一次想要调用setMyString() 函数时,您需要维护列表并调用setIsSecondContract()。但是对于FirstContractsetMyString() 函数的所有调用者来说,它的gas 效率更高,并且首先更容易编写和测试该功能。

    contract FirstContract{
        String public myString;
        
        address owner;
        mapping (address => bool) isSecondContract;
        
        modifier onlySecondContract {
            require(isSecondContract[msg.sender]);
            _;
        }
        
        modifier onlyOwner {
            require(msg.sender == owner);
            _;
        }
        
        function setIsSecondContract(address _address, bool _value) public onlyOwner {
            isSecondContract[_address] = _value;
        }
    
        function setMyString(String memory what) public onlySecondContract {
            myString=what;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2015-05-24
      • 2021-10-26
      相关资源
      最近更新 更多