1

Since function owned is public, does it mean anyone can externally call it and own the contract as msg.sender?

contract owned {
    address public owner;

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

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    function transferOwnership(address newOwner) onlyOwner public {
        owner = newOwner;
    }
}
1

In this particular case, no. The contract is also called owned, so the function acts as the constructor.

In recent versions of solidity, you should explicitly declare it as constructor() public {..} to avoid confusion, and to prevent bugs in scenarios such as renaming the contract and forgetting to change the function name.

If the function and contract had different names, then yes, it would be public and invokable by anyone

1

This is a constructor in Solidity versions prior 0.4.21, so it has to be public, and it cannot be called on an existing contract (can only be called in order to deploy a new contract).

As of Solidity v0.4.21 onward, you can replace function owned with constructor.

This syntax extension has been applied in order to reduce the potential of someone renaming the constructor without renaming the contract, thus exposing it as a regular public function.

6
  • 1
    "However, from Solidity v0.4.21 onward, you'll need to replace function owned with constructor, otherwise this function will indeed pose a security breach." This is untrue. The old syntax for a constructor is deprecated, but using it poses no security risk. – user19510 Aug 15 '18 at 13:56
  • @smarx: The old syntax makes the constructor a public function, callable by anyone. Is that wrong? – goodvibration Aug 15 '18 at 14:04
  • Yes, that's wrong. The old syntax works the same way it always did. – user19510 Aug 15 '18 at 14:18
  • @smarx: So the only security issue is the potential of someone renaming the constructor (which is plausible when the old syntax is used, but not likely to happen when the new syntax is used), thus exposing it as a regular public function? – goodvibration Aug 15 '18 at 14:21
  • Yes. That's why using the new constructor syntax is preferred. – user19510 Aug 15 '18 at 14:22

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.