In-depth research 丨 Lightning attacks in efficient markets

FlashLoan (Lightning Loan) was born as early as the original MakerDAO, and launched late, and once the series of chain innovation brought by the force will lead the entire DeFi industry to a new level of development. In a short period of one or two years, the on-chain financial system has initially possessed a modern financial framework. It can not only form a closed loop, but also constantly test the external financial world. It is this new and dynamic vision that gives the blockchain world a permanent The endless power of exploration no longer stays in the predicament of self-doubt, just like the Internet of that year, everything is constantly changing under the protection of the development law.

(I) FlashLoan Principle

In simple terms, FlashLoan allows users to atomically complete operations such as borrowing, a series of fund utilization, and repayment in a transaction to achieve a zero-cost loan. From our current knowledge, the main purpose is to use For trading arbitrage (such as DEX and margin trading platforms), but with the continuous complexity and improvement of DeFi, other potential uses are not excluded. FlashLoan is a new open lending agreement. Any lending platform can choose to support FlashLoan, thus bringing more imagination and liquidity to itself. The protocol first needs to implement FlashLender. FlashLender helps users complete the following operations in a transaction:

  1. Borrow from any Lending platform
  2. executeArbitrage callback
  3. Profit
  4. Repay the entire amount borrowed, otherwise to Step 5
  5. the entire transaction revert, nothing happened

Roughly need the following functional contracts:

(A) FlashLender

Help Arbitrage contract complete the borrowing operation and call its callback

(B) Arbitrage

Respond to user requests, call the FlashLender contract for borrowing and lending operations, and call the TradeExecutor contract to perform a specially defined fund operation after obtaining funds

(C) TradeExecutor

Often need to cooperate with some wrapper contracts to make API calls to specific DeFi platforms and complete capital operations

(D) ExchangeWrapper (such as KyberWrapper, 0xWrapper, etc al)

This is a type of wrapper contract for DEX. It utilizes the development API operations of DEX and contains logic for exchanging ETH and other currencies on DEX. Generally it includes getExchangeCost, getMaxMakerAmount, transferTakerFee, parseOrder, parseSignature and similar methods. For example, to define a buy order on 0x:

0xWrapperContract.methods.getTokens(orderAddresses, orderValues); and it is used by the TradeExecutor contract trade () method.


So from the above, it is very simple to complete the development and support of a FlashLoan protocol. However, it is this simplicity that has caused the platform side to neglect the risk control that should have been matched. In the design guidelines of MOV, there has always been such a sentence: each additional service needs to be matched with double risk control measures, and each combined service needs to be matched with 10 times risk management.

(B) Lightning attack

Currently FlashLoan has caused two real financial arbitrage attacks (we don't think this is a hacking attack), both of which use the DEX trading market for final arbitrage, and they show agglomeration, and the cycle is very short. (This group) The attacker is obviously very familiar with the entire DeFi market data and operation mechanism, and has demonstrated the flexible use of FlashLoan. We have reason to believe that more thrilling attacks will occur in the next few months. Let's look at the first attack:

The first step ( storage of grain) : use FlashLoan to borrow 10,000 ETH from dydx

Second step (hoarding) : use the 5500 ETH to borrow 112 BTC from Compound

The third step ( declining fraud) : go to bZx ("unconfident") for margin trading, use 1300 ETH to open 5 times leverage, and exchange the borrowed ETH for about 51 BTC, because bZx uses Kyber Network, and Kyber Network eventually Uniswap was still used. This process drove up the price of BTC / ETH in UniSwap. At this time, arbitrage opportunities appeared.

Step 4 ( Total Attack ) : Sell 112 BTC in Uniswap in exchange for more ETH to generate profit

Step 5 (End of War) : Return the dydx loan

The logic is clear. The problem is that the margin trading of bZx has significantly increased the price of BTC / ETH, leading to arbitrage opportunities. The most fundamental problem is that bZx has no liquidation: when the exchange price of BTC / ETH in Uniswap is from 39 When manipulated to 108, the collateral on bZx should be inadequate and will be liquidated, but the bZx smart contract did not require an increase in margin or liquidation. So in essence, the (everyone's) ETH in the bZx fund pool was transferred to BTC lent from Compound through Uniswap, and the bZx depositors bear the final loss. At the same time, Uniswap walked back and forth twice, that is, the first pass used 5637 ETH borrowed by bZx leverage to exchange 51 BTC, the second pass was reversed, and the 112 BTC borrowed by Compound was exchanged for 6871 ETH, so it will eventually lead to BTC on Uniswap The average price of / ETH is (6871-5637) / (112-51) = 20, which is lower than the normal price of 39. Therefore, in the second round of trading, a part of BTC is a loss shipment, and about 60 BTC is almost a half-fold. Sold, and the losing money was made by Uniswap's market maker. So this attack was completed by the attacker making full use of Uniswap slippage protection defects and bZx margin leverage trading contract defects.

Note: About bZx contract defects. In its contract code, there is a require call to check whether the position is healthy (healthy position), but due to low-level code errors (or lack of awareness of risk control), only in loadDataBytes.length == 0 && sentAmounts [6] == sentAmounts In the case of [1], you can bypass the sanity check and finally skip clearing bZxOracle :: shoudLiquidate.

Although the project party urgently repaired its contract defects after the first attack, the second attack immediately took advantage of the risk defect that bZx relies heavily on the on-chain oracle to obtain pricing:

The first step (into the enemy): loan 7500 ETH from bZx itself through FlashLoan

The second step (sacrifice the ego): purchased 92419.7 sUSD on Kyber with 540 ETH, which caused the price of WETH / sUSD to be instantly lowered. To do more sUSD, Kyber used Uniswap, which affected the exchange rate on Uniswap. Attackers Very smart, instead, using 18 small amounts (20 ETH) to continue to smash the disk to pull up sUSD, eventually resulting in Uniswap sUSD / WETH is 1: 157, greatly deviating from the normal price

The third step (surrounded by reinforcements): borrow all sUSD from Synthetix, and then smash it to bZx. Because bZx relies heavily on Uniswap to quote sUSD, the attacker's sUSD value is much higher than normal value on bZx, and a large amount of ETH is exchanged. Complete arbitrage

Step 4 (Return the Renegade): Return 7500 ETH to bZx

This is a very classic oracle attack, the whole process is neat and clean. We believe that the attacker knows the market behavior and arbitrage of sUSD well, so he chose sUSD and Synthetix as reinforcements, and the reinforcements were very powerful. Not only did they give all their family members, but they also succeeded in making bZx believe Uniswap The price quote did not give sUSD too much risk control limit on its platform.

The impact and significance of the second attack must surpass the first. This has caused all current DeFi products to make changes and risk control management on the price prediction mechanism of the predictor to obtain real fair market value (FMV, fair market value). There are roughly five types of oracles:

(1) Off-chain centralized oracle: Obtain FMV from a single off-chain financial system

(2) Centralized oracle of chain down: FMV is obtained from multiple off-chain financial systems, and is separately controlled by multiple parties, and multiple prices are integrated through mathematical formulas

(3) On-chain centralized oracle: often a single DEX

(4) On-chain decentralized oracle: Eco-government participates in feeding and co-governance

(5) Constant predictor: generally used for stable currency feeding, for example, the US dollar stable currency only accepts the real world dollar price

Here are a few major oracle choices before DeFi:

WeChat picture_20200313093816

After the baptism of lightning, all DeFi need to rethink the construction of oracles. On the other hand, because small or inferior DeFi has no ability and funds to maintain the operation of a comprehensive commercial mature oracle (self-built or cooperative), it will continue to die under the threat of lightning attacks and complete the survival of the fittest in the DeFi ecosystem. However, from the perspective of risk management, the emphasis on the construction of robust oracles can only be a mitigation measure, and cannot fundamentally overcome the threat of lightning. For example, the following measures are taken for oracles:

  1. Don't take the median market price as a feed price, a large transaction can easily change the median market price.
  2. Making full use of blocks, FlashLoan can only affect the world (state) of a single block. You can consider using the state information of multiple blocks before and after to feed prices, such as time-weighted average price (TWAP) or volume-weighted average price (VWAP). ) Calculate the weighted average of the previous N blocks.
  3. Make efforts to build and rely on external oracles.
  4. Each time the smart contract system obtains a feed price, it adds a code for risk checking (range of exchange rate changes, multiple source comparison verification).
  5. Even if there is no lightning attack, the attacker can still influence the price of Uniswap in a short time (one block) with less cost (for example, when the liquidity pool size is 1000 ETH, the cost can be 0.025 ETH in one block). Resulting in a 1% price manipulation). Therefore, for other relying parties, you cannot rely on Uniswap's price fluctuations in a short period of time, nor can you rely on the feed price output in a short period of time.

(3) Continue to attack

It doesn't end there.

DDEX has an ETH / DAI margin trading market (providing leveraged long and short positions), and its feeding system first checks Eth2Dai, and if the spread is too large, it reads from Uniswap.

 function peek() public view returns (uint256 _price) { uint256 eth2daiPrice = getEth2DaiPrice(); if (eth2daiPrice > 0) { _price = makerDaoPrice.mul(ONE).div(eth2daiPrice); return _price; } uint256 uniswapPrice = getUniswapPrice(); if (uniswapPrice > 0) { _price = makerDaoPrice.mul(ONE).div(uniswapPrice); return _price; } return _price; } 

Step 1: Loan a ETH from dYdX Lightning

Step 2: Use part of ETH to eat all the DAI / ETH sell orders of Eth2Dai, widen the spread, let DDEX reject Eth2Dai, and choose Uniswap

Step 3: Use ETH to do more DAI on Uniswap, greatly reducing the DAI / ETH exchange rate

Step 4: Mortgage DAI leverage on DDEX in exchange for ETH that is much higher than the value of the mortgage

Step 5: Repay to dYdX, the rest is profit

In this attack, the characteristics of the DAI trading market were fully used: DAI is gradually popularizing into mainstream currency trading pairs and margin trading, so it has also gained the status of capturing large amounts of wealth. Similarly, on a variety of other trading platforms, for the purpose of quick success and quick profit, open the leveraged market without thinking about random listing, it is bound to give FlashLoan the opportunity to attack small currency trading pairs and win mainstream assets. In the world of decentralized finance, attacks can cover all financial systems in an instant, triggering a terrible chain disaster. Even the best DeFi project of its own risk control will be affected as a result. "Good Coin" staged again.

In particular, in addition to Ethereum, more and more public chain ecosystems are moving towards the DeFi strategy. Even if the official DeFi service launches the best risk control, we cannot require all developers in the ecosystem to be aware of the risks, such as For cost considerations, many start-up DeFi projects will rely on the official DEX feed price, and the existence of lightning attacks can easily eat all the DEX pending orders, which will affect the feed price output. Even if the profit on a certain DeFi is not enough to cover the cost of the attack, all the involved DeFi profits are enough to capture the profit, or it is called a lightning attack to capture long-tail profits, and this is in other public chain DeFi except Ethereum It will be more common and effective on the system.

We also said earlier that at present we have only seen the impact of lightning attacks on the trading market, but there must be disasters in other areas. As long as there is a coin, there is a lightning attack in theory. As governance begins to move towards the DeFi system and upgrades to the so-called DAO, this also gives FlashLoan the opportunity to seize political rights (borrow a large number of governance tokens to participate in voting to manipulate the entire system), so I have often seen a lot of governance mechanisms recently. DeFi ’s head is re-modifying governance contracts and risk control mechanisms.

In December of last year, Micah Zoltu, the author of the Augur white paper, pointed out that MakerDAO has a governance loophole: an attacker can use 40,000 MKR (about 20 million US dollars) to steal all Maker DAO's mortgage assets in just 15 seconds. Includes a wealth of assets (over $ 340 million) from DAI, SAI, and systems from integrated Makers such as Compound and Uniswap. At that time, everyone just listened. Although there are loopholes, almost no attacker can have tens of millions of dollars of MKR, even if there is, it can be traced. But now the lightning attack has changed the rules of the game, especially as MKR continues to flood into the liquid market (no longer locked by the foundation), the possibility of collecting attack costs from the liquid market is increasing. Attackers can buy MKRs with different quotas in batches from multiple DEX markets (such as Kyber, Switcheo, Uniswap) that support MKR. In addition, they can also use the oracle attack to maliciously reduce the feed of other platforms that support MKR transaction lending, and then Obtaining more MKR at low cost, or combining these two methods together, in the end, if the governance contract can be successfully occupied, the profit obtained will far exceed these tens of millions of dollars of assets, which is also very scary. We have also seen that MakerDAO has adopted corresponding risk control measures, such as increasing the voting delay, as long as the delay is more than two blocks, lightning strikes can be wiped out.


Whether it will increase the probability of run risk in the lending market. That is, continuous large-scale loans lead to the depletion of liquidity, and the impact of lenders' failure can be controlled, but when depositors who need to withdraw find that they cannot withdraw, panic market sentiment may bring serious risks of run, and the damage to the entire system Fundamentally, we can know from the chart provided by the Ethereum data analysis platform Alethio that this liquidity depletion crisis is still common even on Compound. Therefore, on the one hand, the attacker is completing the arbitrage of the lightning attack, on the other hand, it also exacerbates the risk of run-out caused by the depletion of liquidity of the lending platform.

In addition, FlashLoan is like a dark pool, which allows attackers to play freely and cannot be tracked. After the attack is completed, no stain can be left. Prior to this, the addresses of large-scale attackers could continue to track and analyze them and even request centralized exchanges to lock out prohibition of cashing. The traditional large-scale attack is inherently risky and can only be profitable if it is all calculated correctly. Once an accident occurs midway, it is likely to catch up with your own assets, and FlashLoan will either succeed or nothing will happen, and everyone will never You'll know which address is moving.

Finally, we also need to continue to pay attention to the impact of FlashLoan on the aggressive market manipulation of DeFi assets, which will affect the mainstream market, such as the price of ETH on a centralized exchange, and avoid a "blitz" sweeping across Europe. Bringing World War.

(IV) Existence of Effective Market and FlashLoan Arbitrage

In 1970, American financier Fama proposed the "efficient market hypothesis": Under the assumption of an efficient market, stock prices can fully reflect all information, so unreasonable prices will be eliminated quickly. In an efficient market, all information will be quickly understood by market participants and immediately reflected in the market price, so that the transactions performed by this group of information do not have abnormal returns, and can only earn risk-adjusted average market returns rate. In the real financial world, as long as the market price of a securities can fully and timely reflect all valuable information, the market price represents the true value of the securities, and such a market is called an "effective market." In the emerging world of decentralized finance, efficient markets are everywhere, such as the existence of arbitrage and front running (Front Running), and this is exactly the nature of FlashLoan's existence, which will be accompanied by an efficient market. Everywhere. Arbitrage opportunities exist in various forms in the financial market, and arbitrage is gradually becoming an important vitality and risk control measure for the DeFi financial system. Many exchanges have arbitrage opportunities. Arbitrage helps reduce assets in different markets. The price difference also helps improve liquidity. For example, Uniswap implements a market-making algorithm that implements a constant product through the existence of arbitrage behaviors. Traders can use the exchange rates of other cryptocurrency exchanges to correct price deviations that may occur on Uniswap, but they also have to face arbitrage. The negative impact of everything is a rational existence game of both sides.

Let's first look at several common FlashLoan and peaceful arbitrage methods.

Exchange arbitrage. For example, the founder of DForce mentioned that using the mechanism of becoming a Uniswap liquidity provider can greatly reduce the fee to complete the arbitrage.

Step 1: Loan a large amount of ETH from dYdX via FlashLoan

Step 2: Mortgage ETH to MakerDAO and Lend DAI

Step 3: Lending DAI to Uniswap to Provide DAI Liquidity

Step 4: Perform all DAI related transactions in Uniswap

Step 5: Repay the loan The original normal transaction fee was 0.3%, but now it only needs 0.05%, because becoming a DAI liquidity provider can get 82% commission rebate.

Automated zero-cost refinancing. Take out the ETH that was originally mortgaged in MakerDAO, and then mortgage it on Compound to get a higher market interest rate. Originally, users needed some funds to redeem assets from MakerDAO. Although there is the temptation of interest rates, it increases the user's operation and cost, and reduces enthusiasm. We can use FlashLoan to create a new and effective market tool product.

Step 1: Loan the full DAI through FlashLoan and close the CDP

Step 2: Take out a portion of the ETH in exchange for DAI on Uniswap for the final equal payment, and deposit the remaining ETH in Compound

Step 3: Repayment At this point we have completed automated zero cost refinancing.

Liquidation arbitrage. In a stable financial system, it is often faced with being liquidated, and once incapable of additional mortgages, liquidation will result in up to a dozen percent of liquidation costs. As above, the assets to be returned are lent out through FlashLoan, the mortgage contract is closed to get back the mortgaged assets, and then the token exchange is completed, and the loan can be returned to FlashLoan to avoid liquidation in a timely manner. This also suggests that this real-time tool can cooperate with the stable system's own clearing mechanism to become an excellent risk control auxiliary measure, especially when there are not many official clearing systems and market arbitrage clearers, with the help of FlashLoan's automation The tool quickly resolves the liquidation risk brought by the market decline, which is win-win for users and the system itself.

Be the first to trade. Like FlashLoan, preemptive transactions are an attack that needs to be guarded against, and a reasonable arbitrage behavior. To put it simply, preemptive trading refers to the completion of your own transaction after learning the counterparty's trading intention. For example, Tom plans to buy a large amount of ETH, and Jerry knows Tom's intention and can preempt Tom to buy ETH at the current price before Tom. And then sell it at a higher price to earn the difference. This is illegal in the real financial world, because non-public information is used, but in the decentralized financial world, all information is publicly and legally, so we classify preemptive transactions as an efficient market and respect this behavior. Existing, of course, certain measures will be taken to allow sufficient market competition to gradually eliminate short-term market imbalances caused by preemptive transactions. Here we also want to emphasize a concept that is closely related to the on-chain financial risk control system-atomic time on the chain and a predictable future. In the real world, there is no atomic time and there is no predictable future, but in the blockchain world, blocks are atomic time, and the future can also be orchestration. The transaction is broadcast to the network and enters the mempool. Anyone can listen to it, so for traders, robots, and miners, it is possible to accurately predict the world state update generated by the transaction combination to a certain extent, and it can be completed through preemptive transactions Gaming and risk-free profit. FlashLoan also makes use of the concept of atomic block time. It fully evaluates the adverse information (transactions) contained in the upcoming block, and when it is determined that there is no obstacle (or competition), it constructs an accurate description of future transactions. Complete risk-free arbitrage. With the formation of preemptive transactions and the formation of a new effective market brought by FlashLoan, naturally, competitors will also start to fight the future of the attacker in atomic time, which may cause the attacker to fail or coexist with the attacker. Take a bite of "meat soup" during the attacker's attack process. For example, a robot used to combat lightning attacks can detect a transaction with a clear lightning attack on the transaction that is about to be included in the block, and then go to the DEX to pull the disk. Hanging high point ambush, waiting to be hit by lightning far above the market price.

Lightning makes the market. DeFi ecology relies on market makers, and market makers rely on original capital. In the just-developed public chain DeFi ecosystem, is there a possibility of integrating FlashLoan into the market maker mechanism, thereby driving a zero-cost lightning-fast market-making market. Here's a rough idea:

(1) User A initiated a transaction of 40 ETH for 1 BTC on the official DEX of a public chain, but no market maker responded in time.

(2) The lightning robot captured the transaction and immediately lent 1 BTC from the public chain lending market through FlashLoan, and matched with the order of user A in exchange for 40 ETH (in order to simplify the calculation, there is no profit part here)

(3) The robot constantly searches for ETH / BTC orders in other current trading markets. If there is a counterparty that can exchange 40 ETH for at least 1 BTC, it performs the exchange and repayment operation to complete the lightning market. If no matching order is found, Then the market fails and there is no loss

In addition, it may also exist as a tool for the DEX or lending platform.

(5) Combinability of MOV and Overlay Risk Control

MOV is a comprehensive portfolio financial system that integrates DEX, lending, stable financial systems, and financial derivatives markets. We call it the SOLD financial system (StableCoin, Oracle, Lending, DEX). Combinability allows us to respect the existence of arbitrage, and also supports ten times the risk management mechanism. Generally speaking, risk management is divided into four aspects: arbitrage loopholes, audit loopholes, risk prediction, and risk control. If there are n different applications in a DeFi ecosystem, the corresponding risk complexity is the nth power of 2 (C (n, 0) + C (n, 1) + C (n, 2) + …. .. + C (n, n) = 2 ^ n). Especially for the emergence of innovative DeFi such as FlashLoan, we hope that we can use the positive side as a sharp weapon for overtaking on the corner, and on the other hand, we will firmly lock the negative side in the cage through our own strong wind control system. Here, I will briefly mention a few MOV principles and measures in controlling overlapping risks through the FlashLoan event.

In the real financial world, the occurrence of financial crises is mostly related to unbridled leverage, such as the 2008 subprime crisis. A good on-chain financial system should also be in awe of the design of leverage. DeFi does not mean “madness” Increase leverage. " Imagine how terrible a nuclear weapon would be, especially with FlashLoan, unlimited borrowing + unlimited leverage. In the ecological construction of MOV, we will firmly implement the mission of stabilizing finance. We will give sufficient risk warnings and risk assessments to ourselves and ecological participants in the design of leveraged products. High-risk DeFi projects will limit their impact on important DeFi. The seamless connection of the system or other DeFi systems avoids a series of combined risks brought by its own risks. This is also one of the differences between MOV and Ethereum's DeFi system. MOV will have a strong and responsible central risk control guidance system.

In addition, in the construction of the oracle machine, from the beginning of the ecological blueprint architecture, we have attached great importance to the risk control of the ecological oracle machine system, not only choosing a self-developed system, including external world input ( and on-chain oracle machine. At the same time, it also attaches great importance to co-construction with top oracle providers (such as ChainLink) to avoid single-point containment. At the same time, it will open this oracle machine system in the MOV ecology for other small project parties to connect at no cost and avoid suffering Losses from oracle attacks.

The problem of controlling the superimposed risk is to a certain extent the choice of assets. In the recently released "MOV Stable Financial System" white paper, we give out the principles for selecting portfolios and the risk assessment mechanism for relevance. Inspiration, assets should be more carefully entered into different DeFi systems, such as MOV stablecoin assets or equity assets that are vital to the ecology, which is not suitable for entering the large liquidity market and leveraged trading market prematurely. An important rule of MOV ecological governance (including risk equity) is to use governance with caution, which also minimizes the possible systemic damage of new types of attack products represented by FlashLoan in the future.

Secondly, there are auxiliary means such as the on-chain reputation system, especially when anti-lightning attacks on specific applications, participating addresses can be required to have certain assets Merkle certificate or reputation credentials.

During the ecological design process, we assessed the risk (slippage) of Uniswap, so MOV DEX will give priority to order book matching and market making DEX. Please look forward to the upcoming MOV!

We will continue to update Blocking; if you have any questions or suggestions, please contact us!


Was this article helpful?

93 out of 132 found this helpful

Discover more


Cardano Price Prediction: Will ADA Recover Soon?

The value of Cardano has increased by 4% in the last 24 hours, reaching $0.4728 as the cryptocurrency market slowly b...


🤩 The US Cryptocurrency Conundrum: Regulating in Chaos 😱

Charles Hoskinson, creator of Cardano, expressed to Cointelegraph that regulators in the US, like the SEC, have effec...


Cardano's DeFi Ecosystem Flourishes Total Value Surges to Almost $450M as ADA Rockets 17% on Layer 1 Push!

This week, the total value locked (TVL) of Cardano-based tokens skyrocketed to more than $440 million, surpassing the...


Bitcoin Price Takes a Tumble, Plunges Below $41,000 Is It Just a Bump in the Road or the Start of a Rollercoaster Ride?

Bitcoin Dips Below $41,000, Market Correction Hits Ethereum, XRP, and Cardano with 5% Decline


Cardano (ADA) Price Threatens Bearish Breakout Amid Stagnating TVL

With a recent rebound back towards $0.50, the Cardano (ADA) price has shown resilience following a brief dip below $0...


Cardano Price Prediction: ADA Set for Spectacular Gains Post-Bitcoin Halving – Future Millionaire Maker?

Cardano gains 4% in 24 hours, reaching $0.383747 amidst a 2.5% marketwide increase.