0

Is it possible to check if msg.sender is a contract of a specific type?

For example:

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    function Bar(){
        new Foo();
    }
}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
    }
}

I've tried this in Remix and running it Baz in remix doesn't cause any problems.

1

You could do this short and simple. It would guard against accidental mix-ups, but not deliberate impersonation.

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    function Bar(){
        new Foo();
    }

    function iAmBar() public pure returns(bool isIndeed) {
        return true;
    }
}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
        require(bar.iAmBar());
    }
}

Another way to go is to whitelist all the "friendly" contracts. In the case you have more than one deployer, you would use a separate whitelist to catalogue all the "friendlies". A simpler example just has your Bar contract keep track of its progeny.

pragma solidity ^0.4.23;
contract Baz {

    function Baz(){
        // want this to fail
        new Foo();
    }
}

contract Bar {

    mapping(address => bool) public isWhiteListed;

    function Bar(){
        Foo f = new Foo();
        isWhiteListed[address(f)] = true;
    }

}

contract Foo {
    Bar bar;


    function Foo(){
        // how to make sure that msg.sender is of type Bar?
        bar = Bar(msg.sender);
        require(bar.isWhiteListed(address(bar)));
    }
}

Hope it helps.

  • Can't iAmBar and isWhiteListed be impersonated? For example, can't Baz implement an iAmBar method which always returns true? – Paymahn Moghadasian May 13 '18 at 22:28
  • 1
    Yes. I think you'll be stuck when trying to restrict a constructor this way. By definition, anyone who is deploying has the source and can even modify it as needed. If you flip it around and say something like Bar has functions that are restricted to known Foo then the rules and structure will be easier to sort out. – Rob Hitchens - B9lab May 13 '18 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.