Zero-Knowledge Technology: Illuminating the New Star of DeFi
Introduction
Decentralized Finance (DeFi) represents a significant direction in the innovation of the financial sector. In DeFi, the concealment of transaction information and the maintenance of user privacy are crucial. As DeFi continues to expand and deepen, a variety of projects emerge, brimming with vitality. The application of Zero-Knowledge (ZK) technology opens new possibilities for privacy protection in DeFi. ZK technology allows one party to prove to another that they know certain information without revealing any specific details about that information. This technology, used in DeFi projects such as ZigZag, unyfy, and OKX's ZK DEX, significantly enhances the privacy protection capabilities of DeFi, especially in the protection of transaction information. It is foreseeable that the widespread application of ZK technology will revolutionize the approach to DeFi and the entire cryptocurrency domain, driving the future development of the field and achieving significant breakthroughs.
Challenges of Privacy in DeFi
In the realm of blockchain, there are no secrets, and the transparency of data in DeFi is indisputable. Take, for instance, a specific transaction on Uniswap V3. We can easily access the details of this transaction through the Etherescan website (as illustrated in Figure 1). For example, the address 0x3A4D...a6f2 executed a trade on Uniswap V3, exchanging 2 WETH for 17,654,123,249,375 Bonk, with a transaction fee of 0.0046 Ether. Key information such as the sender (From), receiver (To), transaction amount (Value), and transaction fee (Transaction Fee) in these trades are all publicly accessible.
Figure 1: Transaction Details Publicly Available on Etherescan
Furthermore, we can examine all the transaction records associated with the address 0x3A4D...a6f2 (as shown in Figure 2). Given the right conditions, it's also possible to infer the real-world identity of this address.
Figure 2: Transaction List of a Specific Address Publicly Available on Etherescan
While the transparency of data in DeFi has its advantages, it can also lead to some negative consequences. For instance, if you are a DeFi 'whale', each of your transactions could attract market attention. An example of this is when a whale withdrew 11.24 million WOO tokens (worth about $4.2 million) from Binance, which garnered significant attention. Similarly, any large payments or institutional-level trading activities can also attract widespread public interest.
Other market participants might make buying or selling decisions based on your trading activities, negatively impacting your investments. For example, if you were to invest heavily in a project, and once your transaction becomes known to the market, other investors may follow suit, essentially driving up the asset price and increasing your investment cost. Additionally, your selling actions could trigger market panic, leading to a price drop and affecting your investment returns.
These scenarios highlight the need for privacy protection for both DeFi project operators and users. If we don't want our transaction information to be public, we could opt to make DeFi transaction data partially public, concealing specific details.
Zero-knowledge proof can conceal transactions while ensuring their validity. Users need to submit two things: one is a transaction that hides some specific data (like the transaction recipient or the amount), known as a private transaction, and the other is a zero-knowledge proof about the hidden data. Validating the private transaction involves verifying this zero-knowledge proof.
Unlocking DeFi's Potential: The Opportunities Brought by ZK Technology
The Role of ZK Technology in Combating Front-Running Transactions
Imagine you are privy to information that a large company is about to purchase a significant amount of a certain asset. You might decide to buy that asset before the company does. Then, when the company's substantial purchasing activity drives up the asset's price, you sell it for a profit. In this scenario, your transaction ahead of the company constitutes a front-running transaction.
Front-running is an investment strategy in financial transactions, often occurring in exchanges like Uniswap. This happens because transactions on the blockchain are public and require time for confirmation. Consequently, some malicious traders might choose to increase their transaction Gas fees to prioritize their transactions for mining confirmation, achieving front-running.
Front-running can harm other traders as it changes the original trading environment, potentially disrupting other traders' transactions from proceeding as planned. On the other hand, the purpose of attackers initiating front-running transactions is to profit for themselves, capitalizing on price movements before they occur. As a result, many DeFi projects are exploring various ways to prevent front-running.
ZK technology can play a crucial role in combating front-running. The following is a case analysis using the sandwich attack in Decentralized Exchanges (DEXs) as an example, which is a common type of front-running transaction.
Case Analysis: Sandwich Attacks in DEXs
What is a Sandwich Attack?
Imagine a DEX with a liquidity pool where the reserve status is 100 ETH / 300,000 USDT. Alice initiates a transaction to buy USDT, exchanging 20 ETH for it. When she submits her transaction, the DEX, based on the current reserve status of the liquidity pool, returns a result indicating Alice can get approximately 50,000 USDT. However, Alice ends up receiving only 45,714 USDT.
Here is an explanation of why Alice could buy 50,000 USDT with 20 ETH. This DEX employs an Automated Market Maker (AMM) model, using the Constant Product Market Maker (CPMM) algorithm to automatically calculate buying and selling prices. CPMM, a widely used AMM algorithm, maintains a constant product of the two assets in the trading pool to provide liquidity and automatically adjust asset prices. In this example, Alice's expected USDT quantity is calculated using the formula , assuming no transaction fees.
Alice didn't receive the expected amount of USDT because she was subjected to a sandwich attack.
Sandwich attacks mainly occur in AMM-based DEXs. In a sandwich attack, the attacker places two trades around the victim's regular transaction to manipulate asset prices and profit from the victim's loss. These two transactions are the front-running transaction and the follow-up transaction, with the trade before the regular transaction known as the front-running transaction, and the one following it as the follow-up transaction.
So, how exactly did Alice fall victim to a sandwich attack? As shown in Figure 3.
Figure 3: The Process of a Sandwich Attack.
-
Attacker's Front-Running Transaction: Before Alice's transaction to buy USDT is executed, the attacker also initiates a transaction to buy USDT (the front-running transaction), exchanging 5 ETH for USDT. The attacker pays a higher gas fee than Alice, ensuring their transaction is executed first.
-
After the attacker's transaction is executed, they receive approximately 14,286 USDT from the liquidity pool . The liquidity pool's reserves change from the initial state of 100 ETH / 300,000 USDT to 105 ETH / 285,714 USDT. Alice, in the time between submitting and executing her transaction, is unaware of this change in the liquidity pool's reserve status.
-
Victim's Regular Transaction: Then, Alice's regular transaction is executed.
-
After Alice's transaction is executed, she receives 45,714 USDT from the liquidity pool , changing the reserve status from 105 ETH / 285,714 USDT to 125 ETH / 240,000 USDT. Alice, who should have received 50,000 USDT for her 20 ETH, ends up getting only 45,714 USDT due to the changes in the liquidity pool caused by the attacker's transaction, resulting in an approximate loss of 4,286 USDT .
-
Attacker's Follow-Up Transaction: Finally, the attacker initiates another transaction (the follow-up transaction), exchanging 14,286 USDT (recently acquired) for ETH.
-
After the attacker's follow-up transaction is executed, they withdraw approximately 7 ETH from the liquidity pool , changing the reserve status from 125 ETH / 240,000 USDT to 118 ETH / 254,286 USDT. Thus, the attacker initially spent 5 ETH and ended up with 7 ETH, making a profit of 2 ETH .
Throughout the entire sandwich attack process, the attacker initiates two transactions: the front-running and the follow-up transactions. The front-running transaction results in Alice's loss of approximately 4,286 USDT, and the combination of both transactions leads to a profit of 2 ETH for the attacker.
In DEXs, the public nature of transactions, especially in AMM protocols, is a key factor contributing to sandwich attacks. These protocols make real-time transaction information on DEXs public, and this high level of transparency provides attackers with the opportunity to observe and analyze transaction flows to find chances to execute sandwich attacks.
ZK Technology Can Counteract Sandwich Attacks
The application of Zero-Knowledge Proof can significantly reduce the likelihood of falling victim to sandwich attacks.The privacy of transaction data can be effectively enhanced by using ZK technology to hide transaction volumes, asset types, user or liquidity pool balances, user identities, transaction instructions, and other protocol-related information. This makes it difficult for attackers to obtain complete transaction information, thus making the execution of a sandwich attack more difficult.
In addition, ZK technology can not only defend against sandwich attacks, but ZK-based privacy transactions can also increase the difficulty of judging user behavior models. Any third party attempting to collect blockchain data to analyze historical account transactions, infer behavioral patterns, probe active cycles, transaction frequency or preferences, etc., will face challenges. Such analysis, known as behavioral model inference, not only violates user privacy, but can also pave the way for honeypot attacks and phishing scams.
Preventing Liquidity Manipulation Using ZKP Technology
Liquidity manipulation and front-running are both attack strategies in DeFi, leveraging market information and transaction speed for gains. However, their specific tactics and operations differ.
Front-running exploits informational advantages, while liquidity manipulation misleads other traders through market activities. The former primarily profits by accessing and using undisclosed significant information, whereas the latter misleads other investors by creating false market activity, leading them to make unfavorable trading decisions.
ZK technology can play a crucial role not only in resisting front-running but also in preventing liquidity manipulation.
Case Analysis: Liquidity Manipulation Using Oracles
Consider the scenario of buying apples in a busy fruit market. The market price typically fluctuates based on supply and demand changes. You usually observe the price for a while and decide whether to buy based on the average price. Now imagine a very wealthy buyer enters the market with a strong desire to purchase apples. They start buying apples in large quantities, regardless of the price, causing a rapid surge in the apple price. If you still base your purchase on this price, you might end up paying more than the actual value.
This example helps to understand the workings of the Time-Weighted Average Price (TWAP) oracle and the concept of liquidity manipulation. Your behavior of deciding to buy apples based on the average price resembles the operation of a TWAP oracle, and the wealthy buyer driving up the price by buying in bulk is akin to liquidity manipulation.
TWAP oracles determine the price of an asset by calculating the average trading price over a period. The more recent the trades, the greater their impact on the average price. If someone makes large trades or trades with significant funds in a short period, they could significantly influence the average price of the asset, which is liquidity manipulation. This manipulation artificially inflates or deflates asset prices, leading to inaccurate price information. If someone wants to manipulate the TWAP oracle to raise the asset price intentionally, they can temporarily inflate the price by purchasing the asset with large funds in a short period. If there's a significant increase in asset price during this window, the TWAP oracle might consider this inflated price as the asset's price.
Manipulating the TWAP oracle can have a significant impact on DeFi protocols, especially for emerging tokens with low liquidity. These DeFi protocols often make financial decisions based on asset prices, like liquidations, lending, etc. Inaccurate or unreliable price information can lead to erroneous decisions, potentially causing losses to users. Thus, protecting TWAP oracles from liquidity manipulation is of paramount importance.
ZK Technology Can Counteract Liquidity Manipulation
ZK technology can be utilized to counteract liquidity manipulation within TWAP (Time-Weighted Average Price) oracles. A smart contract can be designed to depend on a TWAP oracle for obtaining asset prices. If an attacker engages in liquidity manipulation, the price retrieved from the TWAP oracle might exceed a preset acceptable range. In such cases, the contract would temporarily suspend its operations. Subsequently, it would recalculate and confirm the asset price based on ZK technology.
To employ ZK technology for calculating asset prices, it is necessary to add a wrapper contract to the TWAP oracle. This contract can access N price reports directly or record the price at N checkpoints over any given interval. Once N data points are available within a specified interval, a ZK proof can be constructed to demonstrate the median of the unsorted array of prices. This unsorted array is denoted as a column vector x, with a length of N. The following describes the process of calculating asset prices using ZK technology:
-
The proof can be verified in either of the following two ways, and in both scenarios, the prover cannot arbitrarily select an array of prices as input:
-
Retrieve the array values from contract storage and use them as public inputs for an on-chain verifier;
-
Form a hash chain step by step through a hash function, representing the array as a single hash value, and use this value in the on-chain verifier.
-
-
There exists an square matrix , such that when this matrix is multiplied by the column vector , it produces another column vector , such that . A is an invertible permutation matrix, but due to the possibility of duplicate price values, is not necessarily unique and contains only binary values.
-
The values in are ordered, meaning . It is important to note that avoid strictly using because of the possibility of repeat price values.
-
The public output of the circuit is the median value of . The proof demonstrates that ,where is a static value at the time of circuit compilation and must be an odd number.
Following this process, a tamper-proof median price is outputted using ZK technology. This median value can help prevent liquidity manipulation to a certain extent. To achieve this, it is necessary to limit the values of , ensuring that in each block, the values of are either inserted once or a number of times within an acceptable range.
ZK technology empowers lending platforms
As mentioned above, ZK technology can resist front-running transactions and liquidity manipulation in DEXs. So, can we further explore the potential applications of ZK technology in other DeFi scenarios? For example, in an important component of DeFi projects - lending, ZK technology can also play a key role.
The key to lending: How to assess borrower credit
On traditional lending platforms, the loan application process usually covers five steps: application, credit assessment, loan approval, loan disbursement, and repayment. Among these, credit assessment is particularly important. Borrowers must prove their income meets the criteria and they have the ability to repay. During the assessment, platforms deeply investigate the borrower's credit history, including income, liabilities, and past repayment records, to ensure their 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, like Aave or Compound, the situation is different. Most DeFi lending platforms, due to their decentralized nature, lack traditional banking KYC (Know Your Customer) procedures and risk assessment steps, and cannot investigate borrowers' credit status through credit bureaus. In this case, you might wonder, how will my credit be assessed?
On DeFi lending platforms, you can prove your credit level through reputation tokens. Reputation tokens are a credit system based on blockchain technology, using digital tokens to represent and quantify users' reputation. The number of reputation tokens becomes an important indicator for assessing a user's reputation. The more tokens, the better the user's reputation and credit rating, potentially leading to more loan limits on DeFi lending platforms.
However, the generation of reputation tokens relies on users' transaction history and financial information, which may infringe on their privacy rights.
Assessing Borrower Credit: Reputation Tokens Based on ZK Technology
Zero-knowledge proof technology can protect user privacy. The combination of ZK technology with reputation tokens enables the maintenance and tracking of users' reputation in the network while safeguarding their privacy.
Users can generate reputation tokens without revealing their transaction history through zero-knowledge proofs. On one hand, users can create proofs of their historical transactions using ZK technology; on the other hand, a smart contract (often referred to as a reputation token generation contract) verifies these proofs, and upon successful verification, reputation tokens are generated.
Additionally, on certain DeFi lending platforms that require over-collateralization, reputation tokens can lower the collateral requirements, thereby addressing the issue of over-collateralization and enhancing market liquidity. The application of reputation tokens based on ZK technology is not limited to DeFi lending platforms; they can also be extensively applied in fields such as insurance and medical assistance.
Conclusion and Outlook
This article explored various application scenarios of ZK technology in DeFi for privacy protection, particularly in resisting front-running transactions, liquidity manipulation, and in lending. In exploring DeFi, we face several challenges, especially those related to privacy and security. The privacy challenges in the DeFi ecosystem are a key issue, and ZK technology offers unique solutions that not only enhance privacy protection but also improve transaction efficiency and security. If you are interested in introducing ZK technology into your DApp, feel free to contact ZEROBASE.
Looking ahead, ZK technology may find deeper applications in the DeFi field, such as in liquidity staking, derivative protocols, real-world assets, insurance, etc. ZEROBASE is dedicated to researching and exploring the application of ZK technology in DeFi and other Ethereum application layer projects. We invite blockchain researchers, technology developers, and professionals in the web3 domain from around the world to join us in our efforts to promote the in-depth development and widespread application of ZK technology, driving the growth of DeFi and the entire industry.