Cointime

Download App
iOS & Android

Formally Verifying OpenZeppelin’s ERC-20 Implementation

Validated Project

Open Zeppelin’s ERC-20 reference implementation is widely used in Web3. A bug in it would be devastating for the many contracts that derive from it. But how do we know that it is correct? And how do we know contracts that derive from it do so correctly and do not introduce bugs?

In Part One of this series on formal verification, we explained how CertiK uses formal verification to mathematically prove the correctness of ERC-20 contracts that we audit. Let’s dive in and see what happens when we apply it to OpenZeppelin’s code.In Part One of this series on formal verification, we explained how CertiK uses formal verification to mathematically prove the correctness of ERC-20 contracts that we audit. Let’s dive in and see what happens when we apply it to OpenZeppelin’s code.

ERC-20 Standard Properties

At CertiK, we have written property templates that precisely describe the expected behaviors of ERC-20 token contracts. These templates are generic: our tools analyze the implementation details of each smart contract and adapt the templates accordingly. We have 38 property templates.

Let's look at some of the properties that we regularly verify on incoming ERC-20 token contracts. For the sake of readability, the formulas that follow are slightly simplified and omit some technical details that do not contribute to the overall understanding of the approach. CertiK's audit reports contain an appendix that reproduces the formulas that have been used during model checking. A list with all the formulas used in our ERC-20 verification approach is publicly available here.

The transferFrom() function in ERC-20 contracts requires special attention, as it needs to distinguish between the initiator of the transaction (the address is msg.sender), the accounts that spend and receive tokens, and because it needs to observe the limits imposed by the entries in _balances and _allowances.

Specifying Correct Allowance Updates

When transferFrom() succeeds, it must deduct the amount of tokens that have been transferred from the allowance that the sender has over the spender's account. However, many ERC-20 token contracts also allow the token owner to grant infinite allowance to another account. This is reflected by setting that account's allowance to the maximum value, i.e. to ((2^256)-1). Taking that exception into account, a correct allowance update can be specified by the following LTL formula 𝜑:

It states that when transferFrom() is invoked and terminates (without reverting) with a return value of true, we expect that the sender's allowance is either reduced by the amount of tokens in amt (the red subformula) or that the sender either is the owner of the transferred tokens or has unlimited allowance over the spender's tokens. In those cases, the allowance must remain unchanged (the blue subformula).

Specifying Dismissal of Transfers That Exceed the Allowance

Attempts to use transferFrom() to transfer an amount of tokens that exceeds one´s allowance should fail. This is formalized by 𝜓:

If the invocation of transferFrom() requests to transfer tokens from somebody other than their owner and if that transfer exceeds the sender's allowance, we expect the transaction to either revert, or to fail and signal its failure by returning false.

These are only two examples of the formalizations CertiK uses to capture the expected behaviors of ERC-20 token contracts. For more information about our properties and all technical details, refer to our property list.

OpenZeppelin's Reference Implementation for ERC-20 Contracts

The OpenZeppelin library provides reference implementations for many popular smart contracts. Its ERC-20 base contracts are popular and often used as building blocks for DeFi projects.

As many of the projects we audit contain contracts that derive from OpenZeppelin, we formally verified a set of 38 security properties on their ERC-20 reference implementation as of version 4.7.3. As can be seen the image below, all properties of the base contract are proven correct.

This result, however, tells us little about the security of actual ERC-20 token implementations, even when they derive from the OpenZeppelin contract! In actual blockchain projects, the reference implementation is modified by overriding its virtual functions and by introducing additional public APIs. What if someone makes a mistake?

The correctness of a base contract is generally not sufficient to ensure security in derived tokens! It is possible to introduce errors not only when overriding parts of the base implementation, but also by making changes to the contract’s state variables that were unforeseen in the base implementation.

OpenZeppelin implements their ERC-20 base contracts by making important state variables private. This ensures that contracts derived from them cannot simply destroy invariants that hold for those private variables. This encapsulation provides a certain level of protection from errors introduced within derived contracts.

Example: PancakeSwap's CAKE Token

PancakeSwap is one of the most popular decentralized exchanges. It is powered by the CAKE token, which implements the BEP20 standard (an extension of the ERC-20 standard). In general, CAKE tokens can be earned by staking and by providing liquidity to the exchange. Running our model checker on the CAKE token implementation successfully proves the basic ERC-20 behavior. The token implementation satisfies all of the properties that CertiK verifies on basic ERC-20 token contracts.

Conclusion

We’ve used formal verification to mathematically prove that OpenZeppelin’s reference ERC-20 implementation v4.8 meets basic ERC-20 properties. While it is not surprising that it does, this is good to know! We explained why just verifying OpenZeppelin’s implementation is not enough. You need to formally verify contracts that derive from it. Be sure to watch for our next blog post, where we discuss handling extensions to ERC-20 and other real-world challenges in verifying.

Read more: https://www.certik.com/resources/blog/7EELzmUpEOE7yhow8LpA3A-formally-verifying-openzeppelins-erc-20-implementation

Get the latest news here: Cointime channel — https://t.me/cointime_en

Comments

All Comments

Recommended for you

  • U.S. Congressman Mike Flood: Looking forward to working with the next SEC Chairman to revoke the anti-crypto banking policy SAB 121

     US House of Representatives will investigate Representative Mike Flood's recent statement: "Despite widespread opposition, SAB 121 is still operating as a regulation, even though it has never gone through the normal Administrative Procedure Act process." Flood said, "I look forward to working with the next SEC chairman to revoke SAB 121. Whether Chairman Gary Gensler resigns on his own or President Trump fulfills his promise to dismiss Gensler, the new government has an excellent opportunity to usher in a new era after Gensler's departure." He added, "It's not surprising that Gensler opposed the digital asset regulatory framework passed by the House on a bipartisan basis earlier this year. 71 Democrats and House Republicans passed this common-sense framework together. Although the Democratic-led Senate rejected it, it represented a breakthrough moment for cryptocurrency and may provide information for the work of the unified Republican government when the next Congress begins in January next year."

  • Indian billionaire Adani summoned by US SEC to explain position on bribery case

    Indian billionaire Gautam Adani and his nephew, Sahil Adani, have been subpoenaed by the US Securities and Exchange Commission (SEC) to explain allegations of paying over $250 million in bribes to win solar power contracts. According to the Press Trust of India (PTI), the subpoena has been delivered to the Adani family's residence in Ahmedabad, a city in western India, and they have been given 21 days to respond. The notice, issued on November 21 by the Eastern District Court of New York, states that if the Adani family fails to respond on time, a default judgment will be made against them.

  • U.S. Congressman: SEC Commissioner Hester Peirce may become the new acting chairman of the SEC

    US Congressman French Hill revealed at the North American Blockchain Summit (NABS) that Republican SEC Commissioner Hester Peirce is "likely" to become the new acting chair of the US Securities and Exchange Commission (SEC). He noted that current chair Gary Gensler will step down on January 20, 2025, and the Republican Party will take over the SEC, with Peirce expected to succeed him.

  • Tether spokesperson: The relationship with Cantor is purely business, and the claim that Lutnick influenced regulatory actions is pure nonsense

     a spokesperson for Tether stated: "The relationship between Tether and Cantor Fitzgerald is purely a business relationship based on managing reserves. Claims that Howard Lutnick's joining the transition team in some way implies an influence on regulatory actions are baseless."

  • Bitwise CEO warns that ETHW is not suitable for all investors and has high risks and high volatility

    Hunter Horsley, CEO of Bitwise, posted on X platform that he was happy to see capital inflows into Bitwise's Ethereum exchange-traded fund ETHW, iShares, and Fidelity this Friday. He reminded that ETHW is not a registered investment company under the U.S. Investment Company Act of 1940 and therefore is not protected by the law. ETHW is not suitable for all investors due to its high risk and volatility.

  • Musk said he liked the "WOULD" meme, and the related tokens rose 400 times in a short period of time

    Musk posted a picture on his social media platform saying he likes the "WOULD" meme. As a result, the meme coin with the same name briefly surged. According to GMGN data, the meme coin with the same name created 123 days ago surged over 400 times in a short period of time, with a current market value of 4.5 million US dollars. Reminder to users: Meme coins have no practical use cases, prices are highly volatile, and investment should be cautious.

  • Victory Securities: Funding Rates halved and fell, Bitcoin's short-term direction is not one-sided

    Zhou Lele, the Vice Chief Operating Officer of Victory Securities, analyzed that the macro and high-level negative impact risks in the cryptocurrency market have passed. The risks are now more focused on expected realization, such as the American entrepreneur Musk and the American "Efficiency Department" (DOGE) led by Ramaswamy. After media reports, the increase in Dogecoin ($DOGE) was only 5.7%, while Dogecoin rose by 83% in the week when the US election results were announced. Last week, the net inflow of off-exchange Bitcoin ETF was US$1.67 billion, and the holdings of exchange contracts and CME contracts remained high, but the funding rates halved and fell back, indicating that the direction of Bitcoin in the short term is not one-sided, and bears are also accumulating strength.

  • ECB board member Villeroy: Falling inflation allows ECB to cut interest rates

     ECB board member Villeroy de Galhau said in an interview that the decline in inflation allows the ECB to lower interest rates. In addition, the slow pace of price increases compared to average wages is also a factor in the rate cut. Villeroy de Galhau emphasized that the ECB's interest rate policy decision is independent of the Fed. Evidence shows that the ECB began to lower interest rates in early June, while the Fed lowered interest rates three months later. With the decline in inflation, we will be able to continue to lower interest rates. Currently, the market generally expects the ECB to cut interest rates by 25 basis points at the next meeting in December, but weaker data increases the possibility of a 50 basis point cut.

  • State Street warns Bitcoin craze could distract gold investors

    George Milling-Stanley, the head of gold strategy at Dominion Bank, warned that the rise of Bitcoin may mislead investors to overlook the stability of gold. He believes that Bitcoin is more like a return-driven investment, while gold provides long-term stability. He also criticized Bitcoin promoters for misleading the market by using the term "mining," and believes that gold is still a more reliable investment choice.

  • CertiK Chief Security Officer: The number of security incidents as of September 2023 has exceeded the total in 2022

    On October 23, at the ETH HK Side Event, a Web3 ecosystem security forum jointly held by CertiK and OKLink in Causeway Bay, Hong Kong, Professor Li Kang, Chief Security Officer of CertiK, shared his views on digital asset security construction. He pointed out that according to CertiK's statistics, the number of security incidents as of September 2023 has exceeded the total number in 2022. Hacking attacks and fraudulent behavior are still important threats, seriously hindering the development of the Web3 industry. Li Kang also mentioned the revolutionary feature of transparency in the Web3 field. The entire ecosystem can reduce security risks through public and transparent measures, such as asset management solutions. At the event, leaders from the Hong Kong Investment Promotion Agency, OKLink, and BlockSec shared their related work and latest developments in Web3 security construction. For example, CertiK and OKLink have received responses from multiple exchanges in asset tracking locking and data labeling. Finally, Li Kang hopes to further strengthen Hong Kong's position as a Web3 innovation gateway in the rapidly growing Asia-Pacific region through this sharing, and jointly promote the safe application and landing of Web3 technology.