Multi-token sandwich attack detection system and method in Ethereum network
By integrating the sandwich attack detection system in the Ethereum client, analyzing transaction events in real time and identifying attack characteristics, the real-time detection problem of multi-token sandwich attacks in the Ethereum network is solved, and efficient security protection is achieved.
Patent Information
- Application Number
- CN202510285682.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-11
- Publication Date
- 2025-07-18
AI Technical Summary
The existing technology cannot monitor and identify multi-token sandwich attacks in real time in the Ethereum network, resulting in low detection efficiency and timely warnings, and cannot effectively prevent such attacks.
The sandwich attack detection system is integrated within the Ethereum client. By monitoring block headers and transaction data, the transaction events are parsed in real time, and the Swap events and Transfer events of Uniswap V2 or V3 routers are identified. Combined with advanced data analysis technology, the combination characteristics of pre-transactions, victim transactions and post-transactions are determined, so as to achieve accurate detection of multi-token sandwich attacks and issue an alarm when an attack is detected.
Real-time and accurate identification and early warning of multi-token sandwich attacks in the Ethereum network, improve detection efficiency, enhance network security protection capabilities, and timely prevent potential attacks.
Smart Images

Figure CN120342655A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of computer network security, and relates to the detection technology of malicious attacks. Specifically, it is a detection system and method for multi-token sandwich attacks in the Ethereum network. Background Art
[0002] With the rapid development of blockchain technology, Ethereum has become one of the most influential public blockchains in the world. Relying on its rich smart contract functions and decentralized financial application platform, Ethereum provides users with convenient financial products and transparent trading mechanisms, thus promoting the transformation of the global financial system towards decentralization. Smart contracts enable automated operations, allowing users to obtain various financial services such as lending, staking, and trading in real time, achieving efficient, secure, and low-cost cross-border transactions without relying on traditional financial intermediaries. However, the openness and transparency of Ethereum, while providing users with a traceable and verifiable trading environment, also make it a prime target for attackers. Attackers can take advantage of the public nature and sequentiality of on-chain transaction information to carry out malicious operations, causing direct economic losses to users.
[0003] Ethereum adopts an account-based transaction model, laying a solid foundation for the widespread application of smart contracts. With the help of smart contracts, decentralized applications can be executed efficiently. Users can directly participate in activities such as asset management, lending, trading, and insurance, thus enjoying unprecedented financial freedom. However, the rapid rise of DeFi applications has also posed severe security challenges to the platform and users. The openness of the blockchain not only enhances market trust but also enables attackers to easily obtain transaction information and even launch attacks before transaction confirmation.
[0004] In addition, the transaction staging area (mempool) in the blockchain network, as a buffer for unconfirmed transactions, has gradually exposed security risks due to its transparency characteristics. Attackers monitor the pending transactions in the mempool in real time, use algorithms to predict and simulate the transaction execution results, and thus accurately capture arbitrage opportunities. In recent years, the total locked value in the decentralized finance field has achieved explosive growth. The highly concentrated funds have not only promoted industry innovation but also given rise to new hybrid attack methods such as smart contract logic flaws, flash loan portfolio attacks, and trading flow manipulation. Among many new attack methods, the sandwich attack has become the main threat to decentralized exchanges due to its concealment and high return rate. Its basic principle is that the attacker constructs a continuous trading sequence of "buy - victim transaction - sell" by finely controlling the transaction sorting and time - space, in order to achieve arbitrage gains. Attackers usually first capture the target transaction characteristics using a blockchain browser or a customized listening tool, then adopt a dynamic Gas bidding strategy to ensure that their front - end transactions are preferentially packaged and executed. Immediately after the victim transaction is executed, they quickly submit the back - end transactions, so that the entire attack sequence is continuously executed within the same block. This bundling of on - chain transactions not only distorts the pricing mechanism of automated market makers but may also trigger a chain reaction, leading to abnormal fluctuations in the liquidity pool. Research shows that the number of sandwich attack events occurring each month is huge, and the resulting hidden asset losses cannot be ignored.
[0005] Currently, there are mainly two types of detection methods for sandwich attacks: one is to rely on post - event retrospective analysis, which identifies abnormal patterns such as transaction sorting, Gas fees, and address matching in historical transaction data; the other is based on statistical analysis or machine learning models to model and classify abnormal behaviors in transaction sequences. However, these methods have obvious deficiencies. Post - event retrospective analysis cannot provide early warnings in the initial stage of the attack, resulting in the ability to trace malicious transactions only after the attack occurs; while statistical and machine learning methods usually rely on a large amount of historical data for training, and their detection accuracy and adaptability are relatively low when dealing with complex multi - token transaction scenarios and constantly changing attack strategies. In addition, existing methods are mostly independent of real - time blockchain data, lacking the ability to monitor and protect the dynamics of on - chain transactions in real time, and unable to provide immediate risk warnings for traders, thus limiting their real - time protection effect. Summary of the Invention
[0006] The purpose of the present invention is to provide a detection system and method for multi - token sandwich attacks in the Ethereum network. This method directly integrates the detector inside the Ethereum client (Geth), without relying on external third - party data sources or retrospective analysis of post - event contract logs, and can monitor block data in real time, and simultaneously identify single - token and multi - token sandwich attacks, thereby greatly improving the detection efficiency.
[0007] Technical Solution: A detection method for multi - token sandwich attacks in the Ethereum network, including:
[0008] S1. Register and initialize a sandwich attack detector during the client startup process, continuously monitor newly generated block headers and transaction data, and capture node data;
[0009] S2. Parse the captured transactions in sequence. By detecting whether there is a Swap event of Uniswap V2 or V3 router in the event log, and the consecutive occurrence of at least two Transfer events and one Swap event, determine whether the transaction has completed an effective token exchange;
[0010] If it is confirmed that the transaction has completed an effective token exchange, record the key information including the hash of the transaction, the sender address, the recipient address, the Gas fee, and the token pair contract address, providing a basis for sandwich attack determination;
[0011] S3. Traverse from the first transaction in the block transaction sequence, and identify the previous transaction Ta1, the victim transaction Tv, and the subsequent transaction Ta2 based on the following steps:
[0012] a) Take the first transaction in the block transaction sequence as the candidate previous transaction Ta1;
[0013] b) If Ta1 completes an effective token exchange, search backward at most 12 transactions from the index where the previous transaction Ta1 is located to find a candidate subsequent transaction Ta2 that has the same token pair contract address as the previous transaction Ta1, the same sender address, and a different transaction hash;
[0014] c) If a transaction that appears between the previous transaction Ta1 and the subsequent transaction Ta2 has the same token pair contract address as the previous transaction Ta1, and its sender and recipient addresses are both different from the sender address of the previous transaction Ta1, then determine this transaction as the victim transaction Tv;
[0015] d) When there is at least one victim transaction Tv, a sandwich attack sequence is formed; if the number of victim transactions is greater than 1, it is regarded as a multi-token sandwich attack.
[0016] Based on the implementation carrier of the above method, the present invention provides a detection system for multi-token sandwich attacks in the Ethereum network. The system includes a node data capture module, a transaction parsing module, and a sandwich attack determination module; it also includes:
[0017] An alarm and log recording module: used to immediately output structured logs and send alarm messages after detecting a sandwich attack sequence, and record information such as block number, hash value, sender address, recipient address, token pair contract address, etc.;
[0018] By directly invoking the above-mentioned modules within the Ethereum client, the system can detect all transactions in real time after a new block is generated, and identify multiple victim transactions in a multi-token scenario, including identifying single-token sandwich attacks and multi-token sandwich attacks.
[0019] In the above system, the node data capture module subscribes to the new block header information based on the subscription interface provided by Geth. When detecting the arrival of a new block header, it timely obtains all transactions and event logs in the block and transfers the raw data to the transaction parsing module.
[0020] Furthermore, the transaction parsing module sequentially parses the event logs of each transaction, identifies the log entries arranged in the order of Transfer, Transfer, Swap in the transaction logs. If the corresponding contract address is the UniswapV2 or V3 routing contract, it further extracts the call method names, including functions such as swapExactTokensForTokens, swapTokensForExactTokens, exactInputSingle, and determines whether a valid token exchange is completed.
[0021] Furthermore, when the sandwich attack determination module identifies the front transaction Ta1 and the back transaction Ta2, it also restricts the difference in their index positions within the block to ensure that the number of transactions between the front transaction Ta1 and the back transaction Ta2 does not exceed the preset threshold n, where the default value of n is 12, to ensure that these three transactions are close enough in chronological order and spatial position. This value is the optimal threshold determined based on the statistical analysis of historical sandwich attack transaction data.
[0022] If multiple victim transactions Tv1, Tv2, Tv3,... are detected between the front transaction Ta1 and the back transaction Ta2, and they all satisfy that the sender and the receiver are not the same as the front transaction Ta1 and the token pair addresses involved are the same as the front transaction Ta1, it is determined as a multi-victim transaction in the multi-token sandwich attack scenario.
[0023] Furthermore, the creation and service registration of the detector instance are implemented in the Ethereum client startup process, specifically including:
[0024] After creating a full node during the startup process of the Ethereum client, embed the sandwich attack detector inside the client in the form of a system service, and call the custom API registration method to register the application programming interface of the detector with the client; the custom API defines the namespace, version, service instance, and visibility parameters of the API, and maps the detection method in the Ethereum client interaction console. The custom detection methods include detect.currentBlockSandwich, detect.newBlockSandwich, and detect.stop. By only registering the core detection functions and necessary shutdown functions, this method effectively reduces the memory and computing resource overhead and avoids negatively affecting the running efficiency of the full node.
[0025] The main working process of the system described in the present invention can be summarized as follows:
[0026] (1) When the Geth client starts, initialize the sandwich attack detector instance and embed it into the client through the system API registration unit;
[0027] (2) Subscribe to new block headers or specified historical blocks to obtain all transaction data and event logs of the target block;
[0028] (3) Call the multi-token sandwich attack determination module and perform the following steps for the transaction sequence in the target block:
[0029] a) Take the first transaction in the block transaction sequence as the candidate pre-transaction Ta1, and call the transaction parsing module to obtain Ta1 data;
[0030] b) If Ta1 completes an effective token exchange, search for the post-transaction Ta2 among the at most n transactions after the pre-transaction Ta1, which needs to satisfy the same token pair address, the same sender, and different hash values;
[0031] c) Classify all victim transactions Tv that are located between the pre-transaction Ta1 and the post-transaction Ta2 and meet the victim transaction characteristics into the same sandwich attack unit;
[0032] (4) If an attack chain composed of the pre-transaction Ta1, the victim transaction Tv, and the post-transaction Ta2 is detected, immediately call the alarm and log recording module for structured storage and alarm;
[0033] (5) Repeat the above steps until the detection is completed or the service is stopped by calling detect.stop.
[0034] Furthermore, the system includes the following two operating modes:
[0035] Detect the latest block mode: By subscribing to the new block header information and automatically executing the detection algorithm after each new block is generated;
[0036] Detect the historical block mode: Receive the target block range and check whether the input is legal, and then execute the detection one by one for the specified block range.
[0037] Finally, the alarm and logging module of the present invention can write the log information into a specified log file for the operation and maintenance personnel to view.
[0038] Beneficial effects: By directly integrating the sandwich attack detection system into the Ethereum execution client, the present invention realizes the real-time, accurate identification and response to potential sandwich attacks in the network. The system adopts advanced listening technology to monitor and record all transaction activities in the Ethereum network in real time, and makes full use of the built-in low-latency data transmission mechanism of the client to ensure that each block and all its transaction data are completely captured. The system deeply analyzes the detailed information of each transaction (including the sender and receiver addresses, transaction amount, Gas fee and other key data), and accurately identifies abnormal transactions that are significantly different from the normal transaction mode with the help of advanced data analysis technology. Subsequently, the system comprehensively analyzes the temporal and logical relationships between transactions using a preset algorithm, and can quickly and accurately locate potential sandwich attack behaviors. Once an abnormal attack is detected, the alarm mechanism will be immediately activated to send detailed warning information to the network administrator so that they can take effective protective measures in time. By directly performing real-time detection within the Ethereum execution client, the present invention significantly improves the efficiency and accuracy of sandwich attack detection, effectively enhances the overall security protection ability of the Ethereum network, and provides strong security technical support for the blockchain ecosystem. Description of the Drawings
[0039] Figure 1 is a schematic diagram of a sandwich attack;
[0040] Figure 2 is a schematic diagram of the working process of the method of the present invention;
[0041] Figure 3 is the call process of the method for exchanging tokens of the Uniswap V2 and V3 routing contracts;
[0042] Figure 4 is the core algorithm for detecting sandwich attacks within a block;
[0043] Figure 5 is the CPU occupancy rate of the detector for detecting historical data blocks
[0044] Figure 6 is the number of sandwich attacks detected by the detector and the number of Eigenphi
[0045] Figure 7 is the CPU usage of the detector in the working and stopped states;
[0046] Figure 8 is an example of the sandwich attack result detected by the detector;
[0047] Figure 9 is the time difference between the block time of the block where the sandwich attack occurs and the time when the sandwich attack is detected. Specific Embodiments
[0048] To describe in detail the technical solution disclosed by the present invention, the following further introduces with reference to the accompanying drawings of the specification.
[0049] Ethereum is an innovative decentralized platform that not only supports cryptocurrency transactions but also promotes the development of smart contracts and decentralized applications (DApps). This platform views the blockchain as a distributed state machine, where each transaction updates the state of the network, and these states are efficiently managed through the Merkle Patricia Trie (MPT) data structure. MPT combines the verification speed of the Merkle tree and the flexibility of the Patricia tree, not only improving the data access efficiency but also enhancing the security of the blockchain state, ensuring immutability and credibility. With technological advancements, Ethereum has also shifted from the energy-intensive proof-of-work (PoW) mechanism to the more energy-efficient proof-of-stake (PoS) mechanism. In PoS, the block packaging right is allocated by staking tokens, which not only reduces energy consumption but also improves the security of the network and ensures the fairness of the incentive mechanism. Under this mechanism, the transaction processing speed is linked to the gas fee, and high-fee transactions can be processed preferentially. The Ethereum Virtual Machine (EVM), as the core component in the Ethereum network, undertakes the important task of executing smart contracts. EVM is Turing complete, meaning that as long as sufficient resources are provided, it can execute any computational task. Through EVM, smart contracts can be executed consistently across the entire Ethereum network, thus supporting the operation of decentralized applications. The design of EVM fully considers the transparency and reliability of smart contracts, enabling developers to create automatically executable smart contracts, which further promotes the innovation and development of decentralized applications.
[0050] As the cornerstone of the Ethereum ecosystem, with the development of decentralized finance (DeFi) and the increase in decentralized exchanges (DEXs), the security research of smart contracts and blockchain transactions in Ethereum has received increasing attention. The sandwich attack has become a common and highly harmful on-chain attack method. Attackers take advantage of the openness and timing advantages of Ethereum transactions to initiate buy and sell operations before and after the target transaction respectively, and obtain arbitrage profits by manipulating market prices, thus causing serious economic losses to normal traders. The present invention proposes a lightweight sandwich attack real-time detection system that can be integrated into the go-Ethereum client (Geth). Different from the existing methods that rely on post-event data analysis or third-party platform detection, this system directly runs the detection algorithm within the Ethereum execution client, uses the built-in low-latency data transmission mechanism to capture and process block information in real time, ensuring that all transaction data is completely recorded without omission. Through advanced listening technology, the system analyzes the detailed information of each transaction, including the sender and receiver addresses, transaction amount, Gas fee, and other key data, and adopts a preset advanced data analysis algorithm to carefully compare the timing and logical relationships between transactions, quickly and accurately identifying abnormal combinations composed of the attacker's pre-transaction, the victim's transaction, and the attacker's post-transaction. After detecting potential attack behaviors, the system immediately triggers an alarm mechanism to provide detailed early warning information to the network administrator, enabling them to quickly take countermeasures, thereby effectively reducing transaction risks. Experimental results show that the sandwich attack detection system described in the present invention has high detection accuracy and real-time early warning capabilities in actual block data, providing a practical technical solution for enhancing the overall security protection of the Ethereum network.
[0051] The core logic of the sandwich attack lies in inserting attacker transactions before and after the target transaction respectively to achieve market price manipulation and obtain arbitrage profits. This strategy relies on the precise utilization of transaction timing and the blockchain execution mechanism. For different transaction behaviors and market environments, the sandwich attack can adopt various transaction combination strategies, such as dynamically adjusting the Gas price to ensure the priority execution of attack transactions, or constructing complex multi-transaction sequences to maximize the arbitrage effect. In actual implementation, the code implementation methods of the sandwich attack are diverse, and attackers may obfuscate and disguise the core transaction logic to hide their true manipulation intentions, increasing the difficulty of detection and defense.
[0052] The detection method described in the present invention integrates the sandwich attack detection system into the Ethereum execution client. The advantage of this integration method is that it can identify and respond to sandwich attacks in real time before transaction confirmation. The detection system captures all transaction data in the Ethereum network in real time, deeply analyzes the detailed information of each transaction (including the sender, recipient, transaction amount, Gas fee, and other key data), and uses advanced data analysis techniques to compare the timing and logical relationships between transactions to determine whether there is a typical sandwich attack pattern. Specifically, based on a predefined sandwich attack model, the detection system identifies the combined characteristics of the attacker's pre-transaction, the victim's transaction, and the attacker's post-transaction, and verifies the transaction sequence through a simulated execution algorithm to achieve accurate detection of multi-token sandwich attacks. Since the detection system directly captures and analyzes data inside the Ethereum execution client without relying on on-chain interaction records or external third-party data sources, its detection efficiency and real-time performance have been significantly improved. In addition, the Ethereum full node running the integrated detection tool can automatically mark and alert potential sandwich attack behaviors, thus providing stronger security protection for the entire Ethereum network.
[0053] The detection system provided by the present invention includes a node data capture module, a transaction parsing module, a sandwich attack determination module, and an alarm and log recording module. Specifically:
[0054] The node data capture module registers and initializes the sandwich attack detector during the startup process of the Geth client, and continuously listens for new block headers and transaction data in the form of a system service; for each captured transaction;
[0055] The transaction parsing module determines whether a transaction has completed an effective token exchange by detecting whether there is a Swap event of the Uniswap V2 or V3 router in the event log, and the consecutive occurrence of at least two Transfer events and one Swap event. If the exchange is confirmed to be effective, it records key information such as the hash, sender, recipient, Gas fee, and token pair contract address of the transaction; subsequently, in the transaction sequence obtained by parsing, the system first locks the transaction with the characteristics of an effective token exchange as the candidate pre-transaction Ta1, then searches backward up to 12 transactions from the index where Ta1 is located to determine the candidate post-transaction Ta2, and filters out transactions that meet specific conditions (i.e., the token pair contract address is the same and the sender and recipient are both different from the sender of Ta1) between the pre-transaction Ta1 and the post-transaction Ta2 as the victim transaction (Tv), thus forming a complete sandwich attack sequence (when the number of victim transactions is greater than 1, it is regarded as a multi-token sandwich attack); finally, after detecting the above attack sequence, the system immediately calls the alarm and log recording module to output structured logs and issue real-time alarm messages, recording the attacker, victim, token pair contract, and relevant transaction details.
[0056] Combined with Figure 1 Regarding the implementation process of the sandwich attack shown, first, the victim hopes to exchange Token A in hand for Token B, while the attacker uses a real-time monitoring tool to monitor the pending transactions in the network and capture the victim's trading intention. When the attacker detects that the victim is about to execute the transaction of exchanging Token A for Token B, the attacker immediately takes action and initiates a pre-transaction Ta1 in advance to buy Token B. To ensure that the pre-transaction is preferentially packed by miners, the attacker usually sets a higher Gas fee, so as to execute this transaction first in the block and push up the market price of Token B. Subsequently, the victim's exchange transaction (victim Tv) is executed in the same block, further pushing up the price of Token B. Immediately afterwards, the attacker quickly submits a post-transaction Ta2, selling the previously bought Token B at a higher price before the market price drops and exchanging it back for Token A, thus realizing arbitrage gains. The whole process depends on the attacker's precise control of the trading timing and Gas bidding strategy, forming a typical sandwich attack mode of "pre-transaction - victim transaction - post-transaction". In addition, in a multi-token trading environment, the attacker may adopt the strategy of combining multiple victim transactions to further expand arbitrage gains. In order to avoid detection and defense measures, the attacker often disguises the trading parameters and code logic, making it difficult for the protection system to identify their true intentions in a timely manner.
[0057] The above process shows how the attacker realizes the implementation of the sandwich attack through real-time data analysis and refined trading operations, effectively utilizing the publicity and transparency of blockchain transactions to obtain illegal economic benefits.
[0058] The sandwich attack detector described in the present invention is integrated into the server running the Ethereum full node. Compared with the existing detection methods for sandwich attacks, this method significantly improves the detection efficiency, can detect the sandwich attack risk in the block in real time, and issue a warning.
[0059] Combined with Figure 2 As shown, first, a full node is created in the Ethereum client startup process, and the registration and initialization of basic services are completed, providing complete block data and transaction information for the subsequent access of the detector. Subsequently, the application programming interface (API) of the sandwich attack detector is registered by calling a custom method, in which the namespace, version, service instance, and visibility parameters of the API are defined. Considering that not all full node users need to run the sandwich attack detection, in order to avoid unnecessary memory and computing resource consumption, only the core functions and stop detection functions necessary for the detection component are registered, rather than registering a complete reference to the Ethereum client instance.
[0060] In the Geth interactive console, the detector maps three main methods to meet the detection requirements in different scenarios: detect.currentBlockSandwich: This method is used to detect sandwich attacks on the current or specified block. One or more block numbers can be input, which is suitable for batch detection of historical blocks or analysis of a single block. detect.newBlockSandwich: This method subscribes to the newly generated block header information in the Ethereum network. Once a new block is detected, the detection logic is triggered in real time, enabling continuous monitoring of newly incoming blocks. detect.stop: This method stops the ongoing sandwich attack detection service, so that system resources can be released in a timely manner when detection is not required, avoiding additional burden on the node.
[0061] Among them, detect.currentBlockSandwich and detect.newBlockSandwich correspond to the scenarios of single detection and real-time detection respectively. However, their core detection processes are similar, and both will call the internal detection logic method (such as detectorLogic) to complete the specific transaction parsing and sandwich attack identification. Since the algorithms for parsing transaction data and identifying sandwich attacks in real-time detection and historical detection are roughly the same, only the implementation of the core detection process needs to be focused on. After obtaining the block data, this process will traverse each transaction and perform in-depth parsing, including key information such as transaction hash, sender, receiver, token pair contract address, and transaction input and output. After confirming that the transaction conforms to the characteristics of token exchange, it further determines whether it constitutes a sandwich attack pattern (i.e., the combination of the front transaction Ta1, the victim transaction Tv, and the back transaction Ta2).
[0062] Once the detection logic identifies a potential sandwich attack, the detector will output relevant information (such as transaction hash, block number, gas value, token pair contract address, etc.) through the logSandwichAttack method for node maintainers or security analysts to view. At the same time, the system can also implement more subsequent actions according to requirements, such as blocking suspicious transactions or adjusting node configurations. By being directly integrated into the Ethereum client and combined with an efficient data capture and analysis mechanism, this sandwich attack detector can provide real-time security protection for the Ethereum network without significantly increasing the burden on the node.
[0063] Combined with Figure 3As shown, in the normal Uniswap trading process, a user initiates a token exchange request to the router contract (such as swapExactTokensForTokens). After the contract execution is completed, two Transfer events and one Swap event will be generated in sequence to record the details of this token input, output, and exchange. For Uniswap V2, these events mainly come from the router calling the swap method inside the trading pair (Pair) contract; for Uniswap V3, they mainly come from the swap method in the IUniswapV3Pool interface.
[0064] Thus, whether it is V2 or V3, as long as a token exchange operation is executed, a complete sequence of Transfer→Transfer→Swap events will appear in the transaction log. It is precisely through these events that the actual exchange process of the tokens can be further identified and analyzed later, providing an entry point for subsequent detection or protection measures.
[0065] Therefore, based on the event logs generated after the transaction execution is completed, each captured transaction is scanned and analyzed one by one. First, the Swap event type is detected, and the logs in the transaction receipt are retrieved in sequence to confirm whether there is a Swap event of Uniswap V2 or V3 (by comparing the event signatures SwapEventABIEventSignatureHash or SwapEventABIEventSignatureHashV3). If no Swap event is found, it is determined that this transaction does not belong to the category of token exchange and is skipped; backtrack and match the Transfer events. After locating the Swap event, search forward for adjacent Transfer events to extract the transferred-in / transferred-out quantities of the tokens, the sender and receiver addresses, and confirm whether the feature of "at least two Transfer events and one Swap event appear continuously" is satisfied; identify the router and core methods. If the event log corresponds to the Uniswap V2 or V3 router contract and core methods such as swapExactTokensForTokens, swapTokensForExactTokens, exactInputSingle are triggered, it is determined that this transaction has completed a valid token exchange; extract the key transaction information. After confirming a valid token exchange, record the hash, sender address, receiver address, Gas fee, and token pair contract address of this transaction, providing the necessary input data for the subsequent sandwich attack determination module.
[0066] Combined with Figure 4 As shown, the implementation process of the core detection algorithm of the solution described in the present invention for block detection is introduced in detail:
[0067] (1) Within the legal block range, the detectorLogic method is used to traverse and check all transactions in the block. This method reads transactions one by one in the order they appear in the block and calls subsequent analysis steps for each transaction. First, detectorLogic filters out transactions related to token swaps (e.g., by detecting swap events on decentralized exchanges in the transaction logs) to reduce the impact of irrelevant transactions on detection efficiency. For each transaction that may involve a token swap, the system records its index position in the block to provide a basis for comparing adjacent transactions before and after;
[0068] (2) The algorithm traverses the transactions in each block and parses the detailed information of each transaction by calling the parseTransaction method. To ensure that the selected transaction Ta1 is a valid previous transaction, the algorithm further filters out transactions involving token swaps and extracts key information such as its hash value, sender address, recipient address, token pair contract address, and input / output of the transaction. If an error occurs during the parsing process or the transaction does not involve token swap operations, the transaction is skipped and the check for the next transaction continues. In this way, the algorithm can identify eligible previous transactions Ta1 and provide accurate transaction data for subsequent analysis.
[0069] (3) After successfully identifying the previous transaction Ta1, the algorithm then searches for potential subsequent transactions Ta2 among the next up to 12 transactions after Ta1. To ensure the relevance between the subsequent transaction Ta2 and the previous transaction Ta1, the algorithm uses the compareTransactionDetails1 method to compare whether the previous transaction Ta1 and the subsequent transaction Ta2 involve the same token trading pair, and makes a detailed comparison of the transaction hashes, sender addresses, and recipient addresses between the previous transaction Ta1 and the subsequent transaction Ta2. If the previous transaction Ta1 and the subsequent transaction Ta2 have the same token pair address, it indicates that the previous transaction Ta1 and the subsequent transaction Ta2 may be the attacker's previous and subsequent transactions. Continue to compare the hash values of the previous transaction Ta1 and the subsequent transaction Ta2. If the hash values are different but the sender and recipient addresses are the same, it can be determined that the subsequent transaction Ta2 is the attacker's subsequent transaction. In this process, the algorithm makes full use of the characteristic that attackers conduct atomic transactions through the same proxy contract, thus ensuring the precise identification of multi-token sandwich attacks;
[0070] (4) When the algorithm finds the eligible front transaction Ta1 and back transaction Ta2, it continues to search for potential victim transactions Tv among all the transactions between Ta1 and Ta2. Whenever a transaction is found, the algorithm extracts the detailed information of the transaction through the parseTransaction method, including the hash value, sender address, recipient address, and token pair address, etc. Then, the algorithm uses the contains method to check whether the token pair address of the front transaction Ta1 contains the token pair address of the victim transaction Tv. If the token pair address of Tv is a subset of the token pair address of the front transaction Ta1, the algorithm further uses the compareTransactionDetails2 method to compare the key attributes such as the hash value, sender address, and recipient address of the transactions. If the hash value of the victim transaction Tv is different from that of the front transaction Ta1, and its sender and recipient addresses are completely different from those of the front transaction Ta1, then this transaction may be a potential victim transaction. In this way, the algorithm can accurately identify the victim transaction Tv located between the front transaction Ta1 and the back transaction Ta2, and further confirm the existence of the multi-token sandwich attack;
[0071] (5) To record the analysis results, all eligible victim transactions Tv are recorded in the victim set B. Whenever an eligible victim transaction Tv is found, the algorithm adds it to B and saves the detailed information of the transaction, including the transaction hash, sender, recipient, token pair address, input / output value, and the gas fee of the transaction, etc. All victim transaction information will be saved in this set to ensure comprehensive recording and tracking of all potential victim transactions;
[0072] (6) Once the algorithm finishes traversing all the transactions between the front transaction Ta1 and the victim transaction Ta2, it adds the front transaction Ta1, all the victim transactions Tv in the set B, and the back transaction Ta2 together to the set A as a complete sandwich attack detection unit. Subsequently, the system immediately calls the logSandwichAttack method to make a structured record of the detected attack event. The log record content includes but is not limited to: block number, transaction hash, sender, recipient, token pair address, input / output value, and the gas fee of the transaction. The above information is output to the log file in a predetermined format for the subsequent security analysis module or operation and maintenance personnel to view and respond immediately;
[0073] Through the above steps, the algorithm can accurately identify the multi-token sandwich attack at the block level, file and output the attacker's front transaction Ta1, back transaction Ta2, and all the victim transactions Tv located between them, thus providing detailed basic data for subsequent security protection and analysis.
[0074] Based on Geth v1.14.0, the present invention implements a detector capable of detecting multi-token sandwich attacks. The Golang code requires only about 600 lines. All tests were carried out on a desktop computer equipped with an Intel Core i5 9500, 32GB of main memory, and a 3TB hard drive. The detector has been successfully applied to full nodes adopting the snap synchronization mode, and the detector has been successfully deployed and demonstrated efficient performance in monitoring sandwich attack behaviors. Given Ethereum's leading position in the field of EVM (Ethereum Virtual Machine) compatible chains, the detector proposed by the present invention also has good cross-chain compatibility and can be easily transplanted to other EVM compatible blockchains for operation.
[0075] The full node used in the present invention only retains about 2TB of on-chain data, covering approximately 3.5 million blocks over a time span of 10 months. Although this storage scale can meet most real-time monitoring requirements, compared with archival nodes that occupy approximately 13TB of storage space, there are still certain limitations when retrieving historical data. However, within the currently covered block range, the detector has performed excellently in real-time detection and attack identification.
[0076] When conducting an in-depth analysis of sandwich attacks on Ethereum execution clients, it can be seen that although such arbitrage strategies utilize the asymmetry of transaction information, the actual execution process is not simple. Considering the performance of the current dataset, if these data are directly compared with research results, it is often difficult to reflect the dynamic competitive environment of the real market; although the simulation environment can provide experimental support to a certain extent, due to its inability to cover the multiple complexities in the real network, it still cannot fully reproduce the actual transaction situation in the Ethereum network.
[0077] For the above reasons, the present invention particularly focuses on real-time detection efficiency and accuracy, and verifies the actual performance of the detector using existing block data. In terms of historical block detection, a total of 210,000 blocks (from block 21.3 million to block 21.51 million) were analyzed in the study. This process took approximately 47 hours, with an average processing time of 0.81 seconds per block, and finally 60,946 sandwich attack events were successfully identified. Figure 5 Shows the overall change trend of CPU usage during the monitored blocks (from 21,300,000 to 21,510,000).
[0078] To further evaluate the accuracy of the detector in historical blocks, the research compared the block detection results synchronized on December 30, 2025 with the historical data provided by an authoritative online detection website (https: / / eigenphi.io / mev / ethereum / ). A total of 7,159 blocks were synchronized on that day. As shown in Table 1, the platform marked 2,672 sandwich attacks, and the detector of the present invention successfully identified 2,569 of them, with an accuracy rate of 96.14%. To further improve the accuracy of the evaluation, the present invention expanded the scope of the detection samples, counted 60,946 sandwich attack events that occurred during the period from November 30 to December 30, 2024, and compared them with 63,370 attack data provided by the online platform during the same period. Finally, the accuracy rate of the detector was further increased to 96.17%.
[0079] Table 1. Sandwich Attack Detection Results of the Detector and Eigenphi
[0080]
[0081] From Figure 6 It can be seen that the overall trend of the detector and the feature function designed in the present invention is similar in terms of the number of sandwich attacks identified. At the start and end of the date range, the number of blocks is relatively small because data collection did not start at the hour, resulting in lower detection values. Generally speaking, the detector successfully identified approximately 96.17% of the attack events, demonstrating its high capture ability for most potential sandwich attacks. This result not only proves the effectiveness of the detector but also further verifies its feasibility and stability in practical applications. Specifically, the detector can continuously and stably detect most sandwich attacks at different time periods, which provides strong support for applying this detection system to other EVM-compatible blockchain platforms.
[0082] Figure 7 Shows the change in CPU real-time usage when the detector is enabled and disabled at random 60-second intervals. It can be observed that whenever a new block is generated, the CPU usage rate increases significantly. Since a new block is generated every 13 seconds on average, this indicates that our detection system has been highly optimized.
[0083] Figure 8Shows a specific example of the recorded sandwich attack. In the multi-token sandwich attack, the presence of additional token pairs in a transaction may be due to the victim setting a slippage tolerance. The slippage tolerance is the price fluctuation range that the victim allows to ensure the success of the transaction. If the victim sets a high slippage tolerance, the transaction may involve some additional token pair addresses, which may not be directly manipulated by the attacker but are generated by the victim to ensure the smooth completion of the transaction. Thus, the additional token pair addresses in the transaction may reflect the victim's trading strategy rather than the attacker's intervention.
[0084] In further analysis, we screened 200 sandwich attacks and compared the time difference between the block time when the sandwich attack occurred and the time when the sandwich attack was detected. As Figure 9 shown, there were 9 records with a time difference of 1 second, accounting for 4.5%; 132 records with a time difference of 2 seconds, accounting for 66%; 42 records with a time difference of 3 seconds, accounting for 21%; and 17 records with a time difference of 4 seconds, accounting for 8.5%. Considering the processing time difference of each historical block, the average processing time was approximately 0.81 seconds, and this difference mostly originated from the time required to obtain the block through peer-to-peer communication. This result proves that the detection system can quickly provide detection results within a short time after the block is generated and demonstrates its ability to respond quickly.
[0085] The sandwich attack detector proposed in the present invention effectively expands its detection ability in the multi-token trading environment through algorithm upgrade, and can efficiently identify and prevent multi-token sandwich attacks without increasing the burden on nodes. This achievement provides a practical solution for the security protection of Ethereum and other EVM-compatible blockchain platforms, promoting the further development of blockchain technology in terms of security. This research verifies that our detection system is a feasible solution to address the security challenge of sandwich attacks.
Claims
1. A method for detecting multi-token sandwich attacks in the Ethereum network, characterized in that, The method includes: S1. Register and initialize a sandwich attack detector during the client startup process, continuously monitor newly generated block headers and transaction data, and capture node data; S2. Parse the captured transactions. By detecting whether there is a Swap event of the Uniswap V2 or V3 router in the event log, and the consecutive occurrence of at least two Transfer events and one Swap event, determine whether the transaction has completed a valid token exchange; If it is confirmed that the transaction has completed a valid token exchange, return the key information including the hash of the transaction, the sender address, the recipient address, the Gas fee, and the token pair contract address, providing a basis for sandwich attack determination; S3. Traverse from the first transaction in the block transaction sequence, and identify the preceding transaction Ta1, the victim transaction Tv, and the subsequent transaction Ta2 based on the following steps: a) Take the current transaction as the candidate preceding transaction Ta1; b) If Ta1 completes a valid token exchange, search backward up to 12 transactions from the index where the preceding transaction Ta1 is located to find a candidate subsequent transaction Ta2 that has the same token pair contract address as the preceding transaction Ta1, the same sender address, and a different transaction hash; c) If a transaction that appears between the preceding transaction Ta1 and the subsequent transaction Ta2 has the same token pair contract address as the preceding transaction Ta1, and its sender and recipient addresses are both different from the sender address of the preceding transaction Ta1, then determine this transaction as the victim transaction Tv; d) When there is at least one victim transaction Tv, a sandwich attack sequence is formed; if the number of victim transactions is greater than 1, it is regarded as a multi-token sandwich attack.
2. A detection system for multi-token sandwich attacks in the Ethereum network, characterized in that Execute the Ethereum sandwich attack detection method as described in claim 1, including a node data capture module, a transaction parsing module, and a sandwich attack determination module; It further includes: An alarm and logging module, used to output structured logs and send alarm messages after detecting a sandwich attack sequence, and record information including the block number, hash value, sender address, recipient address, and token pair contract address; By directly invoking the sandwich attack determination module within the Ethereum client, the system can perform real-time detection on all transactions after a new block is generated, and identify multiple victim transactions in a multi-token scenario, including identifying single-token sandwich attacks and multi-token sandwich attacks.
3. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, wherein, The node data capture module subscribes to new block header information based on the subscription interface provided by the client Geth. When detecting the arrival of a new block header, it timely obtains all transactions and event logs in the block and transfers the raw data to the transaction parsing module.
4. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, wherein, The transaction parsing module sequentially parses the event logs of each transaction, identifies the log entries arranged in the order of Transfer, Transfer, Swap in the transaction logs, and if the corresponding contract address is the Uniswap V2 or V3 routing contract, further extracts the called method names, including swapExactTokensForTokens, swapTokensForExactTokens, exactInputSingle, to determine whether a valid token swap is completed.
5. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, wherein When the sandwich attack determination module identifies the pre - transaction Ta1 and the post - transaction Ta2, it also restricts the difference in their index positions within the block to ensure that the number of transactions between the pre - transaction Ta1 and the post - transaction Ta2 does not exceed the preset threshold n, where the default value of n is 12, to ensure that these three transactions are close enough in chronological order and spatial position. This value is the optimal threshold determined based on the statistical analysis of historical sandwich attack transaction data.
6. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, wherein If multiple victim transactions Tv1, Tv2, Tv3,... are detected between the pre - transaction Ta1 and the post - transaction Ta2, and they all satisfy that neither the sender nor the receiver is the same as the pre - transaction Ta1 and the token pair addresses involved are the same as those of the pre - transaction Ta1, it is determined as a multi - victim transaction in the multi - token sandwich attack scenario.
7. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, characterized in that, The creation and service registration of the detector instance are implemented in the Ethereum client startup process, specifically including: After creating a full node during the startup process of the Ethereum client, the sandwich attack detector is embedded inside the client in the form of a system service, and the application programming interface of the detector is registered to the client by calling the custom API registration method; the custom API defines the namespace, version, service instance, and visibility parameters of the API, and maps the detection methods in the Ethereum client interaction console. The custom detection methods include detect.currentBlockSandwich, detect.newBlockSandwich, and detect.stop. By only registering the core detection functions and necessary shutdown functions, this method effectively reduces the memory and computing resource overhead and avoids negatively affecting the running efficiency of the full node.
8. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 7, characterized in that The working process of this system is as follows: (1) When the Geth client starts, initialize the sandwich attack detector instance and embed it into the client through the system API registration unit; (2) Subscribe to the new block header or a specified historical block to obtain all transaction data and event logs of the target block; (3) Call the multi - token sandwich attack determination module and perform the following steps for the transaction sequence in the target block: a) Take the first transaction in the block transaction sequence as the candidate pre - transaction Ta1 and call the transaction parsing module to obtain the data of Ta1; b) If Ta1 completes a valid token swap, search for the post - transaction Ta2 among the at most n transactions after the pre - transaction Ta1, which needs to satisfy the same token pair address, the same sender, and different hash values; c) Group all victim transactions Tv that are located between the pre - transaction Ta1 and the post - transaction Ta2 and meet the victim transaction characteristics into the same sandwich attack unit; (4) If an attack chain composed of the pre - transaction Ta1, the victim transaction Tv, and the post - transaction Ta2 is detected, the alarm and logging module is called in real - time for structured storage and alarm; (5) Repeat the above steps until the detection is completed or the service is stopped by calling detect.stop.
9. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, characterized in that, The system includes two operating modes as follows: Detect the latest block mode: Automatically execute the detection algorithm by subscribing to the new block header information and after each new block is generated; Detect historical block mode: Receive the target block range and check whether the input is legal, and then execute the detection one by one for the specified block range.
10. The detection system for multi-token sandwich attacks in the Ethereum network according to claim 2, characterized in that, The alarm and logging module can write the log information into a specified log file for the operation and maintenance personnel to view.
Citation Information
Cited By
Real-time quantitative risk transaction method and device, computer equipment and storage medium
CN121352804A