区块链的攻击有哪些,区块链攻防
请查看相关英文文档
Ⅰ Components of Blockchain
The components of Blockchain are as follows:
Openness: Block The system data of the chain is open and transparent, and everyone can participate. For example, when renting a house, you can know the previous rental information of this house and whether there have been any problems. Of course, some personal private information here is encrypted.
Autonomy: The blockchain adopts consensus-based specifications and protocols (such as a set of open and transparent algorithms), and then each node operates according to this specification, so that everything is completed by machines , there is no human element. This changes trust in people to trust in machines, and any human intervention has no effect.
The information cannot be tampered with: If the information is stored in the blockchain, it will be saved permanently and there is no way to change it. As for the 51% attack, it is basically impossible to achieve.
Anonymity: There is no personal information on the blockchain, because it is all encrypted and is a string of letters and numbers, so your various ID card information and phone number will not appear. Numbers are being resold.
Ⅱ Bitcoin Wallet
Bitcoin (bitcoin) was born from a paper in 2008.
A person signed by Satoshi Nakamoto proposed a revolutionary idea: let’s create a currency that is not controlled by the government or anyone else! This idea is crazy: there is no asset support behind it and no one is responsible for it. If you treat it as money and pay it to the other party, how can anyone be willing to accept it?
Merkle tree
It looks very similar to a binary tree, except that this one takes the hash value of the two lower nodes to get the upper node. You only need to remember the root node to detect whether the entire tree has been tampered with.
The root hash value is stored in the block header, and the transaction process is stored in the block body. Full nodes include block headers and block bodies, but light nodes (such as Bitcoin wallets on mobile phones) only include block headers. This tree can prove that a certain transaction has been written into the blockchain.
3. Consensus protocol
Two issues to pay attention to in decentralized currency:
1. Who can issue digital currency: mining.
2. How to verify the legality of transactions: blockchain.
Double spending attack
Double spending attack is a major challenge in digital currencies.
Every transaction in Bitcoin must have input and output, where the currency comes from and where it is spent.
Normally, there may be two forks, because two nodes obtain the accounting rights at the same time, and the blocks packaged by the two nodes calculate the random number at the same time. At this time, the two forks will temporarily coexist until one of the blocks finds the next block first, and this becomes the longest fork.Dharma chain, the other fork is discarded.
Sybil attack
A malicious node keeps generating accounts. If the total number of accounts exceeds half of the total accounts, it has gained control of the blockchain.
Consensus Protocol (Consensus) in Bitcoin
Some nodes are malicious, and most nodes are good.
Idea 1: Pack some transactions into blocks as candidate blocks, let each block vote, and if passed, write it into the blockchain.
No, because some malicious nodes keep publishing some blocks containing malicious transactions and keep voting, occupying resources. And some nodes do not vote.
Idea 2: Don’t vote based on the number of accounts, but vote based on computing power. Each node can generate legal transactions and put them into the block. These nodes will start to try random numbers until they find H (block header) ≤ target, then this node has accounting rights.
The only way to generate Bitcoin
coinbase transaction. There is no need to point out the source of the currency. Nodes with accounting rights (finding random numbers) will be rewarded with block production.
50BTC->25BTC->12.5BTC, the reward will be halved for every 210,000 Bitcoins.
The process of Bitcoin competing for accounting rights is called mining. The nodes competing for accounting rights are called miners.
Ⅲ Nine common ways to attack the blockchain
Nine common ways to attack the blockchain. Many people know about the blockchain, and We all know that the blockchain can be attacked. Many people don’t know which chains or methods can attack the blockchain. Let’s take a look at it with the editor. I hope it can help you.
Nine common ways to attack the blockchain
1. Eclipse attack - a node will select "x" nodes as the basis for accessing the blockchain, and the node will obtain the area from these "x" nodes Blockchain data.
If the attacker can make the "x" nodes selected by this node all nodes controllable by the attacker, the attacked node can be placed in an "isolated" state. The attacked node will be isolated from the main network and completely controlled by the attacker.
2. Witch Attack - The "witch" here does not refer to a woman with magic, but comes from an American movie "Sybil". The protagonist in the play has 16 layers of magic and plays 16 different characters. Key to the same role. The witch attack refers to an attack launched by the same node disguised as a different node.
The attacker uses forged identities to disguise a small number of nodes into a large number of nodes, thereby affecting the entire network. Attackers may use witch attacks to double spend, achieve 51% attacks, etc., and implement eclipse attacks.Attack, usually the witch attack will be carried out first.
3. Alien attack - Alien attack is also called "address pollution".
When different public chains use compatible handshake protocols, we call these public chains homogeneous chains. The attacker adds the node data of the same chain to the attacked public chain node. When the attacked public chain node communicates and exchanges address pools, it will pollute the address pools of other normal nodes and continue to pollute the entire public chain network. , leading to a decrease in the communication performance of the public chain, and ultimately causing node congestion and other phenomena.
4. Selfish Mining_The consensus mechanism of the blockchain determines that nodes will agree that the longest chain is real and effective. An attacker can continue to mine the latest block without broadcasting it, thereby hiding the blocks he mined.
When the block hidden by the attacker node is longer than the longest block published on the chain, it will be broadcast again, thus becoming the longest chain, causing the original longest chain to roll back, thereby achieving attacks such as double spending. .
5. Mining Trojan_The attacker spreads the mining program to other people's computers by uploading malicious programs to the public network or creating worms.
Use other people's computer resources and electricity to mine and obtain mining benefits. An attacked computer will consume a lot of resources, causing the computer to freeze and shorten its service life.
6. 51% computing power attack_51% computing power attack is one of the most famous attack methods in the blockchain.
In a POW consensus blockchain network, computing power is power. When more than 50% of the computing power is controlled by one person, that person can cancel and block transactions at will, thereby achieving double spending.
7. Time hijacking attack_A node determines its time based on the median time of other nodes.
If an attacker places a malicious node list into the peer node list of the attacked node, he can control the time of this node, such as through an eclipse attack.
8. Finney attack_If the attacker can hide a block containing his own transaction, it is possible to achieve a double spend.
When an exchange or other institution accepts a transaction with 0 confirmations, an attacker can make a transfer to it, spend the funds already spent in its hidden block, and transfer the hidden block to the new transaction before the block is broadcast. broadcast.
Because the hidden block time is earlier, subsequent spending will be rolled back, thus achieving double spending.
9. Racial attack_This type of attack is a branch of "Finney attack". The attacker will conduct two transactions at the same time, spending the same amount of funds, one transfer to a merchant that supports 0 confirmation for withdrawal; one transfer to itself and give higher gas.
The node will prioritize transactions with higher gas, so the latter transaction will not be executed. Usually the attacker will connect to a node that is close to the attacked merchant to operate, so that the merchant will receive the transactions that are not executed first.
IV Consensus Mechanism Evaluation Criteria
Different consensus mechanisms are used on the blockchain, which will have different impacts on the overall performance of the system while meeting consistency and effectiveness. Comprehensive examinationConsidering the characteristics of each consensus mechanism, evaluate the technical level of each consensus mechanism from the following four dimensions:
1) Security. That is, whether it can prevent attacks such as secondary payments and selfish mining, and whether it has good fault tolerance. In the process of realizing the consistency of one-stop transactions in a blockchain system driven by financial transactions, the most important security issue is how to prevent and detect secondary payment behaviors. Selfish mining is a theoretical attack method that threatens the security and fairness of the Bitcoin system by using appropriate strategies to publish self-generated blocks to obtain higher relative returns. In addition, the Eclipse attack controls the network communication of the target object, forming network partitions and blocking transaction propagation. Sybil attacks affect system security by producing a large number of meaningless nodes.
2) Divine source scalability. That is, whether to support network node expansion. Scalability is one of the key factors to consider in blockchain design. Depending on the object, scalability is divided into two parts: the increase in the number of system members and the increase in the number of transactions to be confirmed. Scalability mainly considers the changes in system load and network traffic that will occur when the number of system members and the number of transactions to be confirmed increases, and is usually measured by network throughput.
3) Performance efficiency. That is, the time delay from when a transaction reaches consensus and is recorded in the blockchain to when it is finally confirmed, can also be understood as the number of confirmed transactions that the system can process per second. Unlike traditional third-party supported trading platforms, blockchain technology reaches consensus through a consensus mechanism, so its performance efficiency issues have always been a focus of research. The Bitcoin system can handle up to 7 transactions per second, which is far from being able to support the existing business volume.
4) Resource consumption. That is, in the process of reaching consensus, the amount of computing resources consumed by the system, including CPU, memory, etc. The consensus mechanism on the blockchain relies on computing resources or network communication resources to reach consensus. Taking the Bitcoin system as an example, the consensus based on the proof-of-work mechanism requires a large amount of computing resources to be mined and to provide proof of trust to complete the consensus.
IV "Blockchain Project Development Guide" reading notes
ethash
Answer: In DAPP, there is no central server to coordinate nodes or decide anything What is right and what is wrong, so it is really not easy to deal with this challenge, and the consistency protocol can be used to solve this problem.
Supplement: The core of the consensus algorithm is to solve the Byzantine Generals Problem (distributed network consistency problem).
Answer: It is difficult to fix bugs or update DAPP.
If I need to capture data from a centralized application, such as vehicle violation information, how can I ensure that the captured data is true and valid?
Answer: In order to access the centralized API, you can use the Oraclize service as a middleman, Oraclize provides TLSNotary validation for data captured from centralized service smart contracts.
The owner of a centralized application needs to be profitable to maintain the operation of the application in the long term. Although DAPP does not have an owner, like centralized applications, DAPP nodes require hardware and network resources to maintain operation. DAPP nodes need some useful rewards to maintain operation, so the internal currency appears. Most DAPPs have built-in internal currencies, or it can be said that the most successful DAPPs have built-in internal currencies. Such as Ethereum
Authorized DAPPs are not open to everyone. Authorized DAPPs inherit all attributes of permission-free DAPPs, but require permissions to participate in the network. The consensus protocols of authorized DAPPs and permissionless DAPPs are different. Authorized DAPPs have no internal currency.
The Hyperledger project is committed to developing and creating authorized DAPP technology.
Why do a few countries consider Bitcoin illegal, while most countries have not yet made a decision? The reasons are as follows:
The InterPlanetary File System is a decentralized file system.
The goal is to prevent others from using ISPs to trace the owner by making transactions almost instantaneous and hiding the information of the trading account.
Anyone can become a miner in the Ethereum network. Each miner solves the problem alone, and the first miner to solve the problem is the winner, and his reward is 5 ether coins and the transaction fees of all transactions in the block. There is no limit to how many blocks there are in a blockchain, nor is there a limit to the total number of Ether that can be generated.
Any node in the network can check whether the blockchain is legal. First check whether the transaction is legal in the blockchain and the verification of the timestamp, and then check whether the target value and random number of the block are legal. , whether miners receive legal rewards, etc.
How do nodes discover other nodes in the network?
Ethereum’s node discovery protocol: Kadelima. In this protocol, there is a special node Bootstrap node. It saves a list of all nodes connected to it over a period of time, but does not save the blockchain itself.
When peer nodes connect to the Ethereum network, they first connect to Bootstrap nodes.
There can be multiple Ethereum instances, that is, different networks each with their own network ID.
The two main Ethereum networks are the mainnet and the testnet. Ethereum is traded on the mainnet, while the testnet is for developers to test.
A decentralized communication protocol that supports broadcasts, user-to-user, encrypted messages, etc., but is not used to transmit big data.
A decentralized file system.
geth provides a JSON-RPC API for other applications to communicate with them. Serve JSON-RPC API using HTTP, WebSocket and other protocols.
The APIs provided by the JSON-RPC API are divided into the following types:
Nodes in the Ethereum network communicate using port 30303 by default.
--networkid is used to specify the network ID, 1 represents the main network ID, the default value is 1, 2 represents the test network ID
--dev marks running a private network
--etherbase specifies the wallet address where the rewards earned from mining are deposited
--unlock unlocks one or more accounts
The Ethereum wallet is bundled with geth. When running Ethereum, it tries to discover a local geth instance and connect to it; if it cannot find geth running, it starts its own geth node. Ethereum wallet uses IPC to communicate with geth. geth supports file-based IPC.
The name of the next major update to Ethereum. Serenity changes the consensus protocol to casper and will integrate state channels and sharding.
Casper implements a process that punishes all malicious actors. This is how Proof of Stake works under Casper:
Validators stake a certain percentage of the ether they own as collateral. Then, they will start validating the blocks. That is, when they find a block that they believe can be added to the chain, they will place a bet to verify it.
If the block is added to the chain, then validators will receive a reward proportional to their stake. However, if a validator acts in a malicious manner and attempts to do something "nothing at stake", they will be immediately punished and all their equity will be chopped off. As you can see, Casper is designed to work on a trustless system and is more Byzantine fault tolerant.
The payment channel feature allows more than two transactions sending ether to another account to be combined into two transactions. Its working principle is: Suppose X is a video website owner and Y is a user. X charges 1 Ether per minute. Now X wants Y to pay money every minute while watching the video. Of course, Y can broadcast the transaction every minute, but there are some problems here, such as X has to wait for confirmation, so the video will be interrupted for a while. Payment channels can solve this problem. Using a payment channel, Y can broadcast a lock transaction to lock some ether (say 100 ether) for X for a period of time(eg 24 hours). Now every time you watch a minute of video, Y will send a signature record indicating that it can be unlocked, one Ether will enter X's account, and the rest will enter Y's account. After another minute, Y will send a signature record indicating that it can be unlocked, two ether coins will go into X's account, and the rest will go into Y's account. This process will continue while Y watches the video on the X website. Now assume that Y has watched 100 hours of video or 24 hours is up, X will broadcast the final signature record to the network to receive the money into his account. If X does not withdraw the money within 24 hours, the full amount will be returned to Y. So in the blockchain, we will see two types of transactions: lock and unlock.
Sybil attack
51% attack
Supplement: Large data cannot be stored. There are currently distributed storage methods such as Swarm and IPFS to choose from
Put all Everything is stored in memory, so once the node is restarted, the previous state will be lost.
Default listening port: 8545
VI Witch Attack and Double Flower Attack
The name of Witch Attack comes from the 1973 movie of the same name adapted from the novel "Sybil". The heroine in the movie, Sybil Dorsett, suffers from dissociative identity disorder and has 16 personalities.
The bottom layer of the blockchain is the P2P network. Each node in the network can join or exit at any time. In order to maintain the effectiveness of the network, a piece of data often needs to be deployed on several distributed nodes. If a malicious node pretends to have multiple identities, there is a chance that all data can be obtained. Let me give an analogy below:
Suppose Shenlong creates seven dragon balls and puts them on the earth respectively. Every corner. So Shenlong announced to the world that one person from each continent should come to receive the dragon ball. At this time, I, who was proficient in the art of disguise, pretended to be people from seven different regions and came to Shenlong to get the dragon balls. Originally, Shenlong placed the Dragon Balls in different parts of the world to balance the power of various places. However, because I forged my identity, I successfully obtained all the Dragon Balls and controlled the earth.
The above metaphor is the essence of the witch attack.
Double-spending attack is an attack method faced by most blockchain encrypted digital currencies. As the name suggests, a double-spend attack means that a valid amount of money is spent twice.
The feasibility of double-spend attacks is entirely due to the consensus mechanism of the blockchain. Take Bitcoin as an example. Since Bitcoin's POW consensus mechanism is an eventually consistent consensus, it takes a certain amount of time for a transaction to be unanimously confirmed by all nodes in the network, and attackers use this time gap to carry out attacks. Give an example in life:
If bank A has two branches, B and C. However, this bank's accounting system is relatively inefficient. Branches B and C will only synchronize their accounts with main bank A every hour. I deposited 100 yuan in main bank A. An hour later, branches B and C synchronized their accounts, so I can check in both B and C that I have 100 yuan. After that, I used my account through branch B to buy 100 yuan of delicious food, and then used my account through branch C to sell Wei and buy 100 yuan of fun food. Since the accounts between branches B and C cannot be synchronized at any time, branch C still thinks that I have 100 yuan when I go to buy some fun.
The above is a double-spend attack, and "double-spend" is always the primary problem to be solved by a currency in circulation.
Ⅶ How should blockchain websites do some security protection work, and how to solve the problem when they are attacked
Weisan Cloud answered: Blockchain developers can take Some measures
The first is to use professional code audit services,
The second is to understand safe coding standards and nip problems in the bud.
Security of cryptographic algorithms
The development of quantum computers will bring major security threats to the cryptographic systems currently used. Blockchain mainly relies on the elliptic curve public key encryption algorithm to generate digital signatures for secure transactions. Currently, the most commonly used ECDSA, RSA, DSA, etc. cannot withstand quantum attacks in theory, and there will be greater risks. More and more Researchers are beginning to focus on cryptographic algorithms that are resistant to quantum attacks.
Of course, in addition to changing the algorithm, there is another way to improve security:
Refer to Bitcoin's handling of public key addresses to reduce the potential risks caused by public key leaks. As a user, especially a Bitcoin user, the balance after each transaction is stored in a new address to ensure that the public key of the address where Bitcoin funds are stored is not leaked.
Security of consensus mechanism
The current consensus mechanisms include Proof of Work (PoW), Proof of Stake (PoS), and Delegated Proof of Stake (DPoS). , Practical Byzantine Fault Tolerance (PBFT), etc.
Ⅷ How is the security of blockchain? What are the risks of blockchain?
The hottest topic at the beginning of the new year is blockchain, but there are many more. People are skeptical about its security and risks, so how about the security of blockchain? What are the risks of blockchain? Below we will give you the answers one by one. I hope it will be helpful to you after reading them.
How is the security of blockchain Anyuan?
First of all, blockchain is a distributed database technology. Distributed technology mainly refers to storage architecture. Distributed by blockchainThe architecture not only stores ledger data on each node, but each node must contain data for the entire ledger. This completely distributed architecture brings extremely high security, and no one can destroy all nodes at the same time.
Secondly, blockchain technology can achieve tamper resistance through "blocks" and "chains". The unit of data storage in the blockchain is the block. When each block is generated, it must contain the unique "characteristic value" of the previous block (which can be regarded as the ID card of the block). Each block is generated strictly according to the The order of time is lined up to form a "chain".
Security is a major feature of blockchain technology. However, from the perspective of privacy protection, the block chain emphasizes openness and transparency, and any node has the right to operate according to the consensus algorithm, so it is not suitable for scenarios where data privacy needs to be protected.
What are the risks of blockchain?
1. Technical risk: For example, the launch of Ethereum was once popular, but because it is a digital currency with smart contracts, it brings the risk of hacker attacks due to possible loopholes in smart contracts. THEDAO, the largest crowdfunding project in Ethereum, was hacked and lost more than $60 million.
2. Legal risks: The legality issues of digital currency issuance, notarization and confirmation of rights, and legality issues of evidence, including legality issues of smart contracts, digital bills, accounting and liquidation, and equity crowdfunding, are currently in my country and The rest of the world is still legally blank.
3. Crime risks: Using digital currencies to abscond with the money, using digital currencies to launder money and illegal gambling, using smart contracts and digital bills designed to defraud profits, using blockchain technology to commit anonymous crimes, etc. Due to the current regulatory gap, there may be huge criminal risks.
The above is what the editor brings to you. How about the security of blockchain? What are the risks of blockchain? of the entire content.
Ⅸ Interpretation of flash loan attacks
How to prevent flash loan attacks? img=' https://P3 . toutiaoimg.com/large/PGC-image/rrzyiw 2 HF 9 Q1 TN '/(Ovie’s Church, Van Gogh)
In one sentence, these attacks are Very "gorgeous". In each attack, the attacker immediately borrowed hundreds of thousands of dollars in ETH without spending a penny, and then earned hundreds of thousands of stolen funds through a series of vulnerable chain protocols. Repay the ETH loan you borrowed in huge amounts. It all happened in a split second. That is done in a single Ethereum transaction.
Cover by Carmine Infantino.
We don’t know who these attackers are or where they come from. They came empty-handed and took hundreds of thousands of dollars worth of stuff without leaving a trace.
In the wake of these attacks, I’ve been thinking about flash loans and their impact on DeFi security. I think it deserves some honest thought. In short, I think flash loans are a huge security for DeFithreaten. However, flash loans are not going away, and we need to carefully consider their impact on the future of DeFi security.
What is a flash loan?
The concept of flash loans was first proposed by Max Wolff, the founder of Marble Agreement, in 2018. Marble calls itself the “smart contract bank” on the market. Its product is very simple, but extremely innovative in terms of DeFi: risk-free lending through smart contracts. (Blue Fox Note: Regarding what flash loans are, please refer to previous articles "Crypto Flash Loans: The Magical New Invention of Internet Money" "Flash Loans Strategy: Can Attackers Take Maker's $700 Million in Collateral?" "bZx Enlightenment of the incident》)
How can there be a zero-risk loan?
Traditional lenders bear two forms of risk. First, default risk: it would be terrible if the borrower ran away. A second risk for lenders is illiquidity risk: if a lender lends too much at the wrong time or fails to collect repayments on time, the lender may unexpectedly lack liquidity and be unable to meet its obligations.
Quick loans mitigate both risks. This is basically how a flash loan works: I lend you the amount of money you want in one transaction. However, before this transaction is completed, you must at least repay the money I lent you. If you cannot do this, I will automatically rollback your transaction. Yes, smart contracts can do this.
In short, your flash loan is atomic: if you fail to repay the loan, the entire thing reverts as if the loan never happened. This kind of thing can only happen on the blockchain. For example, you cannot flash pay your loan on BitMEX. This is because the smart contract platform can only process a single transaction at a time, so everything that happens in a single transaction is executed sequentially as a batch process. You can think of it as "freeze time" during transaction execution. On the other hand, centralized exchanges may have competition that prevents your order from being filled. On the blockchain, you can ensure that all your code runs in order.
So let's think about economics. Traditional lenders are compensated in two ways: by the filing risk they bear (default risk and liquidity risk), and by the opportunity cost of lending their capital (e.g., borrowing money if I can get 2% interest elsewhere People have to pay me more than the 2% risk-free fee).
Flash loans are different. There is literally no risk and no opportunity cost with flash loans. This is because the borrower “freezes time” during the duration of their flash loan. Therefore, in the eyes of others, capital within the system has always been risk-free and burden-free, and cannot earn interest elsewhere (that is, there is no opportunity to offset costs).
In a sense, this means there is no cost to lenders doing flash loans. This is very counterintuitive. So, what should the cost of a flash loan be in equilibrium? (Blue Fox Note: When we talk about equilibrium here, we mean when we are fully competitive, mature and stable)
Basically flash loans should be free. Or, more accuratelyLocally, a small fee is paid to share the cost of including the extra three lines of code that make the asset available for flash lending.
Remko Bloman
Flash loans cannot charge interest in the traditional sense because the validity period of such loans is zero (arbitrary APR*0=0). Of course, if a flash loan lender charges higher fees, they can easily be outperformed by other flash loan pools charging lower interest rates.
Quick loans make capital a real commodity. This competition will inevitably lead to zero fees or negligible nominal fees. DYdX currently has zero handling fees for flash loans. AAVE, on the other hand, charges 0.09% of the principal for flash loans. I suspect this is unsustainable. In fact, some in their community are already calling for the cost to be reduced to zero. (Note that neither attack used AAVE as their quick loan pool)
What are the loans used for?
The initial promotion of flash loans was that they were basically used for arbitrage. Marble’s announcement claims: “With flash loans, traders can borrow money from Marble Bank, then buy tokens on one DEX, sell the tokens at a higher price on another DEX, and then transfer the money Return it to the bank and earn arbitrage gains in a single atomic transaction."
In fact, judging from the transaction volume, most flash loans so far have been used for this type of arbitrage.
Use of Quick Loans on AAVE. Origin: AAVE
However, the transaction volume is small. Since the launch of AAVE’s flash loan business, its loan amount has been only $10,000. This is minuscule compared to DeFi’s arbitrage and liquidation markets.
This is because most arbitrage is performed by competitive arbitrageurs running sophisticated bots. They participate in chain-first gas auctions and use gas tokens to optimize transaction costs. This is a very competitive market and these people are more than happy to keep some tokens on their balance sheet to optimize their returns.
On the other hand, borrowing money from AAVE costs 80kgas and charges 0.09% of the principal, which is a high price for arbitrageurs competing for the tiny spread. In fact, in most AAVE arbitrage trades, borrowers end up paying more to the borrowing pool than they receive from the arbitrage.
In the long run, arbitrageurs are unlikely to use flash loans for arbitrage unless there are special circumstances. But there are other more compelling use cases for flash loans in DeFi. One example is loan refinancing. For example, let's say I have a Maker Vault (Blue Fox Note: Collateralized Debt Position) in which $100 of ETH is locked, and I borrow 40 DAI from it. That is, excluding the debt, I There is still a net position of $60. Now, let's say I want to refinance at Compound to get a better interest rate. Typically, I need to buy back 40 Dai to close my CDP, which requires some upfront capital. The alternative now is that I could lend out 40 Dai via a flash loan, close the $100 CDP, and deposit the $60 worth of unlocked ETH into Compound, exchange the remaining $40 worth of ETH into Dai via Uniswap, and then use it to repay the flash loan. Boom! Atomic 0 capital refinancing.
This is really amazing. This is a great example of currency LEGO in action. 1x.ag actually built a margin trading aggregator that automates all of this using flash loans. But flash loans can be cool, and bZx attackers show us they’re more than just fun and games.
Flash loan attacks have a significant impact on security
I am increasingly convinced that what flash loans really unlock is flash loan attacks, a capital-intensive attack funded by flash loans. We saw this phenomenon for the first time with the recent bZx attack, and I suspect this is just the tip of the iceberg.
There are two main reasons why flash loans are particularly attractive to attackers:
Many attacks require large amounts of upfront capital (such as oracle manipulation attacks). If you are earning a positive return on your investment of $10 million worth of ETH, it’s probably not arbitrage – you might say it’s bullshit.
You may not like the fact that exchange blacklists are part of today’s blockchain security model. It's very slimy and centralized. But this is an important reality that informs the calculus of these attacks.
In Bitcoin's white paper, Satoshi Nakamoto claimed that Bitcoin is secure from attack because: "Attackers should find it more profitable to follow the rules... than to undermine the effectiveness of the system and its wealth. .”
With flash loans, attackers no longer need to have a stake in the process. (Blue Fox Note: In other words, destroying the system will not affect the attacker's self-interest, because the attacker has no stake). Flash loans essentially change the risk for attackers. Remember, flash loans accumulate! Subject to gas limits, you can actually pool various flash loan pools in a single transaction (up to $50 million) and funnel all the funds into a single fragile contract. It's a $50 million battering ram that now allows anyone to pound any pinata on a chain. This is really scary.
Of course, just because you're rich doesn't mean you can't attack the protocol. If the DeFi stack was as secure as it claims, none of this would be a problem – what types of protocols are unsafe for whales? You might say that failure to consider this is a mistake.
However, we acknowledge that Ethereum itself may also be subject to a 51% attack, and the current attack cost is less than $200,000 per hour. This is not a very large amount of money. If Ethereum’s own security model is basically built on capital restrictions, then why are we so quick to scoff at DeFi usage that can be successfully attacked by $10 million? (To be clear, I don’t think these numbers—which conveniently ignore slippage and undersupply—plus consensus layer security and usage layer security are the same thing. But you get the idea.)
So, How to mitigate flash loan attacks?
Suppose I am a DeFi protocol and I want to avoid being attacked by flash loans. The natural possible question is, ICan I detect if the user I am interacting with is using flash loans?
The simple answer is: no.
EVM does not allow you to read storage from any other contract. So if you want to know what's going on with another contract, this contract can tell you. Therefore, if you want to know if a flash loan contract is being used, you must ask the contract directly. Today, many lending protocols do not respond to such inquiries (and generally speaking, there is no way to force the behavior of flash loan borrowers). Plus, even if you try to check, it’s easy to mislead such queries by using agency contracts or by cascading flash loan pools. Simply put, it’s often difficult to tell whether a storage user is using a flash loan.
Put simply, if someone knocks on your contract's front door with $10 million, you have no way of telling if it's their own money. So, what real options do we have to prevent flash loan attacks? We can consider the following methods.
Convince flash loan pools to stop providing services.
Ha, just kidding. This is the crypto world, you know it!
Seriously, trying to get lending pools to stop offering flash loans is like trying to stop noise pollution—a classic tragedy of the commons. It is in each protocol’s self-interest to offer flash loans, and their users would want to use this feature for legitimate reasons. Therefore, we can ignore this one. Flash loans are not going away.
Forcing critical transactions to occur across two blocks
Please note that flash loans allow you to borrow funds within a single transaction time period. If you need a capital-intensive transaction to span two blocks, then the user must withdraw a loan for at least two blocks, thereby defeating any flash loan attack. (Note: To do this, users must lock their assets between two blocks to prevent them from repaying the loan. If you don't think about the design properly, the user may just perform a flash loan attack in these two blocks)
Obviously, this comes with a huge UX trade-off: it means transactions are no longer synchronous. It's extremely bad for the average user, and it's a difficult step to make the decision to take. (Blue Fox Notes: In order to prevent flash loan attacks and lead to poor user experience, this is obviously the next step)
Many developers are troubled by asynchronous smart contract operations, such as interaction with layer 2 and cross-sharding of Ethereum 2.0 communication. Ironically, asynchrony actually makes these systems more secure against flash loans because you can't cross shards or layer 2 in a single atomic transaction. This means there will be no cross-ETH2.0 sharding or layer 2 flash loan attacks against DEXs.
Require on-chain proof to prove that the user’s previous balance has not changed due to the flash loan
If there is a way to detect the user’s true balance (that is, their balance before they obtained the loan), we can Defeat flash loan attacks.
There is no way to do this natively in the EVM, however, you can do something hackish. This is what you do:
Before a user interacts with your protocol, you ask for a Merkle that proves the end of the previous blockDemonstrate that they have sufficient balances to account for their current use of funds. You need to track this for every user on every block. (Ari Juels outlined this method to me)
This method may have some effect. Of course, there are thorny problems: verifying these on-chain proofs is very expensive, and no user will want to generate these proofs and pay gas fees for it. Also, it is possible that the user had changed their balance earlier in the same block for completely legitimate reasons. So, in theory it has some advantages, but it's not a practical solution.
None of the three solutions mentioned above are particularly promising. I believe there is no comprehensive defense against flash loan attacks. However, there are two specific uses that do mitigate flash loan attacks: market price-based oracles and governance tokens.
For market-based price oracles like Uniswap or OasisDEX, flash loan attacks prevent you from using the current mid-market price as an oracle under any circumstances. It’s child’s play for an attacker to move the mid-market price in a single transaction and create a flash crash, destroying price oracles.
The best solution here is to use a weighted average of the last X blocks via TWAP or VWAP. Uniswap v2 will provide this natively. There is also Polaris, which is a general method that provides moving averages for DeFi protocols. Ironically, Polaris was also built by Marble founder Max Wolff. (Polaris has now been abandoned, but Max deserves credit for seeing something in this corner)
On-chain governance itself is a worm in its own can. On-chain governance is typically determined by token-weighted voting among governance token holders. However, if these governance tokens appear in flash loan pools, then any attacker can pick up a large number of governance tokens and do whatever they want.
Of course, most governance protocols require these tokens to be locked during voting to prevent flash loan attacks. However, some forms of voting do not require this, such as carbon voting, or Maker's execution contract. Today, with the emergence of flash loan attacks, these forms of voting should be considered completely compromised.
Ideally, this would be fine if governance tokens were not available for flash loans. However, this does not depend on the issuer of the token, but on the market. Therefore, all governance actions should require locking to prevent flash loan attacks. Compound’s new COMP token goes a step further by requiring time-based weighting for all protocol votes, weakening even conventional lending attacks against its governance token.
More broadly, all governance tokens must have timelocks. Time locks require that all governance decisions must wait for a period of time before they can take effect (Compound's time lock is two days). This allows the system to recover from any unexpected governance attacks. Although MKR is not yet able to receive a large number of flash loans,MakerDAO has recently been called upon to implement measures due to its vulnerability to such attacks. It recently implemented a 24-hour time lock, shutting down such attack vectors.
What does this all mean in the long run?
I believe the bZx attack changed all that.
This won’t be the last flash loan attack. The second bZx attack is a copycat of the first, and I suspect there will be a wave of attacks in the coming months. All this DeFi lego is now being laughed at by thousands of smart teenagers from the farthest corners of the world, looking under a microscope trying to discover ways in which flash loan attacks can be carried out. If they manage to successfully exploit a vulnerability, they can earn hundreds of thousands of dollars, which in most parts of the world can be significantly life-changing.
Some say flash loans don’t change anything because these attacks are always possible if the attacker has enough money. This is both correct and quite incorrect. Most whales don’t know how to hack smart contracts, and most smart attackers don’t have millions of dollars in assets. (Blue Fox Notes: What I mean here is that there is little overlap between the two. Those who have both are the most terrifying attackers. But the arrival of flash loans has given attackers free tools) Now, anyone can spend just a few points Money can rent a $50 million wrecking ball. From now on this changes the way every building is constructed.
Being attacked by a flash loan after the bZx attack is as embarrassing as being attacked by a reentrancy attack after the DAO attack: you won't get sympathy from people. You should know this.
Finally, these events got me thinking about an old concept in cryptocurrencies: the value extractable by miners. Miner extractable value is the value that miners can extract from the blockchain system. This includes block rewards and transaction fees. But it also includes more malicious forms of value extraction. Such as reordering transactions or inserting rogue transactions into blocks.
Fundamentally, you should treat all of these flash loan attacks as a single transaction in the mempool that can make a lot of money. For example, the second bZx attack generated $645,000 worth of ETH. If you are a miner and you are about to start mining a new block, imagine looking at the previous block transactions and saying to yourself: “Wait, what was that? When the last block contained a profit of $645,000, Why am I even trying to mine a new block for a measly $500 or so?” Instead of expanding the blockchain, you go back and try to rewrite history to make yourself a flash loan attacker. Think about it: this one transaction alone costs more than 4 hours of honestly mining Ethereum!
This is isomorphic to a special superblock containing 1000x the regular block reward, and as you would expect, the rational outcome of such a superblock should be for miners to compete to isolate the chain's reward and provide for Steal the block yourself.
In equilibrium, all flash loan attacks should eventually be withdrawn by miners. (Note that they should also end up stealing all on-chain arbitrage and liquidation) Ironically, this wouldPrevent flash loan attacks from occurring since it would prevent attackers from exploiting these vulnerabilities to profit. Perhaps eventually miners will solicit attack code through private channels and pay discoverers' fees to would-be attackers. Technically, such operations can be done trustlessly using zero-knowledge proofs.
But this is all still science fiction. Apparently miners haven't done that today.
Why wouldn't they?
There are tons of reasons. It's hard and requires a lot of work. EVM is difficult to simulate, it is risky, there may be loopholes that lead to loss of funds or orphaned blocks, and rogue mining pools may face PR crises and be branded as "Ethereum enemies". For now, miners may lose more in business, R&D, and orphan blocks than they gain from doing so.
That's true today. The future may not always be like this.
This provides another impetus for Ethereum to accelerate and transition to ETH2.0. While DeFi on Ethereum is always interesting, it is absolute and irrevocable. DeFi is unstable on the PoW chain because all high-value transactions are subject to redistribution by miners (also known as time robber attacks).
In order for these systems to work at scale, you need finality—so that miners cannot rewrite confirmed blocks. This will protect transactions from previous blocks from being reallocated. Additionally, DeFi protocols are less susceptible to flash loan attacks if they exist in a separate ETH2.0 shard.
In my estimation, the flash loan attack is a small but useful reminder that it’s still early days. We are far from having a sustainable architecture, one that can be built for the financial system of the future.
For now, flash loans are the new normal. Maybe in the long term, all assets on Ethereum can be used for flash loans: all collateral held on exchanges, all collateral in Uniswap, maybe all ERC-20 tokens themselves.
Who knows? It's just a matter of a few lines of code.
Related questions and answers: