Attacking the DeFi ecosystem with flash loans for fun and profit (2020)
palkeo.com
palkeo.com
If you identify an arbitrage opportunity in the market, you can atomically borrow a large sum of money to take advantage of the price difference. You also have the added assurance that if the arbitrage opportunity goes away before you can take advantage of it, the entire transaction fails and you only lose the Ethereum transaction fee. It's essentially risk-free arbitrage.
This paper [1] dives into detail about how these arbitrage mechanics play out on the blockchain, and how both arbitrageurs and miners manipulate transactions in order to make a profit.
Anyway, it’s not clear to me why flash loan providers are still a thing, as they seem to be open to a second layer of abuse: transaction copying / sniping:
All flash loan borrowing transactions are profitable (otherwise they wouldn’t be able to pay back the loan) - but why let the originator of the transaction keep that profit? What a sensible attacker should do is: 1) watch for flash loan transactions to be submitted by someone, then 2) quickly submit a duplicate transaction with a larger fee, but change the destination wallets to your own. That way, you get all the proceeds of a theft, and not just the loan interest rate.
Given this possibility, flash loan pools could be considered as ‘bait’ or a trap for the unwary thief...
There are two main differences:
1) The atomic nature of a flash loan makes flash loan arbitrage much less risky than performing arbitrage traditionally. Doing the same type of arbitrage non-atomically may mean that you miss the arbitrage opportunity, resulting in a loss from having to pay back the loan you took out plus interest without having made any money with it.
2) Because the debt must be repaid in the same transaction, the loan is uncollateralized. As far as I know, one cannot borrow millions of dollars in the traditional financial system without putting up some kind of collateral.
> What a sensible attacker should do is: 1) watch for flash loan transactions to be submitted by someone, then 2) quickly submit a duplicate transaction with a larger fee, but change the destination wallets to your own.
This has been observed on the blockchain in practice. The paper I linked to describes the mechanics of how this plays out and what strategies competing arbitrageurs use to win these opportunities.
The future is likely private smart contracts like Secret (https://scrt.network/)in which the contract’s internal state and the function calls are entirely obscured using sMPC or by leveraging SGX enclaves. This makes it impossible to frontrun in most cases.
Whether an unauditable financial system is a good thing or bad thing is still up for debate.
One interesting thing I think is still under dev/consideration is adding the ability for MakerDAO to make "flash mint loans"(https://forum.makerdao.com/t/mip25-flash-mint-module/4400/9) -- essentially a flash loan where the caller can mint an arbitrary amount of DAI without having to back it with anything, so long as they pay it back + fee at the end.
There's a similiar idea being worked out for WETH10 (https://github.com/WETH10/WETH10#flash-loans), a project trying to make a feature update of the WETH (wrapped ether) token.
I'm honestly unsure WTH the impact of something like these would be, but would definitely prevent arbitrage from going too far out of bounds, since there would always be unlimited liquidity.
Multi-party atomic financial transactions are kinda insane.
Aave is 0.09%: https://aave.com/flash-loans/
It is also an important part of uniswap: https://uniswap.org/docs/v2/core-concepts/flash-swaps/
Any fees on a flash loan will disincentive closing arbitrage positions to that fee amount.
Borrow x amount of tokens. (Withdraw)
Call a function (i.e. Logic to handle flashloaned funds). (Call)
Deposit back x (+2 wei) amount of tokens. (Deposit)
It looks like unlimited leverage for flat fee.Because of the atomicity of the transaction, there's no way to default on the loan. If you can't pay it back, you're never loaned the money in the first place.
[1] https://medium.com/@kentmakishima/the-43k-defi-magic-trick-f...
Basically if you put $1000 of capital into the pot for making flash loans, then you are foregoing the X% / year that you could earn on interest, i.e. you are losing money.
It’s entirely possible that platforms are running these flash loans as a loss leader to drive adoption, but in a mature market and at scale, you’d expect there to be a small fee.
(Or just that the success-case fee covers the loss in the failure case, but that would break if the % of failed txns increased, so might not be a stable equilibrium. )
For a lot of transactions like this its actually miners who can detect and rewrite these transactions to take advantage of the arbitrage opportunities first, for this reason this cost is called "miner extractable value" or MEV.
However, note this fee doesn't accrue to the lender!
The funds aren't foregoing interest in all cases though. Ex: uniswap, curve, etc all require assets to be deposited, and pay depositors trading fees. These protocols could generate additional income by providing assets for flash loans without affecting the income received for acting as an amm.
Vitalik himself acknowledges this, the guy is quite honest and straightforward about its limitations: https://thenextweb.com/hardfork/2019/08/19/vitalik-buterin-e...
Vitalik Buterin: Using Ethereum is expensive, and its blockchain is ‘almost full’ He also said blockchain's 'problem' is that every computer verifies every transaction
Actually blockchains are a first-generation technology that do global consensus for every block, which literally means all transactions in the world must go through one computer in the world (the miner) although it’s a different one each time. And the situation is actually worse, since you don’t know who would mine the next block in advance, every transaction must be sent to every potential miner! Imagine if BitTorrent had every computer store and seed every movie instead of using DHT.
The ability to send or loan arbitrarily large amounts for a fixed fee is a symptom of centralization. In a fully distributed network, transaction fees would have to be proportional to transaction size!
Almost every other protocol on the Internet does not have such bottlenecks in its design. No one asks how many emails or websites can be served per second. Blockchain is trying to secure every transaction using the entire network! That is why so much electricity is wasted just to do 7 transactions per second.
The next generation of crypto will actually be able to power payments using embarrasingly parallel architecture. Until then, we have blockchain.
Ethereum is nicknamed the “world computer” for a reason. Gas fees are super high for small transactions like paying for coffee or voting in a secure election. Just one app KryptoKitties can clog up the entire network.
We built Intercoin apps on top of Ethereum (https://intercoin.org/applications) but we are not going to wait around for Ethereum 2.0 - which is blockchain also. Kik Messenger and others have long gotten off.
That said currently ethereum has many L2 solutions (https://ethereum.org/en/developers/docs/layer-2-scaling/) that "run in parallel" and result in low gas fees.
So far I've not seen any hint of an "embarrasingly parallel architecture" that can satisfy the safety requirements that a blockchain also does and run smart contracts. I'd be happy to read up if you can point me to any research or projects that I've missed.
Ethereum has so much network effect that these other projects need to actually pay people to use them over Ethereum. Not to mention they're also more centralized.
A lot of other platform projects are providing bridges which makes it possible to use those projects as some sort of an L2 for ethereum. If a lot of dapps starts migrating to those instead of to native L2 solutions it can get ugly.
However, the actual technical research paper with rigorous mathematical proofs is still going through peer review, but if you email me I am happy to share it with you.
Really, what you need is a distributed hash table (like MaidSAFE), or randomness beacons (like Algorand) to select a subset of the network. This paper shows mathematically that the probability of a double-spend goes down exponentially with the number of notaries, and having the entire network secure every transaction, no matter the size, is wayyyy overkill:
If you don’t like ME saying it — here is VITALIK HIMSELF saying it, the guy is quite honest and straightforward about its limitations: https://thenextweb.com/hardfork/2019/08/19/vitalik-buterin-e...
Vitalik Buterin: Using Ethereum is expensive, and its blockchain is ‘almost full’
He also said blockchain's 'problem' is that every computer verifies every transaction
Actually Ethereum 2.0 should be “fast enough” for many applications. It’s still going to be doing a global consensus, but at least it will be able to handle actual real world usage - people paying for coffee, let’s say, or voting in elections.
In fact, a major reason that so many ICOs from 2017 were considered scams is that the tokens could not actually be used for their intended purpose. Teams like Kik Messenger discovered this early on and moved away:
https://medium.com/kinblog/kin-pushing-ahead-next-steps-on-t...
[0] https://www.forbes.com/sites/kellyphillipserb/2019/09/19/por...
The more important reason flash loans work on Ethereum is that Ethereum runs programmatic contracts that can take the output of a function call from a different contract as their input. This is something that doesn't exist outside of the world of smart/programmatic contracts.
The blockchain just provides the immutable ordering of transactions and credible neutrality of access-control needed for the state of programmatic contracts to accrue value.
Been hearing that for years. Anyone yet have anything running that allows a digital currency to scale without being vulnerable to the attacks Bitcoin can resist?
For the time being, no one has found vulnerabilities in it.
What can I say, the first generation of any technology is laughably inadequate as a replacement for what came before. That is why for example hardlh anyone uses Bitcoin in everyday transactions and why we still don’t use technology to secure voting, but that will change. As an aside, I don’t think blockchain is the best technology for voting but it’s the buzzword that people understand:
https://cointelegraph.com/news/russian-blockchain-voting-sys...
You can actually follow the money yourself:
https://etherscan.io/address/0x148426fdc4c8a51b96b4bed827907... https://etherscan.io/address/0xb8C6Ad5fE7CB6cC72F2C4196dca11...
It looks like neither attacker was able to cash out, but the seccond attacker is moving his funds around even to this day.
Fascinating but I obviously have no understanding of either.
What makes you say that?
If they wanted to, they could simply send the funds back to Tornado Cash, which is basically Zcash-running-on-Ethereum-EVM. The seed funds to run the attack came out of Tornado Cash. It's liquid enough to handle a deposit this size, although it probably wasn't liquid enough back in May.
[1] - https://news.ycombinator.com/item?id=25806183
I used to do some work on Bitcoin, but this all reads like some Cirque du Soleil fever dream.
These market making smart contracts will trade at 50% swings within a single block?
> The core of this trade utilises a margin trade on a DEX (bZx) to increase the price of WBTC/ETH on another DEX (Uniswap) and thus creates an arbitrage opportunity. The trader then borrows WBTC using ETH as collateral (on Compound), and then purchases ETH at a “cheaper” price on the distorted (Uniswap) DEX market. To maximise the profit, the adversary then converts the “cheap” ETH to purchase WBTC at a non-manipulated market price over a period of two days after the flash loan.
So we start with a flash loan of ETH, go through two smart contracts to end up holding 112 “WBTC” against their borrowed 5,500 ETH.
> In steps 4 , the trader opens a short position for ETH against WBTC (on bZx), with a 5× leverage.
I’m having trouble parsing this sentence. What exactly does this mean?
> Upon receiving this request, bZx transacts 5,637.62 ETH on an exchange (Uniswap) for only 51.35 WBTC (at 109.79 ETH/WBTC).
What does ‘transacts’ mean in this sentence? And bZx is offering an anonymous trader 5x leverage... based on what?
I think they are selling ETH to buy WBTC which blows out the order book and ends up crashing the price of ETH from 30ETH/WBTC to 100ETH/WBTC?
> Note that at the start of block 9484688, Uniswap has a total supply of 2,817.77 ETH and 77.09 WBTC (at 36.55 ETH/WBTC).
I’m not sure why the total supply on Uniswap of each token is expressed as a price?
The trader then converts 112.00 WBTC to 6,871.41 ETH at 61.35 ETH/WBTC on Uniswap. Recall they started off by getting 112 WBTC for 5,500 ETH.
> In step 6 the trader pays back the loan, paying a 1×10^11 Wei fee. Note that dYdX only requires a fee of 1 Wei.
No idea what Wei are or what the significance is of why they would pay 100 billion of them instead of 1, where they come from or how they are accounted for in the profitability.
> After the flash loan transaction (i.e. the first part of this pump and arbitrage trade), the trader gained 71.41 ETH...
Wait, I thought they had netted ~1,209 ETH, where does this 71.41 come from?
> ...and has an over-collateralized loan of 5,500 ETH for 112 WBTC (49.10 ETH/WBTC).
What happened to the 5x leveraged short position?
And how in the world did they coordinate all of these separate and interlinked orders to execute in multiple transactions all in the same block in an atomic fashion?
Anyway, in the end they need to give back the WBTC by buying WBTC with the ETH they netted;
> In total, the adversarial trader exchanged 4, 377.72 ETH for 112 WBTC (at 39.08 ETH/WBTC) to redeem 5, 500.00 ETH. (over the following two days)
Look... whatever people are out there building on these networks, this is just bizarre.
The thing where the “market” smart contract will just take the money and blindly trade at ever more ridiculous prices (because it’s just two pools of assets and a dumb formula) is crazy. I don’t expect it to last too long in the wild (at least at any scale, obviously some smart contracts that exist now will technically be around forever) or make it into many real world uses of the tech.
Well functioning markets have protection against extreme price moves, including flash crashes, whether caused by flash loans or other algorithms.
It might even turn out that good decentralised markets end up being resistant to atomically chaining trading transactions with other actions generally.
[1] An example of this in action can be seen here: https://twitter.com/RudolphTamlyn/status/1349719025933291520
Anyhow, wei are a unit of gas, since you usually pay for gas in ETH you can just think of it as paying small amounts of ETH.
For the Uniswap price question, just look up the formula.
Leverage is provided presumably against some collateral.
You chain contract calls to make them execute in the same block. It's more of a side effect of how time works when dealing with blocks rather than something you have to try hard to do.
[2] https://github.com/keeperdao/whitepaper/blob/main/whitepaper...
This does not prevent a large miner from watching the mempool and picking the right transaction order that they want.
It also will only protect the very small number of people who are using keeperdao. It is a very nice try, but I don't think it'll go very far.
Disclosure: very large scale miner working on this exact problem space
Also remember, the cost of ETH to a large miner is significantly lower than market price (hence mining instead of buying).
As well as a course to teach how to build an arbitrage bot using flashloans: https://eattheblocks-pro.teachable.com/p/profitable-flashloa...
(just to be clear I am not selling a magical money making machine, what you will learn is the process of building an arbitrage bot, and you will still need to do some work to make some profits)
A flash loan requires that the funds be returned before the end of a transaction. If removing funds is a two-step process, then by definition you can’t use attack it with a flash loan.
Of course there’s always the possibility of someone with that much capital to stake attacking. But the number of participants with $50 million in funds lying around is a lot less than the number with $0. It drastically shrinks the attack surface.
[1] https://forum.makerdao.com/t/urgent-flash-loans-and-securing...
It is very easy these days to go between Eth <-> BTC without any KYC/AML.
Here's an old computerphile video: https://youtu.be/UlLN0QERWBs
Etherscan provides such a service for ethereum: https://info.etherscan.com/ethprotect/
As long as there are enough centralised services with enough volume that agree such tokens are tainted the decision is effectively made for the entire ecosystem.
Just as in real life getting someone to sign on the dotted line with the intent to cheat them is fraud that can invalidate the contractual obligation, technical exploitation of a smart contract is the same. As you say, it might not even be illegal, details matter, but it might also well be a felony.
Shapeshift just DROPPED its KYC.
https://erikvoorhees.medium.com/no-more-kyc-with-shapeshift-...
>Second, cross-chain exchanges may not be possible in a fully trustless manner.
Monero <-> Bitcoin atomic swaps (codename: farcaster) are coming later this year. In the mean time, you can use Bisq.
Actually it's quite easy with something like tornado.cash.
How it ever got moved to prod is beyond me.
EDIT: And when I mean formally define, I mean something that is machine-checkable so implementations would have a conformance suite.
I get the impression from their documentation (https://developers.cardano.org/en/virtual-machines/iele/abou...) that it's intended to address that, but I'm no expert in this area.
I actually hadn't considered this issue at all until you mentioned it, but was aware that one of Cardano's selling points is a focus on verifiability (e.g. via their Haskell-based Plutus language for smart contracts), and came across this IELE after a quick search through their materials.
WASM couldn't be ported over to Ethereum because it isn't, so eWASM is being developed as the deterministic subset of WASM, for possible use in Ethereum.
Honest projects which actually deliver are ignored completely.