EDIT: The function will return false if it is invoked from a contract's constructor (because the contract has not been deployed yet).
The code should be used very carefully, if at all, to avoid security hacks such as:
https://www.reddit.com/r/ethereum/comments/916xni/how_to_pwn_fomo3d_a_beginners_guide/ (archive)
To repeat:
Do not use the EXTCODESIZE check to prevent smart contracts from calling a function. This is not foolproof, it can be subverted by a constructor call, due to the fact that while the constructor is running, EXTCODESIZE for that address returns 0.
See sample code for a contract that tricks EXTCODESIZE to return 0.
If you want to make sure that an externally owned account (EOA) is calling your contract, a simple way is require(msg.sender == tx.origin)
. However, preventing a contract is an anti-pattern with security and interoperability considerations.
This will need revisiting when account abstraction is implemented.
Prior answer.
Yes, the function works.
EXTCODESIZE is the EVM opcode for getting the size of the code at an address.
0x3b EXTCODESIZE Get size of an account's code
A contract cannot fool EXTCODESIZE to return zero for the contract's size.
Also, an externally owned account (EOA) cannot fool this code into making it think that the EOA is a contract. This is because an EOA has no code (zero length) and you can't put code into an EOA any more feasibly than it is to find the private key of a contract.
The function does not have any dependency on Proof of Stake and will continue working.