Zero-knowledge proof technology explained: a rising star that ignites the great power of DeFi

IntermediateJan 12, 2024
This article introduces the privacy challenges caused by transparency in DeFi, and explains how to use zk zero-knowledge proof technology to solve problems such as front-running transactions, liquidity manipulation, and credit lending.
Zero-knowledge proof technology explained: a rising star that ignites the great power of DeFi

I. Introduction

Decentralized Finance (DeFi) is a crucial growth direction in the current field of financial innovation. In DeFi, it is essential to hide transaction information and protect user privacy. As DeFi continues to expand and evolve, various projects emerge endlessly, displaying great vitality. And zero-knowledge proof (ZK) technology has opened up new possibilities for privacy protection in DeFi. ZK technology allows one party to prove to another party that they know a piece of information without revealing any specific details about that information. This technology is used in DeFi applications such as ZigZag unyfy and ZK DEX, which has greatly improved the privacy protection capabilities of DeFi, especially the protection of transaction information. It is foreseeable that the widespread application of ZK technology will innovate the way in which DeFi and the entire cryptocurrency field are handled, promoting the future growth throughout the field and making major breakthroughs.

2. Privacy Challenges in DeFi

There are no secrets on the blockchain, and DeFi’s data transparency is incontrovertible. Take a certain trade on Uniswap V3 as an example, we can easily view the transaction details through the Etherescan website (shown in Figure 1). For example, the address [0 x 3A 4 D…a 6 f 2] exchanged 2 WETH for 17, 654, 123, 249, 375 Bonk on Uniswap V3, and the trading fee was 0.0046 Ether. Key information such as the sender, receiver, transaction amount (Value), and transaction fee in these transactions are all publicly available.

Figure 1 Transaction details disclosed on etherescan

We can also view all transactions recorded under the address [0 x 3A 4 D…a 6 f 2] (as shown in Figure 2). If conditions permit, once can infer the true identity of this address in the real world.

Figure 2 A list of all transactions for a specific address is public on etherescan

However, DeFi’s data transparency may have some downsides. If you are a DeFi whale, every transaction you make may attract market attention. For example, when a whale withdraws 11.24 million WOO (approximately $4.2 million) from Binance, this transaction will draw widespread attention. Similarly, any large-value payments or institutional-level transactions may also trigger extensive public concern.

Other market participants may make buying and selling decisions based on these trading behaviors, which may adversely affect your investment strategy. For example, you invest a large amount of money in a certain project, but once your transaction is noticed by the market, other investors may follow suit, causing asset prices to rise, thereby increasing your investment costs. In addition, your selling operation may also trigger market panic, causing prices to fall and affecting your investment returns.

This situation highlights the urgent need for privacy protection among DeFi projects and users. If we don’t want the details of our transactions to be known to the public, we can choose to keep certain information about our DeFi transactions private.

ZK technology can ensure the legitimacy of transactions while hiding transaction details. Users need to submit two types of information: one is a transaction (a private transaction) that partially hides details (such as transaction recipient or amount), and the other is a ZK certificate about this hidden information. Verifying the legitimacy of a private transaction is actually verifying the corresponding ZK certificate.

3. Unlocking the potential of DeFi: opportunities brought by ZK technology

3.1 The role of ZK technology in combating front-running trading

Suppose you are lucky enough to learn that a large company is about to purchase a large amount of a certain asset. You may choose to purchase this asset before the company does. Then, when the price of the asset is pushed up by the heavy buying of that company, you sell it for a profit. In this case, your trade before the big players is a front-running trade.

Front-running is an investment strategy in financial trading, typically occurring on exchanges such as Uniswap. This is because transactions in the blockchain are known to the public and transaction confirmation takes a certain amount of time. Therefore, some malicious traders may increase the trading gas fee to allow their transactions to be mined and confirmed before other people’s transactions, so as to achieve the purpose of front-running transactions.

Front-running trades can cause losses to other traders because it changes the original trading environment so that other players’ trades may fail to proceed as originally planned. On the other hand, attackers initiate front-running transactions to make profits for themselves. They can make profits before the price changes. Therefore, many DeFi projects are also taking various measures to prevent front-running transactions.

ZK technology plays a key role in resisting front-running transactions. Below, we take the sandwich attack, also a common type of front-running transaction, in Decentralized Exchange (DEX) as an example for case analysis.

3.1.1 Case Study: Sandwich Attack in DEXs

What is a sandwich attack?

Assume that on a DEX, there is a liquidity pool with a reserve of 100 ETH / 300, 000 USDT. Alice places an order purchasing USDT, exchanging 20 ETH for USDT. When she submits the order, the DEX returns a result based on the current reserve of the liquidity pool, telling Alice that approximately 50,000 USDT is available to buy. But in fact, Alice only got 45,714 USDT in the end.

Here, let’s first briefly explain why Alice can use 20 ETH to purchase 50, 000 USDT. This DEX adopts the automated market maker model (AMM), which automatically calculates the buying and selling price through the Constant Product Market Maker algorithm (CPMM). CPMM is a currently popular automated market maker algorithm that maintains a constant product of two assets in the trading pool to achieve liquidity supply and automatically adjust asset prices. In this example, the amount of USDT that Alice can buy is calculated by using the formula [50, 000 = 300, 000-(100* 300, 000)/(100+ 20) (assuming no handling fees)].

Alice did not buy the expected amount of USDT because she suffered a sandwich attack.

Sandwich attacks mainly occur in AMM-based DEXs. In this attack, the attacker places two transactions around the victim’s regular transactions to manipulate asset prices and profit from the victim’s losses. These two transactions are front-running transactions and follow-up transactions respectively. The transaction before the regular transaction is called the front-running transaction, and the transaction after the regular transaction is called the follow-up transaction.

So, how did Alice’s sandwich attack work? As shown in Figure 3.

Figure 3 How Sandwich attack works

  1. The attacker initiates a front-running transaction: Before the transaction initiated by Alice to purchase USDT was executed, the attacker also initiated a transaction to purchase USDT (front-running transaction), that is, exchanging 5 ETH for USDT. Moreover, the gas fee paid by the attacker to the miner for this transaction is higher than that of Alice, so the attacker’s transaction will be executed before Alice.

  2. After the attacker executed the transaction to purchase USDT, he got approximately 14, 286 USDT from the liquidity pool, that’s, 14, 286 ≈ 300, 000-( 100* 300, 000)/( 100+ 5). The reserve of the liquidity pool changed from 100 ETH / 300,000 USDT to 105 ETH / 285,714 USDT. However, Alice does not know that the reserve of the liquidity pool has changed between the time she submits the transaction and the time her transaction is executed.

  3. Execute Alice’s regular transaction: Subsequently, Alice’s regular transaction starts to execute.

  4. After Alice’s transaction to purchase USDT was executed, she received 45, 714 USDT from the liquidity pool, that’s, 45, 714 ≈ 285, 714-( 105* 285, 714)/( 105+ 20) calculated according to the constant product function. The reserve of liquidity changed from 105 ETH / 285, 714 USDT to 125 ETH / 240, 000 USDT. Therefore, Alice should have been able to buy 50,000 USDT with 20 ETH, but now she can only buy 45,714 USDT due to changes in the liquidity pool caused by the attacker’s transaction. Alice lost approximately 4286 USDT (4286 = 50,000-45,714).

  5. The attacker’s follow-up transaction: Finally, the attacker initiated a transaction (follow-up transaction) again, that is, exchanging 14, 286 USDT for ETH (the 14, 286 USDT was purchased just now).

  6. After the attacker’s follow-up transaction was executed, he got 7 ETH from the liquidity pool, that’s, 7 ≈ 125-(125* 240, 000)/(240, 000+ 14, 286). The liquidity pool’s reserve changed from 125 ETH / 240,000 USDT to 118 ETH / 254,286 USDT. Therefore, the attacker only spent 5 ETH at the beginning, but finally got 7 ETH and gained 2 ETH in profit (2 = 7-5).

During the whole sandwich attack process, the attacker initiated a total of two transactions, namely a front-running transaction and a follow-up transaction. Because of the front-running trade, Alice lost approximately 4286 USDT. By combining the front-running and follow-up trades, the attacker obtained a net income of 2 ETH.

In DEXs, the visibility of transactions is a key factor that brings forth sandwich attacks, especially in AMM protocols. These protocols make real-time transaction information on DEXs public. This high level of transparency makes it possible for attackers to observe and analyze transaction flows, aiming to find opportunities to conduct sandwich attacks.

3.1.2 ZK technology can resist sandwich attacks

The application of ZK technology can significantly reduce the possibility of sandwich attacks. By using ZK technology to hide transaction volume, asset types, user or liquidity pool balances, user identities, transaction instructions and other protocol-related information, we can effectively improve the privacy of transaction data. As a result, it is difficult for the attacker to obtain complete transaction information to implement a sandwich attack.

In addition, ZK technology can not only resist sandwich attacks, but ZK-based private transactions can also make it more difficult to judge user behavior models. Any third party that attempts to collect blockchain data to analyze account historical transactions, infer behavioral patterns, explore activity cycles, transaction frequencies or preferences, etc., will face challenges. This kind of analysis, known as behavioral model inference, not only violates user privacy, but can also pave the way for honeypot attacks and phishing scams.

3.2 Prevent liquidity manipulation based on ZK technology

Liquidity manipulation and front-running trading are both attack methods in DeFi. Both attack methods involve taking advantage of market information and transaction speed to obtain benefits, but their specific strategies and operations are different.

Front-running is taking advantage of information, while liquidity manipulation is taking advantage of market activity to mislead other traders. The former mainly makes profits by obtaining and using undisclosed important information, while the latter misleads other investors by creating false market activity, causing them to make unfavorable trading decisions.

ZK technology can not only play a key role in resisting front-running trades, it can also help prevent liquidity manipulation.

3.2.1 Case Study: Liquidity Manipulation Using Oracles

Suppose you are buying apples in a busy fruit market. Market prices typically fluctuate based on changes in supply and demand. You usually watch prices over a period of time and then decide whether to buy based on the average price. Now imagine that a very wealthy buyer enters the market and he really wants to buy apples. He started buying apples in large quantities, regardless of the price. This will cause Apple’s price to skyrocket in a short period of time. If you still buy Apple based on this price, you’re probably paying more than it’s actually worth.

This example can help us better understand the working principle of the TWAP (Time-Weighted Average Price, Time-Weighted Average Price) oracle and the concept of liquidity manipulation. The act of deciding to buy apples based on the average price is similar to the operation of the TWAP oracle, and the large purchase of apples by wealthy businessmen causing prices to rise is similar to liquidity manipulation.

The TWAP oracle determines asset prices by calculating the average transaction price over a period of time. The more recent the transaction, the greater the impact on the average price. If someone makes a large number of transactions or trades with a large amount of money in a short period of time, which may significantly affect the average price of an asset, this is liquidity manipulation. Liquidity manipulation can artificially raise or lower asset prices, resulting in inaccurate price information. If someone wants to use the TWAP oracle to intentionally increase the price of an asset, he can use a large amount of money to purchase the asset in the short term, causing the price to rise temporarily. If the asset price skyrockets during this time window, the TWAP oracle may treat this higher price as the asset price.

Liquidity manipulation of TWAP oracles can have a significant impact on DeFi protocols, especially emerging tokens with low liquidity. These DeFi protocols often make financial decisions, such as liquidation, lending, etc., based on the price of the asset. If price information is inaccurate or unreliable, it may lead to wrong decisions, thereby causing losses to users. Therefore, it is crucial to protect TWAP oracles from liquidity manipulation.

3.2.2 ZK technology can resist liquidity manipulation

ZK technology can help resist liquidity manipulation in the TWAP oracle. A smart contract can be designed to rely on a TWAP oracle to obtain the price of an asset. If an attacker performs liquidity manipulation, the price obtained from the TWAP oracle may surpass the preset acceptable range. In this case, the contract will temporarily stop its operations. It will then recalculate and confirm the asset price based on ZK technology.

To use ZK technology to calculate asset prices, you need to firstly add a wrapper contract to the TWAP oracle. The contract can directly access a number of N price reports, or record a number of N checkpoint values ​​of the price at arbitrary intervals. Once these N data points are available within a given interval, a ZK proof can be constructed to prove the median of the unsorted array of prices. The unsorted price array is labeled as a column vector x, of length N. The following is the calculation process of asset prices based on ZK technology:

  1. The proof can be verified in either of the following two ways. In either case, the prover cannot arbitrarily choose a price array as input.
  • Retrieve array values ​​from contract storage and use them as public inputs to on-chain validators;
  • A hash chain is gradually formed through the hash function, representing the array as a single hash value and using that value in the on-chain validator.
  1. There is an N x N matrix A (square matrix). When the matrix is ​​multiplied by the column vector x, a column vector y is generated. A is an invertible permutation matrix, but since there may be duplicate price values, A is not necessarily unique, and A contains only binary values.

  2. The values ​​in y are ordered. What’s to be stressed is < cannot be used because there may be duplicate price values.

  3. The circuit’s public output m is the median value of y. The proof shows that N is a static value when the circuit is compiled, and it must be an odd number.

According to the above process, a median price m is output based on ZK technology, which is tamper-proof. The median m, to a certain extent, can prevent liquidity manipulation. In order to achieve this, we need to limit the value of y to ensure that in each block, the value of y is only inserted once, or the number of insertions is kept within an acceptable number.

3.3 ZK technology empowers lending platforms

As mentioned above, ZK technology is resistant to front-running and liquidity manipulation in DEXs. So, can we further explore the application possibilities of ZK technology in other DeFi scenarios? For example, ZK technology can also play a key role in lending, an important part of DeFi projects.

3.3.1 The Key to Lending: How to Assess Borrower Creditworthiness

On traditional lending platforms, the loan application process usually covers five steps: application submission, credit assessment, loan approval, loan issuance and repayment. Among them, the credit assessment is crucial. Borrowers must prove that their income meets the standard and they have the ability to repay. During the evaluation process, the platform will conduct an in-depth investigation of the borrower’s credit history, including income, liabilities, and past repayment records, to ensure that the borrower has the ability to repay the loan. Only on this basis will the platform consider approving the loan application.

However, when you turn to DeFi lending platforms such as Ghost or Compound, the situation will be different. Due to their decentralized nature, most DeFi lending platforms do not have the KYC (Know Your Customer) procedures and risk assessment procedures of traditional banks, and they cannot investigate the credit status of borrowers through joint credit bureaus. In this case, you may be wondering, how will my credit be evaluated?

On DeFi lending platforms, you can prove your creditworthiness through reputation token proof. Reputation token is a credit system based on blockchain technology, which uses digital tokens to represent and quantify users’ reputation. The number of reputation tokens has become a key indicator for evaluating a user’s creditworthiness. The greater the number of tokens, the better the user’s reputation and corresponding improvement in credit rating, making it possible to obtain more loan lines on the DeFi lending platform.

However, the generation of reputation tokens relies on users’ transaction history and financial information, which may violate users’ privacy rights.

3.3.2 Evaluate borrower’s credit: reputation token based on ZK technology

ZK technology protects user privacy. The combination of ZK technology and reputation tokens can protect user privacy while maintaining and tracking their reputation in the network.

Users can use ZK technology to generate reputation tokens without disclosing historical transactions. On the one hand, users can generate proof of historical transactions based on ZK technology; on the other hand, the proof is verified by a smart contract (often called a reputation token generation contract), and reputation tokens can be generated if the verification passes.

In addition, on some DeFi lending platforms that require over-collateralization, reputation tokens can reduce collateral requirements, thereby solving the problem of over-collateralization and improving market liquidity. And the application of reputation tokens based on ZK technology goes beyond DeFi lending platforms to be widely used in insurance, medical subsidies and other fields.

4. Summary & Expectations

This article explores the various application scenarios of ZK technology for privacy protection in DeFi, especially its key role in lending and its great potential to resist front-running, and liquidity manipulation. As we explore DeFi, we face several challenges, especially issues related to privacy and security. Privacy challenges in the DeFi ecosystem are a key topic, and ZK technology provides a unique solution that not only enhances privacy protection, but also improves transaction efficiency and security. If you want to introduce ZK technology to your DApp, please feel free to contact Salus.

Looking to the future, ZK technology may be applied in deeper DeFi fields, such as liquidity staking, derivatives protocols, real-world assets, insurance, etc. Salus focuses on researching and exploring the application of ZK technology in DeFi and other Ethereum application layer projects. We sincerely invite blockchain researchers, technology developers and all professionals in the web3 field around the world to work with us to promote the in-depth development and widespread application of ZK technology, so as to drive the growth of DeFi and even the industry as a whole.

Disclaimer:

  1. This article is reprinted from [odaily]. All copyrights belong to the original author [LZ]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Start Now
Sign up and get a
$100
Voucher!
Create Account