Using EXTCODEHASH to secure your systems

How to safely integrate anyone's smart contract

What is the EXTCODEHASH?

The EVM opcode EXTCODEHASH was added on February 28, 2019. Not only does it help to reduce external function calls for compiled Solidity contracts, it also adds additional functionality. It gives you the hash of the code from an address. Since only contract addresses have code,  you could use this to determine if an address is a smart contract (taken from Openzeppelin-contracts):

function isContract(address account) internal view returns (bool) {
    bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;

    bytes32 codeHash;    
    assembly { codeHash := extcodehash(account) }

    return (codeHash != accountHash && codeHash != 0x0);
}

The account hash of 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for non-contract addresses, so-called Externally Owned Account (EOA). If an account was not used yet, the code hash of 0x0 will be returned, see the specification. Be aware though that in some cases this will return false even for contracts, when they are just created or when they have been destroyed. But if it returns true, you can be sure that it's a smart contract.

Whitelisting contract bytecodes in your system

The other interesting use case is whitelisting bytecodes. You can develop and compile different smart contract implementations that you want to allow in your system. Then you get the hash of that contract, e.g., just by using another contract with an extcodehash view function. Once you have the allowed bytecode hashes, you can whitelist them and allow only whitelisted contracts to be added and used in your system:

contract ExtCodeHashExample is Ownable {
    mapping (ExternalContractInterface=>bool) public isAddedContract;
    mapping (bytes32=>bool) public isWhitelistedByteCode;
    ExternalContractInterface[] public externalContracts;
    
    function addWhitelistedContractByteCode(bytes32 contractByteCode) external onlyOwner {
        isWhitelistedByteCode[contractByteCode] = true;
    }

    function registerNewContract(ExternalContractInterface externalContract) external {
        bytes32 codeHash;
        assembly { codeHash := extcodehash(externalContract) }
    
        require(isWhitelistedByteCode[codeHash], "Contract byte code is not whitelisted");
        require(!isAddedContract[externalContract], "Contract already added");
        
        externalContracts.push(externalContract);
        isAddedContract[externalContract] = true;
    }
}

That's great. We keep a list of every externally registered contract inside externalContracts. Anyone can create and register a contract, but thanks to the check of require(isWhitelistedByteCode[codeHash]), we know that those contracts must behave exactly like we want them to. Let's look at a gambling system as an example for how you could make use of such a system.

Gambling with external contracts

We will define an ExternalContractInterface. This interface will be used in our system and anyone can create contracts and register them in our system. Think of them in Defi terms as liquidity providers.

interface ExternalContractInterface {
    function game() external returns(ExtCodeHashExample);
    function payoutToWinner(address winner) external;
    function withdrawTo(uint roundId, address receiver) external;
    receive() external payable;
}

Player vs. Contracts: Now we will add the main function playGame. A user can send 0.55 ETH and the system will 'randomly' choose a winner, the player or the contracts. If the player wins, the current external contract is chosen to pay him 1 ETH. Once a round is over, meaning each external contract played one time, an external contract is chosen 'randomly' as winner. This external contract will be able to withdraw all of the ticket fees for the round.

function playGame() external payable {
    require(msg.value == totalPrice, "You must send 0.55 ETH");

    if (now % 2 == 0) { // unsafe randomness
        externalContracts[nextContractIndex].payoutToWinner(msg.sender);
    }

    nextContractIndex = (nextContractIndex + 1) % externalContracts.length;
    
    if (nextContractIndex == 0) {
        earningsForRound[roundId] = externalContracts.length * totalPrice;
        contractWinnerForRound[roundId] = externalContracts[now % externalContracts.length]; // unsafe randomness
        roundId++;
    }
}

Now we also need a withdraw function, so that the winning external contract can receive his funds. We could send the ETH directly to the contract, but we need a defined way for contract owners to withdraw money, so that they can't empty the whole contract whenever they want.

function withdraw(uint withdrawRoundId, address receiver) external {
    require(
        ExternalContractInterface(msg.sender) == contractWinnerForRound[withdrawRoundId],
        "Only winning contract can withdraw"
    );
    
    contractWinnerForRound[withdrawRoundId] = ExternalContractInterface(0); // prevent further withdrawals
    
    (bool success,) = receiver.call{value: earningsForRound[withdrawRoundId]}('');
    require(success, "Withdraw transfer failed");
}

Now let's look at an ExternalContractInterface implementation. This will implement the payoutToWinner and withdrawTo interface functions. This will be our accepted and honest implementation:

contract ExternalContractInterfaceHonest is ExternalContractInterface {
    ExtCodeHashExample public override game;
    
    constructor(ExtCodeHashExample _game) public {
        game = _game;
    }
    
    function payoutToWinner(address winner) external override {
        require(msg.sender == address(game), 'Only game can call this');
        
        (bool success,) = winner.call{value: 1 ether}('');
        require(success, "Liquidity transfer failed");
    }
    
    function withdrawTo(uint roundId, address receiver) external override {
        game.withdraw(roundId, receiver);
    }
    
    receive() external override payable {}
}

If you check the bytecode hash of this contract, it will be 0x0f3c98d10c122fd1440d0b59341c9b144658c79f7b3a612a99b7e970339d0ee4. This will be our whitelisted implementation. It fairly sends out 1 ETH to the winner.

Now imagine someone would create a contract with the following function:

function payoutToWinner(address winner) external override {
    require(msg.sender == address(game), 'Only game can call this');

    (bool success,) = attackerAddress.call{value: 1 ether}('');
    require(success, "Liquidity transfer failed");
}

This contract behaves maliciously. Instead of sending 1 ETH to the winner of the game, it sends it to the attacker. But since the bytecode is different, the hash will be 0x68af5afef67164fa697c8b978f3ee5dd0d799e151ef236bcaec53fa4d68895a7. This is not a whitelisted hash, so the attacker won't be able to register his contract in our system.

Full example: You can find a fully working example here that is perfectly usable inside Remix. Make sure to transfer ETH to the deployed interface contracts by clicking the 'CALLDATA Transact' button which transfers ETH using the fallback function. You can use the getExtCodeHash view function to read a deployed contract's bytecode and then whitelist it. The full example also automatically removes contracts with an ETH balance that is too low.

In summary: Secure & cheap

The new opcode costs only 400 in gas, so it's really not expensive. It allows you to figure out if an address is a contract, but more importantly it can be very powerful and will enable new possibilities for complex Defi systems. Have you used the opcode yourself already? Or do you know a project where they make use of this?


Markus Waas

Solidity Developer

More great blog posts from Markus Waas

  • Matic Logo

    How to use Matic in your Dapp

    Deploying and onboarding users to Matic to avoid the high gas costs

    Gas costs are exploding again, ETH2.0 is still too far away and people are now looking at layer 2 solutions. Here's a good overview of existing layer 2 projects: https://github.com/Awesome-Layer-2/awesome-layer-2 . Today we will take a closer look at Matic as a solution for your Dapp. Why Matic...

  • Migrating from Truffle to Buidler

    And why you should probably keep both.

    Why Buidler? Proper debugging is a pain with Truffle. Events are way too difficult to use as logging and they don't even work for reverted transactions (when you would need them most). Buidler gives you a console.log for your contracts which is a game changer. And you'll also get stack traces...

  • Factory

    Contract factories and clones

    How to deploy contracts within contracts as easily and gas-efficient as possible

    The factory design pattern is a pretty common pattern used in programming. The idea is simple, instead of creating objects directly, you have an object (the factory) that creates objects for you. In the case of Solidity, an object is a smart contract and so a factory will deploy new contracts for...

  • IPFS logo

    How to use IPFS in your Dapp?

    Using the interplanetary file system in your frontend and contracts

    You may have heard about IPFS before, the Interplanetary File System. The concept has existed for quite some time now, but with IPFS you'll get a more reliable data storage, thanks to their internal use of blockchain technology. Filecoin is a new system that is incentivizing storage for IPFS...

  • tiny-kitten

    Downsizing contracts to fight the contract size limit

    What can you do to prevent your contracts from getting too large?

    Why is there a limit? On November 22, 2016 the Spurious Dragon hard-fork introduced EIP-170 which added a smart contract size limit of 24.576 kb. For you as a Solidity developer this means when you add more and more functionality to your contract, at some point you will reach the limit and when...

  • Uniswap

    Using the new Uniswap v2 in your contracts

    What's new in Uniswap v2 and how to integrate Uniswap v2

    What is UniSwap? If you're not familiar with Uniswap yet, it's a fully decentralized protocol for automated liquidity provision on Ethereum. An easier-to-understand description would be that it's a decentralized exchange (DEX) relying on external liquidity providers that can add tokens to smart...

  • Continuous Integration

    Solidity and Truffle Continuous Integration Setup

    How to setup Travis or Circle CI for Truffle testing along with useful plugins.

    Continuous integration (CI) with Truffle is great for developing once you have a basic set of tests implemented. It allows you to run very long tests, ensure all tests pass before merging a pull request and to keep track of various statistics using additional tools. We will use the Truffle...

  • Devcon 6

    Upcoming Devcon 2021 and other events

    The Ethereum Foundation just announced the next Devcon in 2021 in Colombia

    Biggest virtual hackathon almost finished First of all, the current HackMoney event has come to an end and it has been a massive success. One can only imagine what kind of cool projects people have built in a 30 days hackathon. All final projects can be seen at:...

  • ERC-2020

    The Year of the 20: Creating an ERC20 in 2020

    How to use the latest and best tools to create an ERC-20 token contract

    You know what an ERC-20 is, you probably have created your own versions of it several times (if not, have a look at: ERC-20 ). But how would you start in 2020 using the latest tools? Let's create a new ERC-2020 token contract with some basic functionality which focuses on simplicity and latest...

  • hiring

    How to get a Solidity developer job?

    There are many ways to get a Solidity job and it might be easier than you think!

    You have mastered the basics of Solidity, created your first few useful projects and now want to get your hands on some real-world projects. Getting a Solidity developer job might be easier than you think. There are generally plenty of options to choose from and often times not a lot of...

  • People making fun

    Design Pattern Solidity: Mock contracts for testing

    Why you should make fun of your contracts

    Mock objects are a common design pattern in object-oriented programming. Coming from the old French word 'mocquer' with the meaning of 'making fun of', it evolved to 'imitating something real' which is actually what we are doing in programming. Please only make fun of your smart contracts if you...

  • React and Ethereum

    Kickstart your Dapp frontend development with create-eth-app

    An overview on how to use the app and its features

    Last time we looked at the big picture of Solidity and already mentioned the create-eth-app . Now you will find out how to use it, what features are integrated and additional ideas on how to expand on it. Started by Paul Razvan Berg, the founder of sablier , this app will kickstart your frontend...

  • Solidity Overview

    The big picture of Solidity and Blockchain development in 2020

    Overview of the most important technologies, services and tools that you need to know

    Now, I do not know about you, but I remember when I first started with Solidity development being very confused by all the tools and services and how they work in connection with one another. If you are like me, this overview will help you understand the big picture of Solidity development. As I...

  • Design Pattern Solidity: Free up unused storage

    Why you should clean up after yourself

    You may or may not be used to a garbage collectors in your previous programming language. There is no such thing in Solidity and even if there was a similar concept, you would still be better off managing state data yourself. Only you as a programmer can know exactly which data will not be used...

  • How to setup Solidity Developer Environment on Windows

    What you need to know about developing on Windows

    Using Windows for development, especially for Solidity development, can be a pain sometimes, but it does not have to be. Once you have configured your environment properly, it can actually be extremely efficient and Windows is a very, very stable OS, so your overall experience can be amazing. The...

  • Avoiding out of gas for Truffle tests

    How you do not have to worry about gas in tests anymore

    You have probably seen this error message a lot of times: Error: VM Exception while processing transaction: out of gas Disclaimer : Unfortunately, this does not always actually mean what it is saying when using Truffle , especially for older versions. It can occur for various reasons and might be...

  • Design Pattern Solidity: Stages

    How you can design stages in your contract

    Closely related to the concept of finite-state machines, this pattern will help you restrict functions in your contract. You will find a lot of situations where it might be useful. Any time a contract should allow function calls only in certain stages. Let's look at an example: contract Pool {...

  • Web3 1.2.5: Revert reason strings

    How to use the new feature

    A new Web3 version was just released and it comes with a new feature that should make your life easier. With the latest version 1.2.5 , you can now see the the revert reason if you use the new handleRevert option. You can activate it easily by using web3.eth.handleRevert = true . Now when you use...

  • Gaining back control of the internet

    How Ocelot is decentralizing cloud computing

    I recently came across an ambitious company that will completely redefine the way we are using the internet. Or rather, the way we are using its underlying infrastructure which ultimately is the internet. While looking at their offering, I also learned how to get anonymous cloud machines, you...

  • Devcon 5 - Review

    Impressions from the conference

    I had a lot to catch up on after Devcon. Also things didn't go quite as planned, so please excuse my delayed review! This year's Devcon was certainly stormy with a big typhoon warning already on day 1. Luckily (for us, not the people in Tokyo), it went right past Osaka. Nevertheless, a lot of...

  • Devcon 5 - Information, Events, Links, Telegram

    What you need to know

    Devcon 5 is coming up soon and there are already lots of events available, information about Osaka and more. Here is a short overview: Events Events Calendar Events Google Docs Events Kickback Most events are in all three, but if you really want to see all, you will have to look at all three...

  • Design Pattern Solidity: Off-chain beats on-chain

    Why you should do as much as possible off-chain

    As you might have realized, Ethereum transactions are anything but cheap. In particular, if you are computing complex things or storing a lot of data. That means sometimes we cannot put all logic inside Solidity. Instead, we can utilize off-chain computations to help us. A very simple example...

  • Design Pattern Solidity: Initialize Contract after Deployment

    How to use the Initializable pattern

    There are a few reasons why you might want to initialize a contract after deployment and not directly by passing constructor arguments. But first let's look at an example: contract MyCrowdsale { uint256 rate; function initialize(uint256 _rate) public { rate = _rate; } } What's the advantage over...

  • Consensys Blockchain Jobs Report

    What the current blockchain job market looks like

    Consensys published their blockchain jobs report which you can checkout in their Blockchain Developer Job Kit . The most interesting aspects are Blockchain developer jobs have been growing at a rate of 33x of the previous year according to LinkedIns jobs report Typical salary is about...

  • Provable — Randomness Oracle

    How the Oraclize random number generator works

    One particularly interesting approach by Provable is the usage of a hardware security device, namely the Ledger Nano S. It uses a trusted execution environment to generate random numbers and provides a Provable Connector Contract as interface. How to use the Provable Randomness Oracle? Use the...

  • Solidity Design Patterns: Multiply before Dividing

    Why the correct order matters!

    There has been a lot of progress since the beginning of Ethereum about best practices in Solidity. Unfortunately, I have the feeling that most of the knowledge is within the circle of experienced people and there aren’t that many online resources about it. That is why I would like to start this...

  • Devcon 5 Applications closing in one week

    Devcon 5 Applications closing

    Watch out for the Devcon 5 applications. You only have one week left to apply either as Buidler Student Scholarship Press Devcon is by far the biggest and most impressive Ethereum conference in the world. And it's full of developers! I am especially excited about the cool location this year in...

  • Randomness and the Blockchain

    How to achieve secure randomness for Solidity smart contracts?

    When we talk about randomness and blockchain, these are really two problems: How to generate randomness in smart contracts? How to produce randomness for proof-of-stake (POS) systems? Or more generally, how to produce trusted randomness in public distributed systems? There is some overlap of...