Solidity – How Fallback Function Rejecting Ether Works

contract-developmentfallback-functionSecuritysolidity

A contract in Solidity can have a fallback function like:

// This contract rejects any Ether sent to it. It is good
// practise to include such a function for every contract
// in order not to loose Ether.
contract Rejector {
    function() { throw; }
}

What underlying mechanism in the EVM allows for this?

Best Answer

The fallback function is a feature of the Solidity language, and is not an EVM-level feature. Solidity simply parses the msg.data field in transactions according to the ABI:bytes4(sha3("functionName(argTypes)"))

When the code is compiled, the ABI signatures are stored in the compiled code, and when the code is called, it looks to see if the first four bytes of the msg.data corresponds to one of its functions. If so, it calls that function with the rest of msg.data interpreted as arguments. If not, the fallback function is called.

Serpent could implement a similar system, but I don't know enough about Serpent to say how it could be implemented.