Unmasking Role-Play Attack Strategies in Exploiting Decentralized Finance (DeFi) Systems

The rapid growth and adoption of decentralized finance (DeFi) systems have been accompanied by various threats, notably those emerging from vulnerabilities in their intricate design. In our work, we introduce and define an attack strategy termed as Role-Play Attack, in which the attacker acts as multiple roles concurrently to exploit the DeFi system and cause substantial financial losses. We provide a formal definition of this strategy and demonstrate its potential impacts by revealing the total loss of \$435.1M caused by 14 historical attacks with applying this pattern. Besides, we mathematically analyzed the attacks with top 2 losses and retrofitted the corresponding attack pattern by concrete execution, indicating that this strategy could increase the potential profit for original attacks by \$3.34M (51.4%) and \$3.76M (12.0%), respectively.


INTRODUCTION
Blockchain technology has deeply impacted the financial technology environment [1].Its revolutionary potential led to the development of decentralized finance (DeFi), a promising financial system [2].Nevertheless, the unique complexity of DeFi systems, like any emerging technology, entails an array of potential vulnerabilities that could be exploited [3].These flaws primarily compromise implementation flaws resulting from coding issues and logic flaws resulting from poor designs.Rectifying implementation vulnerabilities usually involves code-focused analysis, while addressing logic vulnerabilities often requires mathematical and financial expertise.
Against this intricate backdrop of potential threats, we delve into various historical attacks instigated by logic vulnerabilities.A careful study of these incidents led us to identify a recurrent pattern, which we have termed Role-Play Attack.This attack strategy involves an attacker acting as various roles (e.g., lender, borrower, trader) simultaneously, exploiting the DeFi system to achieve substantial financial benefits.Instead of aiming at certain vulnerabilities like re-entrancy attacks, Role-Play Attack emphasizes the combination of roles and actions involved in an attack.In light of this, we present a formal definition of Role-Play Attack in Section 3 and delve into two historical attack methods in Section 4. In Section 5, we prove that the attacker's profits could be further promoted with this strategy and analyze the possible maximum gains.We propose our conclusion in Section 7 and point out two potential future works to further analyze or mitigate this attack in Section 6.
The main contributions of this paper are summarized as follows: • Formal Definition of Role-Play Attack: We propose a definition for a recurrent attack strategy, the Role-Play Attack.
Through our data collection and manual inspection, we identified this strategy in 14 distinct DeFi security incidents, leading to an accumulated financial loss of $435.1 million1 .• Comprehensive Analysis of Role-Play Attack: We conduct a detailed exploration of the role-play strategy by analyzing two distinct attack methods with mathematical analysis.Our analysis brings forth the roles and their specific impacts, unveiling the complex dynamics underlying such malicious exploits.• Promoting Profits of Role-Play Attack : We delve into two historical attack events' profitability from an attacker's viewpoint.Using advanced modeling and analysis, we have achieved a significant improvement in the attacker's profits from two historical attacks, by $3.34M (51.4%) and $3.76M (12.0%), respectively.

BACKGROUND AND RELATED WORKS
The inception of blockchain technology, distinguished by its decentralization and distributed ledger capabilities, brought forth a new paradigm for transparent and tamper-resistant transaction recording [4].Blockchain, which is essentially a permissionless peer-to-peer (P2P) network, uses Proof of Work (PoW) [5,6] and Proof of Stake (PoS) [7] as separate consensus procedures and allows any member to transmit transactions [8].Notably, the emergence of smart contracts extended the financial utility of blockchain, catalyzing the rapid growth of DeFi with a peak historic total value locked (TVL) exceeding $150 billion [3].

Decentralized Finance (DeFi)
Decentralized finance (DeFi) is a novel, permissionless financial system employing blockchain technology to execute operations in a transparent, decentralized manner [9,10].At its core, DeFi relies on autonomous smart contracts to maintain transaction transparency and immutability [9].By facilitating peer-to-peer transactions, DeFi aims to establish robust alternatives to traditional finance [2,10].Readers seeking a comprehensive understanding of DeFi are referred to existing literature, notably reference [3,11].Three of the primary infrastructures within the DeFi ecosystem are as follows: • Lending: In DeFi lending markets, users have the chance to lend their assets to earn interest, resembling traditional finance mechanisms where debt is a crucial instrument [12].The interest rates, typically determined by supply-borrow dynamics [13], generate a revenue stream.To safeguard lenders, borrowers are often required to provide more collateral than the loan value, which can be liquidated if its value dips [14].• Decentralized Exchange (DEX): DEXes allow users to trade their assets for another through liquidity pools.Instead of using the classic order book model where buyers and sellers place orders at their preferred prices, DEXes often use Auto Market Makers (AMMs) [15].AMMs algorithmically set the price of tokens, offering a seamless and efficient trading experience that doesn't require matching individual buy and sell orders.• Yield: DeFi yielding protocols, often built on top of lending markets or DEXes, offer users with interests to earn from farming their assets.Profits often come from interest earned and rewards in the form of additional tokens.To optimize the profits, different yield farming strategies have been adopted in practical use [16].

DeFi Attack
The exponential growth of DeFi has made it an alluring target for hackers [17].Between April 30, 2018, and April 30, 2022, DeFi protocols experienced losses exceeding $3 billion due to various attacks [18].Noteworthy attack types include re-entrancy attacks, flash-loan attacks, and oracle manipulation attacks, with each exploiting different facets of the DeFi system vulnerabilities.Numerous studies have addressed various forms of attacks [19][20][21][22].Remarkably, Qin et al. systematically analyzed flash loan attacks and performed optimizations on historical attack incidents [23].

Security of DeFi
The security of DeFi is multifaceted, addressing both coderelated vulnerabilities and economic design flaws.From the perspective of smart contract code vulnerabilities, several detection tools have been developed.These tools utilize static and dynamic analysis to detect potential issues [24].Static analysis examines the contract's code without executing it, aiming to find vulnerabilities through code patterns and flow analysis [25,26].On the other hand, dynamic analysis involves executing the contract's code in a controlled environment to monitor the runtime behavior [27][28][29][30].
The realm of DeFi security extends beyond mere code vulnerabilities [2,3].The design of the underlying economic mechanisms can also introduce exploitable weak points [31].It is important to take a comprehensive approach to DeFi security, considering both code-related and economic risks.

DEFINITIONS AND MODELS 3.1 Formal Definition
As we delve into the exploration of the Role-Play Attack, it is paramount to begin by setting a clear understanding of the terminologies and concepts that form the foundation of such an attack strategy.• Multiple roles activities: The attacker  engages in a malicious activity by acting as multiple roles   , i.e.,  = { 1 ,  2 , . . ., } • The result: The gain  of the attacker is the cumulative sum of the gains of the roles (some of which can be negative), i.e., A normal user benefits from the DeFi system with gains , while an attacker of a Role-Play Attack can achieve significantly greater gains with  >> .

Common Roles in Different DeFi Systems
DeFi presents a wide array of services to users, enabling a multifaceted engagement within each specific DeFi ecosystem.Depending on the system type, users can adopt various roles.Some notable systems and their corresponding user roles are described below.The functions of each role are shown in Table 1.
• Lending Markets Lender: A user who deposits assets into the market to be loaned, typically receiving interest payments as a reward.
Borrower: A user who obtains assets from the market, ordinarily providing collateral to safeguard the loan.
Liquidator: A user responsible for reimbursing a borrower's debt when the value of the collateral falls short, thereby maintaining the system's balance and stability.

• DEX
Trader: A user who engages in exchanging assets.Liquidity Provider: A user who contributes funds to a liquidity pool.These funds are then used to facilitate trading activities within the liquidity pool, earning swap fees in return.

• Yield Farming
Yield Farmer: A user who commits assets to a DeFi protocol with the intention of earning rewards.
Yield Source: Typically a DeFi protocol offering rewards to users for depositing or locking their assets.These incentives can emanate from various sources, such as transaction fees.

ROLE-PLAY ATTACKS: A DEEP DIVE 4.1 Role-Play Attacks in history
Role-Play Attacks have been a common tactic among malicious entities intending to exploit DeFi systems, thereby inflicting significant financial losses.To understand the scale of these breaches, we have constructed a dataset comprising 14 Role-Play Attack incidents that occurred between September 28, 2020, and May 13, 2023.These attacks caused losses exceeding $400 million in total, which, as illustrated in Table 2, may serve as a conservative estimate of the comprehensive financial loss induced by such attack patterns.The dataset is primarily derived from sources such as BlockSec [32], Rekt News Leaderboard [33], PeckShield [34], and SlowMist [35].
To gain a better understanding of such attack patterns, we delve into this prevalent strategy by examining two case studies in Sections 4.2 and 4.3.These incidents, whose losses rank top 2 in our dataset, represent two typical types of Role-Play Attacks 2 .

Borrow and Buy Attack (B&B Attack)
-Role-Play Attack in Lending and DEX Market exploit [37], which rank 17th and 75th on the Rekt News Leaderboard with losses of $115 million and $8.4 million, respectively.These incidents consist of iterations of a common malicious process wherein the attacker repeatedly borrows and purchases crypto assets, a strategy we refer to as the Borrow and Buy Attack (B&B Attack).
A further exemplar of this attack pattern is the Agora Lending exploit.In this case, the hacker (identified by the address 0xFFD90C77e-aBa8c9F24580a2E0088C0C940ac9C48) executed a B&B Attack on Agora Lending [38].Throughout this attack, the exploiter fulfilled three roles: trader, lender, and borrower.
The Agora Lending attack was halted by the project developers, who lowered the collateral factor of the impacted token to zero [39].In this section and Section 5, we reconstruct the attack and also explore ways to potentially enhance the attacker's profits by performing reversed attack operations and simulating the roles of a second and subsequent hackers, as shown in Figure 2.
Overall Attack Process: To portray the shared pattern of B&B Attacks, we propose a typical attack sequence wherein a lending market allows a low-liquidity token (denoted as token A) to be used as collateral.This attack sequence can be segmented into four steps: (1) The attacker bought some token A and deposited it as collateral.
(2) The attacker borrowed against this collateral to purchase more of token A, thereby driving up its price.These tokens were subsequently deposited into the lending market.
(3) This increase in price and collateral quantity enabled the attacker to borrow more assets.(4) The attacker repeated this process to drain the lending market.

State Assumptions and Models:
To simplify the complexity of real-world DeFi scenarios, we make several assumptions to more effectively analyze the attack process: • We categorize the funds related to this attack into two types: manipulated and stable assets.The latter refers to funds in the lending pools whose prices remained stable during the attack.• There are three DeFi components involved in this attack: the lending market, the Automated Market Maker (AMM), and the oracle.These components are defined as follows: -Lending market: Facilitates deposits and loans in accordance with borrowing rates and asset prices provided by the oracle.-AMM : We consider this AMM to be a Uniswap-V2style constant product market maker with the equation  =  [40].The swap fee is disregarded due to its insignificance relative to the potential profits.-Oracle: In reality, the oracle extracts the time-weighted average price from the AMM, necessitating the attacker to wait for the oracle's update.For our theoretical analysis, we suppose the attacker waits for a price update after every swap transaction.
• For a mathematical analysis of the attack process, we define the following variables: -: The initial stable assets in the market (denoted in USD).-: The initial amount of borrowable manipulated assets in the lending market (denoted in manipulated assets).
-: The collateral rate of the manipulated assets, which is the ratio between the maximum amount of currency that can be borrowed and the total amount of collateral.
-: The collateral rate of the stable assets.
-: The required USD value to purchase the manipulated assets in one attack cycle.-: The amount of purchased assets in one attack cycle.
- 0 : The value of the stable assets in the pool.Assuming the initial asset price equals one unit of stable assets, the total value of the initial Uniswap V2 liquidity pool is 2 0 .Mathematical Analysis: First swap some stable assets to manipulated assets, resulting in a new price of manipulated assets: For AMM: The purchased asset can be collateralized to borrow stable assets: This attack becomes profitable when: • the value of the borrowed stable assets exceeds the asset purchase amount.(Eq.4) • there are sufficient stable assets to borrow.(Eq.5) Eq. 3 >  (4) Eq. 3 ≤  (5) When these conditions are met, having Eq. 5 hold as an equality and solving  in terms of ,  and  0 , the maximized hacker's profit will be:

Borrow and Donate Attack (B&D Attack)
-Role-Play Attack in Lending and Yield On October 28, 2021, Cream Finance [41], a prominent Ethereum lending platform, was exploited [42], resulting in a loss of $130 million with transaction hash 0x0fe2. . .1c92.Similarly, Lodestar Finance [43] fell victim to an exploit [44] on December 12, 2022, costing the platform $6.5 million as traced in transaction 0xc523. . .4e8c.These two attacks rank 13th and 88th on the Rekt News Leaderboard.These events shared a unique characteristic: collateral token prices were manipulated via direct transfer of the underlying asset to interest-bearing tokens, a category of tokens that generate yield over time.We refer to this attack as the Borrow and Donate Attack (B&D Attack).Here, the attacker played the roles of a yield farmer, lender, and borrower.
In section 5, we propose enhancements to the Lodestar Finance attack operation sequence to reduce flashloan fees and donation amounts, thereby potentially increasing the attacker's profit.We also introduce the liquidator role, which can potentially augment the attacker's profit through liquidation rewards.The processes of the primitive attack and the enhanced attack are shown in Figure 3.
Root Cause: The Cream Finance attack primarily originated from the price manipulation of Yearn's yUSD vault token (address: 0x4B5B. . .33d3).The attacker repetitively deposited and borrowed the interest-bearing token, effectively inflating the market size to yield significant profits.
Overall Attack Process: In such attacks, the attacker employed two smart contracts, referred to as A and B. Contract A was responsible for minting cryUSD (Cream Finance's lending token for yUSD, address: 0x4BAa. . .9Dd4, denoted as   ) and manipulating Yearn's yUSD vault token (denoted as   ), while Contract B was primarily used to borrow assets against ETH collateral: (1) Contract A initiated the attack by borrowing $500M using a flashloan and depositing the   into Cream Finance, minting an equivalent amount of   .(2) Contract B then borrowed $2B worth of ETH via flashloan and deposited it into Cream Finance as collateral against borrowed   from the lending market.This borrowed   was then transferred to contrac A and deposited back to mint more   .This process was repeated, each time transferring the borrowed   to contract A. (3) After repeated mints and borrows, contract A withdrew all the withdrawable   from the lending market and burned them to decrease the total supply of   .
A then purchased approximately $8M worth of   's underlying asset to donate and subsequently inflate the price of   .(4) Following process 3, Cream Finance was left with a vast quantity of bad debt (around $3B) on contract B. Contract A then borrowed $2B worth of assets against the inflated collateral, repaid the initial flash loans to conclude the attack.State Assumptions and Models: Similar to section 4.2, we simplify the model under the following assumptions: • We ignore the friction of swapping the flashloan to the underlying asset of the interest-bearing token.• The initial attack was split into various transactions due to gas limit.In our analysis, we combine them into one transaction.• We define the following variables in our mathematical analysis: -  : The initial total supply of the interest-bearing token.
-  : The initial borrowable interest-bearing token in the lending market.-: The initial borrowable assets other than the interst-bearing token in the lending market.-  , : The collateral rate of the interest-bearing token and stable assets.

Mathematical Analysis:
The attack process commences with a flashloan borrow of a significant amount denoted by  ℎ  .The fee rate of this flashloan is represented as  ℎ   ; hence, the amount to return would be: ℎ  1 −  ℎ   (7) The flashloan funds are divided into three portions: •   : the funds used to swap for underlying tokens and mint interest-bearing tokens.•   : the fund designated as the collateral for Contract B. • : the funds later used for donation purposes.
We define  as the number of iterations.After process 2, the collateral of Contract B became   while Contract B's debt was as given in Eq. 8. Contract A's collateral is illustrated in Eq. 9 and carries no debt.
The collateral rate of Contract B prior to the donation is shown in Eq. 10.After donating  amount of underlying tokens, the price was amplified by a factor of  (Eq.11), thereby causing a substantial amount of bad debt for Contract B.
Simultaneously, the collateral of Contract A is: The final profit stage includes the redemption of withdrawable   and exhausting the lending market by borrowing all other assets.The profit will be as shown in Eq. 13.Setting Eq. 13 equal to    and enabling Eq. 11 hold equility, we can solve for  as in Eq. 14.
The final profit for the attacker is: where  ℎ  =      and  =  − 1  −

ENHANCEMENT OF THE ATTACKS 5.1 Enhancement of the B&B Attack
In order to escalate the profit potential of the B&B Attack, the hacker, acting as a secondary trader, could execute reversed operations following the completion of the initial attack sequence, as shown in Figure 2. At this juncture, the lending market is saturated with a substantial volume of manipulated assets.Taking these manipulated assets as the unit of valuation, the price of stable assets can be effectively adjusted using similar attack methodologies.The profits of the reversed operations originate from the overestimated price for token A after the initial attack.Thus, in this reversed round of attack, we can perceive the stable assets as the manipulated assets.
If we designate the initial attack as Attack Round -I and the subsequent reversed operation as Attack Round -II, the hacker has the potential to amplify their profits by cycling through numerous attack rounds.Here, even rounds enact forward operations, and odd rounds undertake backward operations.
Mathematical Analysis: When considering iterated attack rounds, we can reflect on the transformation of state from the initial to the final state.In an ideal scenario, all manipulated assets in the lending market are borrowed and sold after an even number of rounds, leaving only stable assets in the market.When conducting a new round becomes unprofitable (Eq. 5 in section 4 cannot be concurrently satisfied), we deduce: stable assets left To maximize the attacker's profit, the hacker could implement several rounds until Eq.16 holds true.The hacker's maximized profit is given by equation Eq. 17: In practical situations, due to the discrete nature of the number of rounds, the final result may be slightly different but still significantly improved compared to the pre-modification results.

Enhancement of the B&D Attack
In this section, we will explain two key operations targeted at increasing the hacker's earnings by altering operation sequences and leveraging the liquidation process, as illustrated in Figure 3.
Adjustment of Operation Sequences Profits can be increased by draining the lending market before the donation step, directly after the iterated mint and borrow procedure (process 2 in Section 4.3).Applying this adjustment, contract A's debt (Eq.8 in 4.3) becomes Eq. 18, and its collateral before donation becomes Eq.19.
•     (18) Liquidation Profit can also be increased by adding a new liquidator role.Contract A can liquidate contract B when the attack is completed, receiving the collateral assets of contract B with a liquidation incentive.The money required to liquidate contract B and contract A's collateral, in addition to the remaining liquidation funds, will be equivalent, as shown in Eq. 20.For our purposes, we'll call the liquidation incentive component   .
With these enhancements, the final maximized profit for the hacker is represented by Eq. 21.
−  ℎ  1 −  ℎ   (21) where  ℎ  = and We can find Eq.21 can be maximized by setting   = 0 because we can increase  to reduce flashloan fees.However, due to the gas limit, we can take a proper   to tradeoff with .

Implementation
With the toolchain Foundry [45], we reconstructed the Agora Lending exploit and implemented the improved attack, which resulted in a profit of $31.34M and $35.10M, respectively, illustrating the enhancement of $3.76M (12.0%) with our refinement.We also improved the attack of the Loadstar to lower the flashloan fees and donation amount, improving the hacker's profit from around $6.5M to $9.84M by $3.34M (51.4%).

DISCUSSION
Post-Attack Value Extraction.Our research, along with others [3,23,46], has highlighted a pattern where attackers frequently don't exploit all their available opportunities, a concept known as 'leaving money on the table'.This residual value can be a potential target for subsequent attackers who copy the initial exploit.Intriguingly, this scenario also presents an opportunity for the compromised project to deploy emergency measures, such as pausing operations or activating an emergency exit.A promising direction for future research is the in-depth analysis of these potential tactics, especially the potential for rescuing funds via back-running mechanisms [47].
Mitigation Methods.We propose future research in the following areas to strengthen defenses against Role-Play Attacks: • Tailored Vulnerability Detection Toolkits: Improve the security tools, like formal verification and fuzzing, used to identify Role-Play attacks.These tools can help auditors and project developers find and fix vulnerabilities before an attack occurs.• Real-Time Anomaly Detection Systems: Explore the creation of real-time detection tools [30,48,49] capable of identifying unusual role actions.These could signal an ongoing attack, possibly leveraging heuristics or machine learning algorithms.• Design Modifications: Research into DeFi protocol design choices that limit a single transaction from playing multiple roles can be pivotal.While this may cause inconvenience, it can reduce the risk of Role-Play Attacks at the design level.

CONCLUSION
This paper delves into a recurrent attack strategy we define as the Role-Play Attack.We first propose a formal definition and categorize this attack based on the scenarios and roles.We analyzed 14 attack incidents that resulted in $435.1M in losses, demonstrating the huge threat of this attack.Furthermore, we offer a comprehensive mathematical analysis of two distinct attack methods of the Role-Play Attack: the Borrow-And-Buy Attack and the Borrow-And-Donate Attack.

Figure 2 :
Figure 2: The attack process of a B&B Attack.The left part of the figure shows the initial attack (analyzed in section 4.2) while the right part illustrades the Round -II of the refined attack (analyzed in section 5.1).

Figure 3 :
Figure 3: The attack process of a B&D Attack.The primitive attack is analyzed in Section 4.3 while the enhanced attack is analyzed in Section 5.2.

Table 1 :
Different roles in common DeFi protocols.
,  =  1 ,  2 , . . .∈  ,   ∈  • Actions () and Events (): An action  is a function call sequence that achieves a purposeful activity.A common approach involves utilizing the approve and borrow functions to execute a borrowing action.An event  comprises a sequence of actions:  =  1 ,  2 , . . .• Gains (): The cumulative gain of an address  involved in an event , denoted as   , is the sum of the profit     of the address (denominated in USD) from each action   within , i.e.,    =   1    2  . . .• Roles (): A role  is an address that performs particular actions.Examples of roles include borrowers, traders and lenders.3.1.2Threat Models.Let   represent a Role-Play Attack, as shown in Figure 1, We can define the threat model as the followings.Figure 1: An example of Role-Play Attack Protocol Role Function Lending Lender lend(asset, amount) Borrower borrow(asset, amount) Liquidator liquidate(borrower, debt) DEX Trader swap(token1, token2, amount) Liquidity Provider addLiquidity(pool, amount) Yield Yield Farmer claimReward() Yield Source addReward(amount)

Table 2 :
[36]salient examples of the Role-Play Attack pattern can be found in the Mango Market exploit[36]and the Moola 2 †: B&B Attack in Section 4.2, ⋆: B&D Attack in Section 4.3.The 14 previous attack incidents with the Role-Play Attack pattern.The total losses are worth 435.1MUSD.