Depth | A Comprehensive Interpretation of Lightning Loans: Why Will Lightning Attacks Become the New Normal?

Source: Chain News

Author: Haseeb Qureshi, Managing Partner of Dragonfly Capital, a cryptocurrency venture capital firm

Lightning loans have recently become a hot topic. Two hackers used lightning loans to attack the margin trading agreement bZx . The first arbitrage amount was US $ 350,000 , and then they carried out a pirated attack of US $ 600,000 .

If one word is used to describe these attacks, it can be said to be " spectacular ." In each attack, penniless hackers loaned hundreds of thousands of dollars worth of ETH, dispersed a series of vulnerabilities in on-chain protocols to conduct a pass, took hundreds of thousands of dollars from the stolen assets, and successfully blocked them. Huge ETH loan hole. All of this is done in an instant, that is, in an Ethereum block.

Comic cover by Carmine Infantino

We do not know who these attackers are or where they are. Both were white wolves with empty gloves . The attack made hundreds of thousands of dollars without leaving any trace of their identity.

When the news of these attacks broke out, I was thinking about the security issues of Lightning Loan and DeFi. I think this issue deserves public discussion.

Briefly put forward my point: I think there is a major security threat to Lightning Loan. But Lightning Loan will not disappear, and we need to seriously consider its security impact on DeFi in the future.

What is Lightning Loan?

The Lightning Loan concept was first proposed by the Marble Agreement in 2018 . Marble prides itself on being a " smart contract bank, " whose product is a simple but intelligent DeFi innovation: a zero-risk loan through smart contracts .

How can loans be risk-free?

Traditional credit institutions face two risks when lending. The first is the risk of default : if the lender absconds with the money, the credit institution will swallow the bitter fruit. But the second is liquidity risk : if a credit institution releases too many loans at the wrong time, or the borrower fails to repay in time, the credit institution may unexpectedly encounter liquidity tension and fail to fulfill its obligations.

Lightning loans mitigate these two traditional lending risks. The basic working principle of Lightning Loan is: loan the amount required by the borrower in a single transaction. However, at the end of the transaction, the borrower must repay at least the amount of the loan . If the borrower fails to do so, the lender will automatically roll back the transaction. (Yes, smart contracts can do this! )

Simply put, Lightning Loans are automatic: if the borrower fails to repay the loan, the entire transaction will roll back, as if the loan did not happen at all.

Such things can only happen in the blockchain. For example, you cannot make a lightning loan on the BitMEX exchange. Because the smart contract platform processes transactions at once, all elements of a transaction are executed in batches. When the transaction is executed, this can be thought of as the " freezing time " of the transaction. In a centralized exchange, fierce competition may occur, which may cause your transaction to partially fail. In a blockchain, all your code can be guaranteed to be executed line by line.

So consider briefly the economic mechanism. Traditional credit institutions earn returns for two elements: the risk they take (default and tight liquidity) , and the opportunity cost of the funds they lend (for example, if the money would have given the lenders 2% Interest, so the borrower must pay a higher interest rate than the risk-free rate of return of 2%) .

Lightning loans are different. There is no risk or opportunity cost in Lightning Lending Rate! Because the borrower " freezes time " during the lightning loan process, in the eyes of anyone else, the system's funds are never risky and never blocked, so you can't earn interest (for example, it has no opportunity cost) .

This means that it does not feel like any cost to be a Lightning Lender. This is seriously counterintuitive. So what should be the cost of a lightning loan in equilibrium?

Basically, there should be no cost for Lightning Loans. Or more accurately, a small fee can compensate for the three lines of code added to put an asset into a loanable state.

From 0x Researcher Remco Bloemen

Lightning loans cannot charge interest in the traditional sense because the duration of the loan is 0 (APR * 0 = 0) . Of course, if any lenders charge higher interest rates, they will be crushed by other competitors with lower interest rates.

Lightning loans make money a real commodity. In the end, this kind of competition will inevitably reduce the cost to zero or a small amount. dYdX's current lightning loan handling fee is 0. AAVE charges 0.09% of the principal as interest. I don't expect this situation to continue, in fact the AAVE community has started calling for 0 interest. (Please note that neither of the two hacks we mentioned earlier chose to obtain a lightning loan from AAVE)

What is the use of Lightning Loan?

The initial marketing label of Lightning Loan was mainly used for arbitrage transactions . Marble's debut statement states:

"Lightning Loans can help traders to borrow from Marble Bank, buy coins in a decentralized exchange DEX, and then sell tokens at a higher price in another DEX. An automated transaction allows you to generate arbitrage income. In the bag. "

And the reality is indeed-in terms of amount, most of the lightning loans we have seen so far are used for such arbitrage transactions.

AAVE's Lightning Loan Use, Source: AAVE

But the amount is still small. The amount of lightning loans initiated by AAVE since its inception has just exceeded $ 10,000 . Compared with the size of arbitrage transactions and the liquidity of the DeFi market, it is only a fraction of a dollar.

This is mainly because most arbitrage transactions are done by competitive arbitrageurs running complex robots. They conduct on-chain priority gas auctions, and then use GasToken to optimize transaction fees. This market is very competitive, and they are happy to keep some tokens on their books to optimize profits.

On the other hand, the cost of borrowing from AAVE is about 80,000 gas, and 0.09% of the principal is charged. This cost is too high for arbitrage competition with thin profits. In fact, in most AAVE arbitrage transactions, the borrower pays more to the loan pool than the arbitrage income.

In the long run, arbitrageurs are unlikely to use lightning loans unless there are some special circumstances.

It turns out that Lightning Loan has other, more compelling use cases in DeFi. One example is refinancing loans. For example, suppose I have a Maker Mortgage Debt Position (CDP) with 100 USD of ETH locked in it, and I borrowed a loan of 40 DAI coins from it, so my net position in the CDP after subtracting the debt is 60 US dollars. Suppose I want to refinance in Compound for higher interest rates. Usually I need to repurchase 40 DAI to close CDP, which requires some upfront funding. Instead, I can use Lightning Loan to borrow 40 DAI to close the CDP, deposit $ 60 of unlocked ETH into Compound, and use Uniswap to convert the remaining 40 USD of ETH back to DAI and use it to repay the Lightning Loan. In one go, refinancing at zero cost.

This is amazing! This is a great example of how Lego Capital operates. actually builds a margin trading aggregation application that uses Lightning Loan to automatically implement such transactions.

Although these are cool, the bZx attacker made it clear to us how much damage Lightning Loan can do.

The significance of lightning attacks for security

I am increasingly convinced that what is really unlocked by Lightning Loans is Lightning Attacks -using Lightning Loans for high-value fund attacks. The recent bZx hack has given us a glimpse of the panther. I suspect this is just the beginning.

Why does Lightning Loan become a weapon for attackers? There are two main reasons.

  1. Many hacking attacks require a large amount of upfront funding (such as manipulating the price of Oracle coins) . If you get a positive return of 10 million USD of ETH, it should not be an arbitrage transaction.
  2. Short-term loans can minimize the taint of attackers. If I have an idea of ​​how to manipulate Oracle Coins with 10 million USD of ETH, even if I have that much ETH, I may not want to risk it with my own funds. My ETH may be stained, the exchange may refuse my deposit, and the difficulty of money laundering is greatly increased. risky! But if I loan $ 10 million with Lightning, who cares? All parties will benefit. My loan source, dYdX 's mortgage pool will not be polluted, and dYdX's pollution has disappeared to some extent.

You may not like it, but the exchange review system is now part of the blockchain security model-quite vague and centralized. But I think for an attacker, Lightning Loans essentially changes that risk. In the Bitcoin white paper, Satoshi Nakamoto made the famous statement: Bitcoin will not be subject to security attacks because:

"(The attacker) should find it more profitable to participate in accordance with the rules than to destroy the system, and destroying the system is destroying his own assets."

In Lightning Loan, attackers and Lightning Loan games have no interest at all . Lightning loan essentially changes the risk of attackers.

Also keep in mind that Lightning Loans can accumulate ! Given the limitations of gas, you can borrow from all pools of funds that can be lent (up to $ 50 million) in one transaction, and then bundle all funds into an attackable contract. Now the attacker has a 50 million dollar sledgehammer. As long as he smashes heavy gold , any weak on-chain agreement cannot bear its huge impact. this is too scary.

Of course, an attacker can't attack these protocols with just a lot of money. If all DeFi stacks are as secure as it claims, this should not be a problem-which protocol is insecure in the face of rich whales? You might say that these agreements didn't take that situation into account and were simply negligent.

However, it is said that Ethereum itself can be subject to 51% attacks with less than 200,000 US dollars per hour **. This amount is not great! If Ethereum's own security model can only prevent fund-poor attackers, why should we be so harsh on those DeFi applications that can't prevent a $ 10 million attack?

(** To be clear, I personally do not believe this number. This number ignores the impact of ETH shortage and other conditions, but it shows an idea.)

How to slow down lightning attacks?

Suppose you are a derivatives platform and want to avoid lightning attacks. I will naturally ask: Can I detect whether the users who trade with me are using Lightning Loans?

The simple answer is: you can't do it.

The EVM design of Ethereum does not allow you to read storage from any other contract. So if you want to know what happened in another contract, you can only tell you through that contract. If you want to know if a customer is using a Lightning loan contract, you must ask the Lightning loan contract. Many current lending agreements are unable to respond to such queries (and in general, there is no way to force Lightning Lenders to execute this query) .

Even if your derivative platform attempts to check a known Lightning Loan agreement, the agreement platform can easily mislead any such inquiry using an agency contract or linking across a Lightning Loan agreement. It is often impossible to tell at all whether a user is using Lightning Loan.

In just one second, if someone is knocking on the door of your trading platform with $ 10 million, it is impossible to tell whether this is their own funds or a lightning loan.

So we have to guard against lightning attacks. What is the real choice? I think of three methods.

  • Convince Lightning Loan Agreement to stop providing such services

Just kidding. Guys, this is the crypto world!

Seriously, trying to stop the loan pool from providing lightning loans is like trying to stop noise pollution, which is a classic tragedy in the public domain . Providing Lightning Loans is in the interest of each agreement, and its users have reasonable reasons to want to use this feature. Therefore, we can safely eliminate this option. Lightning loan will not disappear.

  • Force critical transactions across two blocks

Keep in mind that Lightning Loans allow you to borrow capital in a single transaction time. If a capital-intensive transaction needs to span at least two blocks and the user needs to withdraw the loan at least two block times, lightning attacks become impossible. (Note: To achieve this effect, the user value between the two blocks must be locked to prevent it from repaying the loan. If you don't design it correctly, users may perform lightning attacks on both blocks)

Obviously, this is done at the expense of the user experience: this means that transactions will no longer be synchronized, much like the commit / reveal scheme. The user experience is terrible and requires careful thinking.

Many developers complain that smart contracts operate asynchronously, such as interacting with Layer 2 or Ethereum 2.0 cross-chip communication protocols. Ironically, asynchrony makes these systems more secure and avoids lightning attacks. Because the attacker cannot synchronize the operation of the main chain with Layer 2 or sharding in one automated transaction. This means that ETH 2.0 shards or Layer 2 DEXs are not subject to lightning attacks.

  • Requires on-chain proof that the user's account balance has not changed after completing the lightning loan

If we can detect the actual balance of the user by some method (that is, the balance before their loan and after their repayment) , we can defeat the lightning attack.

This cannot be done in the native EVM mechanism, but it can be modified. What you have to do is: before the user interacts with your agreement, you ask them to provide Merkle proof that they have enough balance at the end of the previous block to repay the currently used funds. You need to track this for each user in each block. (Thanks to Cornell University professor Ari Juels for giving me an overview of this approach)

This method works to some extent. Of course, it is still rough and has some problems: the cost of verifying the evidence on the chain is very high on the chain, and no one with a normal thinking is willing to provide such a proof and pay the gas fee for the entire process. In addition, users may have legitimate and reasonable reasons and want to adjust their balance in the previous block. So, although this method has some theoretical benefits, it is not a viable solution.

It is clear that none of the three solutions I mentioned above are ideal. I believe that there is no really good solution to lightning attacks. But there are two special applications that can slow down lightning attacks: market price oracles and governance tokens .

Market price oracles like Uniswap or OasisDEX , due to the possibility of lightning attacks, you cannot under any circumstances take the current median market price as the feed price. Attackers need only one transaction to easily change the median market price and make the oracle fail. The best solution to this is to calculate the weighted average of the previous batch of X blocks from time-weighted average price (TWAP) or volume-weighted average price (VWAP) . Uniswap v2 comes with this functionality; the book Polaris by economist Max Wolff provides a common approach to other protocols.

On-chain governance is a series of headaches. On-chain governance is usually determined by voting holders of governance tokens by weight. But if this governance token enters a certain loan pool, any attacker can steal a large number of votes and get the result they want.

Of course, most governance agreements require these governance tokens to be locked during the voting period, which makes lightning attacks impossible. But this is not the case for some governance agreements, such as "Carbon Vote" and Maker 's executive vote. Under the shadow of a lightning attack, these governance mechanisms are likely to be captured.

Ideally, you don't want governance tokens to enter the Lightning Loan Pool. But this is not determined by the issuer, it is determined by the market. Therefore, all governance actions should require a token lock-up period to prevent lightning strikes. More critically, all governance tokens must have timelocks . Time locks force all execution decisions to have a waiting period before they take effect. (E.g. Compound's time lock is 2 days) . In the event of an unexpected governance attack, this mechanism gives the system fault tolerance . Even though MKR has not entered a large number of Lightning Loan Fund pools recently, some people have recently said that MakerDAO is vulnerable to such attacks. MakerDAO is currently speeding up repairs.

What's the significance of this?

I think the bZx attack has completely changed the situation.

This will not be the last lightning strike. The second bZx attack is just the first copy, and I suspect there will be another wave of similar attacks in the coming months. Thousands of smart teenagers now look at all of these DeFi Legoes everywhere, looking for any loopholes with a microscope, trying to find a way to launch a lightning attack. If they breach a loophole, they will also make hundreds of thousands of dollars, which is enough to change lives for most countries and regions around the world.

For each DeFi protocol, a lightning attack means that the security model has changed . A similar attack after the bZx hack will be the same as a reentry attack after the DAO hack, and will become a joke in the crypto world. But you can expect this to happen.

Finally, these events led me to think about the ancient concept of the crypto world: miners extractable value (MEV) . MEV refers to the total value that a miner can extract from a blockchain system, including block rewards and fees, but also other less-than-bright gains, such as reordering transactions or inserting rogue transactions into blocks .

Fundamentally, all of these lightning attacks should be considered as a single transaction in a massive fund memory pool (mempool) . For example, the second bZx attack generated ETH profits worth $ 645,000 in a single transaction. If you are a miner and you plan to start mining new blocks, imagine looking at the transactions in the previous block and saying to yourself, "What's going on? The last block contained a profit of $ 645,000, why should I mine? A new block for only $ 500? "

It is more in your interest not to continue mining new blocks, but to try to rewrite history and make yourself the lightning attacker. Think about it: This transaction is equivalent to four hours of honest mining on Ethereum! This is the same principle as having a super block containing 1000 times the reward of a normal block-a reasonable result of this kind of super block is that a large number of miners furiously compete to steal that super block for themselves.

Simulation shows fierce contention among miners

In an equilibrium state, all lightning attacks should eventually be extracted by miners . (Note that they should also eventually steal all on-chain arbitrage and liquidation) . Ironically, this will be an important element in stopping lightning attacks, as it will prevent attacking hackers from discounting the theft. Maybe eventually the miners will start offering rewards for attacking the code in private, providing hackers with informer fees . Technically speaking, zero-knowledge authentication can be done without trust. (Is it strange to think so? )

This is still science fiction today. The miners apparently did not do this.

Why didn't they do that? There are countless reasons. First of all, it is difficult , requires a lot of work, EVM is difficult to simulate, and the risk is high. The existence of loopholes may cause loss of funds or solitary blocks, which will lead to verbal criticism. The entire mining pool will encounter a public relations crisis and may be listed as " Ethereum public enemy ". Under the current circumstances, if miners do this, they are more likely to bring more economic losses and loneliness than to get the money.

This is true at the moment, but this will not last long.

This has given Ethereum a new impetus to transition to Ethereum 2.0 as soon as possible. DeFi on Ethereum, while stunning and fascinating, is undoubtedly flawed. DeFi is unstable on the PoW chain because all high-value transactions are redistributed by miners (also known as time gangster attacks) .

For large-scale systems, what you need is immutability-miners cannot rewrite confirmed blocks. This will protect previous blocks from being reallocated. In addition, if the DeFi protocol exists on a separate Ethereum 2.0 shard, they will not be vulnerable to lightning attacks.

In my estimation, the lightning strike brought us a small but useful reminder that this is just a start. We do not yet have an excellent architecture to build the financial system of the future.

Lightning loans are now the new normal. Perhaps in the long run, all assets on Ethereum can be invested in Lightning Loans. All collateral held by the exchange, Uniswap's collateral, and maybe all ERC-20 standard tokens.

Who knows, it's just a few lines of code.