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

  • Binance assisted Taiwan’s law enforcement agencies in cracking a major virtual asset case involving nearly NT$200 million

    On May 17th, Binance announced that the Financial Crime Compliance department (FCC) of Binance, in collaboration with the Taiwan Department of Justice Investigation Bureau, has successfully cracked a major criminal case involving money laundering of virtual assets, with an involved amount of nearly 200 million New Taiwan dollars. Throughout the entire case, Binance provided support to Taiwan's crime fighters, offering crucial intelligence and assistance, and played a key role in promoting the investigation.

  • $1.2 billion in notional value of BTC options and $930 million in ETH options are set to expire

    Greeks.live data shows that on May 17th, 18,000 BTC options with a put/call ratio of 0.63 and a maximum pain point of $63,000 (nominal value of $1.2 billion) will expire. Additionally, 320,000 ETH options with a put/call ratio of 0.28 and a maximum pain point of $3,000 (nominal value of $930 million) will also expire. Greeks.live states that this week, inspired by the meme stock craze in the US, BTC ETFs have seen significant inflows, causing BTC to surge above $65,000. However, the rest of the crypto market remains weak, with trading volume continuing to decline, and the divergence in the options data of BTC and ETH reflects this. Looking at the structure of bulk trades and market trades, the downward trend in IV for major deadlines has ended and entered a consolidation phase, with limited downside potential at present. BTC longs and shorts are relatively balanced, while the weak ETH price has led to a continuous decline in market confidence, with selling calls becoming the absolute main transaction.

  • Tether CEO: 1 billion USDT will be issued on Tron Network, but it has been authorized but not yet issued

    On May 17th, Tether CEO Paolo Ardoino announced that 1 billion USDT had been issued on the Tron Network early this morning Beijing time, but not yet released. This means that the amount will be used as inventory for the next issuance request and chain exchange.

  • On-chain indexing service Subsquid completes financing of US$17.5 million, with participation from DFG and others

    Subsquid, a chain indexing service, announced the completion of a $6.3 million financing through the CoinList community. As of now, its total financing amount has reached $17.5 million, with participation from DFG, Hypersphere, Zee Prime, Blockchange, and Lattice. It is reported that its native token, SQD, is scheduled to be listed this Friday. The Subsquid SDK has been integrated with Google BigQuery, allowing developers to use Google's technology to analyze blockchain data and reduce the data costs of large-scale deployment in the blockchain and developer communities.

  • Optimism 2024 Q1 Report: The implementation of EIP-4844 reduces L1 submission costs by 99%

    Optimism has released its Q1 2024 report, which shows that the number of daily active addresses has reached 89,000 (a 23% increase compared to the previous period), and the daily transaction volume has increased to 470,000 (a 39% increase compared to the previous period). These indicators are slightly lower than the historical high point in Q3 2023.

  • US Secret Service seizes domain used to run cryptocurrency scam

    On May 17th, the US Secret Service seized a domain used for cryptocurrency trust fraud in a "pig-killing plate" scam. In the "pig-killing plate" scam, scammers contact victims through various means, including dating apps, social media websites, and even random text messages disguised as wrong numbers.

  • Peaq Completes $20 Million Fundraising via CoinList Launch

    Peaq, a Layer1 blockchain applicable for DePIN and machine RWA, announced on X platform that it raised $20 million through its native token Launch, which was launched on CoinList from May 9 to May 16. As of now, over 145,000 community members have completed over-subscriptions of over $36 million. The new funds will be used to accelerate the growth of the peqosystem and further consolidate various ecosystem and community plans.

  • LocalMonero to Shut Down in Six Months Amid Regulatory Pressure and Internal Factors

    LocalMonero, a peer-to-peer exchange for trading privacy coin Monero (XMR), has disabled all trades and will be taken down in six months, according to parent company AgoraDesk. The company cited a combination of internal and external factors for the decision, but did not provide specifics. The move follows a trend of P2P crypto trading platforms shutting down due to regulatory challenges, including LocalBitcoins and Paxful. LocalMonero's closure also comes amid pressure from regulatory authorities on privacy coins, with exchanges including Binance and Coinbase delisting tokens like Monero and Zcash.

  • French securities regulator issues new warning to Bybit

    The French securities regulator has issued a new warning to the cryptocurrency exchange Bybit, urging customers to make arrangements for the possibility that the platform may suddenly stop providing services to French customers. The Financial Markets Authority (AMF) stated in a notice on Thursday that the exchange is not registered as a Digital Asset Service Provider (DASP), and therefore is providing services illegally in France. Bybit has been blacklisted by the AMF since May 20, 2022 for illegal operations.

  • 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.