DEV Community

Cover image for Hack Solidity: Visibilities
Kamil Polak
Kamil Polak

Posted on

Hack Solidity: Visibilities

In Solidity you can specify the visibility of your function, i.e. to determine whether a function can be called externally by users, by other derived contracts, only internally or only externally.

By default, the function is public.

As described in the Solidity Documentation there are four types of visibility for functions and state variables:

  • external

  • public

  • internal

  • private

External functions are part of the contract interface, which means they can be called from other contracts and via transactions. Note, an external function cannot be called internally.

Public functions are part of the contract interface and can be either called internally or via messages.

Internal functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this.

Private functions and state variables are only visible for the contract they are defined in and not in derived contracts.

The problem with the visibility is that if you do not specify the desired type function that should be private will be public, and thus can be called by unauthorised people.

Let's look at the exapmle.

contract HashForEther {

    function withdraw() {
        // Winner if the last 8 hex characters of the address are 0.
        require(uint32(msg.sender) == 0);
        _sendWinnings();
     }

     function _send() {
         msg.sender.transfer(this.balance);
     }
}
Enter fullscreen mode Exit fullscreen mode

This is a simple game where to win the balance a user must generate an Ethereum address whose last 8 hex characters are 0.

As you can see the visibility of the _send function has not been specified. As a result, anyone can call this function (default mode is public) and get the balance.

Preventative techniques

Since all the default visibility for functions is public it is recommended to always specify the visibility of all functions in a contract, even if they are intentionally public.

Sources

Top comments (0)