Smart contract reentry vulnerability detection and repair method and related device
By extracting the structure information of smart contracts and function call relationships, combining large language models to generate malicious attack contracts and conducting tests and verifications, the problem that existing tools cannot accurately identify complex reentry vulnerabilities is solved, efficient vulnerability detection and repair is achieved, and the security of smart contracts is improved.
Patent Information
- Application Number
- CN202510348652.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-24
- Publication Date
- 2025-07-11
AI Technical Summary
The existing smart contract reentry vulnerability detection tools cannot accurately identify complex attack patterns, resulting in the vulnerability still hidden in Ethereum smart contracts. The existing large language model performs poorly in vulnerability detection and repair, and the generated code is insufficient readability and security.
By extracting the structural information and function call relationship of the smart contract, generating a reentry vulnerability detection report, combining the large language model to generate a malicious attack contract, verifying the vulnerability in the test environment, and performing adaptive code repairs, using static analysis and large language model to improve the accuracy of detection and repair.
It improves the accuracy and efficiency of smart contract reentry vulnerability detection, reduces the dependence on traditional static analysis tools and professional knowledge, and ensures the security of smart contracts and the stability of blockchain applications.
Smart Images

Figure CN120296741A_ABST
Abstract
Description
Technical Field
[0001] This application belongs to a vulnerability detection and repair method, and specifically relates to a method for detecting and repairing reentrancy vulnerabilities in smart contracts and related devices. Background Art
[0002] A blockchain is a public database updated and shared by many computers in a network. A smart contract is a reusable and executable program uploaded and running on the blockchain, that is, a decentralized application (DAPP). Users can submit transaction requests and send a sufficient amount of Ether (ETH) to call the smart contract to execute code snippets without rewriting the code.
[0003] As the value of Ethereum continues to rise, more and more attackers target smart contract vulnerabilities to obtain unfair profits, which can cause significant losses at any time. Therefore, the security issues of smart contracts, especially reentrancy vulnerabilities, have become a concern. In addition, the immutability of blockchain data means that once a smart contract is deployed on the blockchain, it cannot be changed. Therefore, it is very important to conduct a thorough security check before deploying the smart contract. Currently, although a large number of researchers have designed some tools to avoid reentrancy attacks, these tools cannot accurately identify complex attack patterns or require expert-level knowledge to interpret the analysis results, resulting in reentrancy vulnerabilities still lurking in Ethereum smart contracts. Summary of the Invention
[0004] In view of the technical problem that the existing tools for avoiding reentrancy attacks cannot accurately identify complex attack patterns, resulting in reentrancy vulnerabilities still lurking in Ethereum smart contracts, this application provides a method for detecting and repairing reentrancy vulnerabilities in smart contracts and related devices.
[0005] To achieve the above object, this application adopts the following technical solutions: In a first aspect, this application proposes a method for detecting and repairing reentrancy vulnerabilities in smart contracts, including: Extracting the structural information and function call relationships of the smart contract, analyzing potential reentrancy vulnerabilities, and generating a reentrancy vulnerability detection report; Performing type checking according to the results of the reentrancy vulnerability detection report, determining all functions that may have reentrancy vulnerabilities, and determining potential attack paths for each function that may have reentrancy vulnerabilities; Performing instruction-level engineering structuring on the reentrancy vulnerability detection report and potential attack paths to obtain prompts for generating malicious attack contracts that can be understood and learned by large language models; Input the malicious attack contract generation prompt into the large language model, bypass the security warning of the large language model, and generate a malicious attack contract that can attack the victim contract; Deploy the victim contract and the malicious attack contract in the test environment, simulate the trigger conditions for the reentrancy vulnerability, and verify the reentrancy vulnerability through the interaction test between the victim contract and the malicious attack contract; Judge whether the malicious attack contract has a reentrancy vulnerability according to the verification result; According to the attack path, use the large language model to adaptively repair the code of the victim contract with a reentrancy vulnerability to obtain a repaired contract; Verify the reentrancy vulnerability again through the interaction test between the repaired contract and the malicious attack contract, and judge whether the repaired contract has a reentrancy vulnerability according to the result of the re-verification.
[0006] In a second aspect, the present application proposes a detection and repair system for smart contract reentrancy vulnerabilities, including: A report generation module, which is used to extract the structure information and function call relationships of the smart contract, analyze potential reentrancy vulnerabilities, and generate a reentrancy vulnerability detection report; A path module, which is used to perform type checking according to the result of the reentrancy vulnerability detection report, determine all functions that may have reentrancy vulnerabilities, and determine potential attack paths according to each function that may have reentrancy vulnerabilities; A prompt module, which is used to perform instruction-level engineering structuring on the reentrancy vulnerability detection report and potential attack paths to obtain a malicious attack contract generation prompt that the large language model can understand and learn; A malicious attack contract module, which is used to input the malicious attack contract generation prompt into the large language model, bypass the security warning of the large language model, and generate a malicious attack contract that can attack the victim contract; A test module, which is used to deploy the victim contract and the malicious attack contract in the test environment, simulate the trigger conditions for the reentrancy vulnerability, and verify the reentrancy vulnerability through the interaction test between the victim contract and the malicious attack contract; A judgment module, which is used to judge whether the malicious attack contract has a reentrancy vulnerability according to the verification result; A repair module, which is used to adaptively repair the code of the victim contract with a reentrancy vulnerability by using the large language model according to the attack path to obtain a repaired contract; A repair judgment module, which is used to verify the reentrancy vulnerability again through the interaction test between the repaired contract and the malicious attack contract, and judge whether the repaired contract has a reentrancy vulnerability according to the result of the re-verification.
[0007] In a third aspect, the present application provides an electronic device, including: a memory and one or more processors; the memory is coupled to the processor; wherein, computer program code is stored in the memory, and the computer program code includes computer instructions. When the computer instructions are executed by the processor, the electronic device executes the steps of the method for detecting and repairing the reentrancy vulnerability of the smart contract described above.
[0008] In a fourth aspect, the present application provides a computer-readable storage medium, in which a computer program is stored. When the computer program is executed by a processor, the steps of the method for detecting and repairing the reentrancy vulnerability of the smart contract described above are implemented.
[0009] Compared with the prior art, the present application has the following beneficial effects: The present application provides a method for detecting and repairing the reentrancy vulnerability of a smart contract, which extracts the structural information and function call relationships of the smart contract, analyzes potential reentrancy vulnerabilities, generates a reentrancy vulnerability detection report, performs type checking according to the results of the reentrancy vulnerability detection report to determine all functions that may have reentrancy vulnerabilities, then determines potential attack paths, and then generates a malicious attack contract with the help of a large language model. The victim contract and the malicious attack contract are deployed in a test environment, and the reentrancy vulnerability is verified through the interaction test of the victim contract and the malicious attack contract. According to the verification results, it is judged whether the malicious attack contract has a reentrancy vulnerability. In addition, the vulnerable code of the victim contract with a reentrancy vulnerability is repaired, and the repair is verified in the same test environment to prevent the reentrancy vulnerability from occurring again. The present application uses a static analysis tool and a large language model to cooperate to detect the reentrancy vulnerability of the smart contract and implement vulnerability repair. This cooperative method not only improves the accuracy and efficiency of detecting the reentrancy vulnerability of the smart contract, but also reduces the dependence on traditional static analysis tools and professional knowledge, providing important support for strengthening the security of smart contracts and improving the overall performance of blockchain applications. Among them, the existing types of reentrancy vulnerabilities are classified and described in detail, and the existence of the vulnerability is intuitively and effectively verified by deploying and executing the malicious attack contract and the victim contract in a virtual environment, and a repair contract is efficiently generated to complete the vulnerability repair.
[0010] The present application also provides a system for detecting and repairing the reentrancy vulnerability of a smart contract, an electronic device, and a computer storage medium, which have all the advantages of the method for detecting and repairing the reentrancy vulnerability of the smart contract described above. BRIEF DESCRIPTION OF THE DRAWINGS
[0011] To more clearly illustrate the technical solutions of the embodiments of the present application, the accompanying drawings required for the embodiments will be briefly introduced below. It should be understood that the following drawings only show some embodiments of the present application and should not be regarded as limiting the scope. For those of ordinary skill in the art, without creative efforts, other related drawings can also be obtained based on these drawings.
[0012] Figure 1 It is the first flowchart of the method for detecting and repairing the reentrancy vulnerability of the smart contract of the present application; Figure 2 It is the second flowchart of the method for detecting and repairing the reentrancy vulnerability of the smart contract of the present application; Figure 3 It is the schematic diagram of the reentry attack path in the embodiments of the present application; Figure 4 It is the schematic diagram of the reentrancy vulnerability type in the embodiments of the present application; Figure 5 It is a schematic diagram of the system for detecting and repairing the reentrancy vulnerability of the smart contract in the embodiments of the present application. Detailed implementation manners
[0013] To make the objectives, technical solutions, and advantages of the embodiments of the present application clearer, the technical solutions in the embodiments of the present application will be clearly and completely described below in conjunction with the accompanying drawings in the embodiments of the present application. Obviously, the described embodiments are some, rather than all, of the embodiments of the present application. Usually, the components of the embodiments of the present application described and shown in the accompanying drawings here can be arranged and designed in various different configurations.
[0014] Therefore, the following detailed description of the embodiments of the present application provided in the drawings is not intended to limit the scope of the present application claimed, but merely represents the selected embodiments of the present application. Based on the embodiments in the present application, all other embodiments obtained by those of ordinary skill in the art without creative efforts belong to the scope of protection of the present application.
[0015] It should be noted that similar reference numerals and letters denote similar items in the following drawings. Therefore, once an item is defined in one drawing, it does not need to be further defined and explained in subsequent drawings.
[0016] In the description of the embodiments of the present application, it should be noted that if terms such as "upper", "lower", "horizontal", "inner", etc. are used to indicate the orientation or positional relationship, it is based on the orientation or positional relationship shown in the drawings, or the orientation or positional relationship in which the invention product is usually placed during use. This is only for the convenience of describing the present application and simplifying the description, rather than indicating or implying that the device or element referred to must have a specific orientation, be constructed and operated in a specific orientation. Therefore, it should not be construed as a limitation to the present application. In addition, terms such as "first", "second", etc. are only used for distinguishing descriptions and cannot be construed as indicating or implying relative importance.
[0017] In addition, if the term "horizontal" appears, it does not mean that the component is required to be absolutely horizontal, but it can be slightly inclined. For example, "horizontal" only means that its direction is more horizontal relative to "vertical", and does not mean that the structure must be completely horizontal, but it can be slightly inclined.
[0018] In the description of the embodiments of the present application, it should also be noted that unless otherwise clearly specified and limited, if terms such as "set", "installed", "connected", "linked" are used, they should be understood in a broad sense. For example, it can be a fixed connection, a detachable connection, or an integral connection; it can be a mechanical connection or an electrical connection; it can be directly connected or indirectly connected through an intermediate medium, and it can be the communication inside two elements. For those of ordinary skill in the art, the specific meanings of the above terms in the present application can be understood according to specific situations.
[0019] Blockchain technology constructs a real-time synchronized public ledger system through a distributed node network. As the core component of this system, smart contracts are automated programmable protocols deployed on the blockchain in the form of code, and their essence is a decentralized application with autonomous execution capabilities. Users can trigger the preset contract logic by paying Ether, without the need to repeatedly develop basic functional modules. With the continuous increase in the ecological value of Ethereum, malicious attacks against smart contract vulnerabilities have shown a high incidence. Among them, the reentrancy vulnerability has become a key defense object in the blockchain security field due to its strong concealment and great destructiveness. Attackers can carry out illegal recursive calls by manipulating the contract execution order, and can achieve malicious operations such as fund theft in a single transaction.
[0020] The immutable characteristic of the blockchain makes it impossible to correct the code of the deployed smart contract, requiring developers to complete strict security audits before the contract is uploaded to the chain. Although various reentrancy vulnerability detection tools have been developed in the current security field, there are generally two limitations in the existing solutions: one is the insufficient recognition accuracy for complex attack patterns such as multi-path calls and cross-contract interactions; the other is that the analysis results rely on the interpretation of professional security personnel, resulting in some high-risk vulnerabilities still being able to bypass the detection mechanism and lurk in the Ethereum ecosystem. Therefore, building an intelligent and all-dimensional security protection system is an urgent need for technological development.
[0021] In the field of security detection and repair of smart contracts, existing static analysis tools such as Slither, Oyente, and Maian, although they have played a certain role in detecting re-entrancy vulnerabilities, still have obvious limitations. These tools may not be able to comprehensively and accurately identify all re-entrancy vulnerabilities, and there is a risk of false negatives or false positives. This means that although these tools can provide certain references, developers still need to treat their analysis results with caution and avoid complete reliance.
[0022] To address re-entrancy vulnerabilities in smart contracts, developers need to be extra careful when designing and implementing external calls. These calls must be carefully designed and it is ensured that the contract state is always checked and updated. For example, auditing before fulfilling a request to send funds to reduce the Ethereum balance, although this increases the complexity of the operation, can improve the credibility of the transaction. However, both vulnerability detection and repair bring more manual workload, requiring developers to invest more time and effort.
[0023] In addition, the recently popular large language model ChatGPT has not performed well in the detection and repair of smart contract vulnerabilities. Experimental studies have shown that ChatGPT has deficiencies in accurately locating smart contract vulnerabilities and output randomness. The code it generates is usually less readable and understandable than manually written code, especially when using non-intuitive variable names and complex and diverse function parameters. More worryingly, the code generated by ChatGPT may contain unnecessary or incorrect content, which further increases the security risk of smart contracts.
[0024] In summary, the security detection and repair of smart contracts is a complex and arduous task that requires the joint efforts of developers, tool developers, and researchers. Developers should treat the analysis results of existing tools with caution and adopt a more meticulous and cautious development process to ensure the security of smart contracts. At the same time, tool developers should also continuously improve and optimize existing tools to improve the accuracy and reliability of detection and repair.
[0025] Based on the above situation, this application proposes a method and related device for detecting and repairing re-entrancy vulnerabilities in smart contracts. The following will describe this application in detail with reference to embodiments and drawings.
[0026] As Figure 1 shown, the following is the first process schematic diagram of the method for detecting and repairing re-entrancy vulnerabilities in smart contracts of this application, which may include: S101, extract the structural information and function call relationships of the smart contract, analyze potential re-entrancy vulnerabilities, and generate a re-entrancy vulnerability detection report.
[0027] By statically analyzing the source code of a smart contract, its structural information can be extracted, which typically includes state variables, functions, and events in the smart contract. This information is the basis for understanding the behavior and potential vulnerabilities of the smart contract. Analyzing the call relationships between functions in the contract, including direct and indirect calls, helps identify possible reentry points, that is, those functions that may be interrupted by external calls and reentered during execution. Based on the function call relationships and combined with the security rules and best practices of smart contracts, analyze which functions or combinations of functions may have reentry vulnerabilities. For example, check whether there are state variables that are not properly managed, which may lead to inconsistencies or security vulnerabilities when the function is reentered. Finally, organize the analysis results into a reentry vulnerability detection report, detailing all potential reentry vulnerabilities, including the vulnerability location, type, possible impacts, etc.
[0028] S102. Perform type checking based on the results of the reentry vulnerability detection report to determine all functions that may have reentry vulnerabilities. For each function that may have a reentry vulnerability, determine the potential attack paths.
[0029] Conduct further type checking on the potential reentry vulnerabilities listed in the reentry vulnerability detection report to confirm their nature and severity. Based on the results of the type checking, it can be clarified which functions actually have reentry vulnerabilities. These functions are usually those that do not properly consider the possibility of reentry when dealing with state variables or performing critical operations. For each function with a reentry vulnerability, analyze the possible attack paths, such as identifying how an attacker can exploit the vulnerability to trigger reentry and the harmful operations that may be executed after reentry. Determining the attack paths helps generate effective malicious attack contracts later.
[0030] S103. Perform instruction-level engineering structuring on the reentry vulnerability detection report and the potential attack paths to obtain prompts for generating malicious attack contracts that can be understood and learned by large language models.
[0031] Performing instruction-level engineering structuring is to decompose complex contract logic and attack paths into a series of clear instructions or steps. Then, based on the results of the structuring, generate prompts for guiding the large language model to generate malicious attack contracts. These prompts can include sufficient information so that the large language model can generate contract code with specific attack behaviors.
[0032] S104. Input the prompts for generating malicious attack contracts into the large language model, bypass the security warnings of the large language model, and generate malicious attack contracts that can attack the victim contract.
[0033] Large language models are advanced AI models capable of understanding and generating natural language (including code). Since large language models usually have built-in security warning mechanisms to prevent the generation of malicious or harmful content, corresponding methods can be adopted to bypass these warnings. After successfully bypassing the security warnings, the large language model will generate a malicious attack contract that can attack the victim contract according to the prompts. This malicious attack contract that can attack the victim contract can include all necessary logic and instructions to execute the previously determined attack path.
[0034] S105, Deploy the victim contract and the malicious attack contract in a test environment, simulate the trigger conditions for the reentrancy vulnerability, and verify the reentrancy vulnerability through the interaction test between the victim contract and the malicious attack contract.
[0035] By constructing a specific transaction or call sequence, the trigger conditions for the reentrancy vulnerability can be simulated, which may include sending specific transactions at specific time points or triggering specific contract events. Let the victim contract and the malicious attack contract interact, observe and record their behaviors, and especially pay attention to whether the malicious attack contract can successfully exploit the reentrancy vulnerability and whether the victim contract exhibits the expected security vulnerability.
[0036] S106, Judge whether the malicious attack contract has a reentrancy vulnerability according to the verification result.
[0037] Analyze the results of the interaction test, including transaction records, contract state changes, event logs, etc. These information will provide direct evidence on whether the malicious attack contract has successfully exploited the reentrancy vulnerability. Based on the analysis of the test results, it can be judged whether the malicious attack contract has a reentrancy vulnerability. If the malicious attack contract can successfully execute the attack path and cause security problems in the victim contract, the existence of the reentrancy vulnerability can be confirmed, and appropriate follow-up actions can be taken according to the judgment result. If the existence of the reentrancy vulnerability is confirmed, the vulnerability should be repaired immediately and retested. If no vulnerability is found or the vulnerability has been repaired, other aspects of the contract security audit and testing can be continued.
[0038] S107, Based on the attack path, use a large language model to perform code adaptive repair on the victim contract with a reentrancy vulnerability to obtain a repaired contract.
[0039] Perform instruction - level engineering structuring on the successful attack paths to obtain code repair hints that the large - language model can understand and learn, and input the code repair hints to generate a repair contract. The confirmed attack paths can be reversely decomposed into the root causes of vulnerabilities and repair logics to generate structured repair instructions, guiding the large - language model (LLM) to generate repair contract code. In practical applications, if the attack modifies the state after an external call, the repair strategy is "update the state first and then execute the external call"; if cross - contract re - entry is involved, the repair strategy is "add a re - entry lock (such as ReentrancyGuard in OpenZeppelin)".
[0040] S108, Re - verify the re - entry vulnerability through the interaction test between the repair contract and the malicious attack contract, and judge whether the repair contract has a re - entry vulnerability according to the re - verification result.
[0041] Deploy the repair contract and the malicious attack contract in the test environment, continue to simulate the trigger conditions of the re - entry vulnerability, and verify the repair result through the interaction test between the repair contract and the malicious attack contract. By reproducing the attack path, verify whether the repair contract blocks the exploitation of the vulnerability. Deploy the repair contract (new version) and the un - repaired malicious attack contract (keeping the attack logic unchanged), using the same account and initial state (such as account balance, contract permissions). Through test data analysis, the key verification point is that the attack contract cannot steal extra funds through re - entry, confirm whether the repair contract effectively repairs the vulnerability, and evaluate the robustness of the repair. If the repair fails, the newly discovered attack path can be fed back to step S107 to generate optimized repair hints and start multiple rounds of repair - verification loops.
[0042] This application proposes a set of feasible detection and repair solutions. By deploying the victim contract and the malicious attack contract to implement the re - entry attack process, the re - entry vulnerability can be directly and reliably verified.
[0043] As Figure 2 shown, it is the second process schematic diagram of the detection and repair method for the re - entry vulnerability of the smart contract in this application, which may include: S201, Use static analysis techniques to deeply analyze the smart contract source code to identify potential re - entry vulnerability points and generate a detailed re - entry vulnerability detection report.
[0044] It should be noted that this application does not directly use the output results of static analysis tools, but requires them to be formatted in a form that the large - language model can understand and process. Therefore, it is necessary to extract the key vulnerability statements and their corresponding descriptions from the source code. Specifically, the following methods can be adopted: (1) The re - entry vulnerability detection report includes vulnerability detection, naming convention detection, etc., and can clearly point out the contract name, function name, and state variables with potential risks that may have vulnerabilities.
[0045] Among them, vulnerability detection is used to detect the name of the smart contract, the name of the function, and the variable names that may be tampered with. Naming convention detection is used to detect functions, parameters, and variable names that do not conform to the smart contract specifications.
[0046] (2)Refine the key information in the reentrancy vulnerability detection report to adapt to the detection requirements of reentrancy vulnerabilities and the processing requirements of large language models.
[0047] In practical applications, the key information usually includes the contract name, function name, state variable name, corresponding line numbers, and relevant external call information. The reentrancy vulnerability information usually includes the contract name and function name that may be reentered by a reentrancy attack, the variable names that may be tampered with, and external calls.
[0048] S202. Perform type checking on the results of the reentrancy vulnerability detection report, determine the functions that may have reentrancy vulnerabilities, and identify the attack paths.
[0049] The key to the large model generating a malicious attack contract is to select a specific type of reentrancy vulnerability. This step is crucial for generating targeted attack scenarios and test cases in a targeted manner, thus ensuring the effectiveness and relevance of the generation process. It can be specifically achieved through the following steps: S2-1, as Figure 3 shown, is a schematic diagram of the reentrancy attack path. This kind of attack usually occurs when a smart contract calls the function of another contract, and the called contract re-calls the function of the original contract before completing its execution, which may cause some states of the original contract to be unexpectedly changed.
[0050] Each path has functions for determining the start (A / B / C) and end conditions (1 / 2 / 3) of the attack, as well as specific instructions and corresponding parameters for guiding the behavior of the malicious attack contract during the interaction. Select the corresponding generated contract according to the type of reentrancy vulnerability, match it with the corresponding generated contract, and send it to the large language model.
[0051] The basic paths of the reentrancy attack include: (1)Preparation stage: The attacker deploys a malicious attack contract that has the ability to re-call the functions of the victim contract. The attacker needs to send a certain amount of funds to the victim contract to pave the way for subsequent attacks.
[0052] (2)Trigger stage: The attacker triggers a certain function of the victim contract in some way. During the execution of this function, it will interact with the attacker's malicious attack contract in some form (such as transferring funds, making calls, etc.).
[0053] (3)Reentrancy stage: ① During the interaction between the victim contract and the attacker contract (such as transferring funds through methods like call, send, or transfer), the attacker contract uses callback functions (such as fallback or receive functions) to re-enter the victim contract, or calls the victim contract through the Hook mechanism (such as functions like ERC721, ERC777, ERC223, etc.).
[0054] ② Re-enter the same function Function1 or other functions Function2 in the victim contract, or enter a certain function Function3 in another victim contract. Since some states of the victim contract (such as the balance) have not been updated before the end of the first call, the attacker can take advantage of this to repeatedly (Callback) withdraw funds or perform other malicious operations.
[0055] (4)Completion stage: By repeatedly executing the steps in the re-entry stage, the attacker may extract all the funds in the victim contract or achieve other malicious purposes. After the attack is successful, the attacker can terminate the attack and withdraw the funds in the malicious attack contract.
[0056] S2-2, classify the re-entry vulnerability types into three categories: fallback type re-entry, Hook mechanism re-entry, and user-defined re-entry according to the basic path of the re-entry attack. As Figure 4 shown, it is a schematic diagram of the re-entry vulnerability type.
[0057] (A)Fallback type re-entry: Call the victim contract in the fallback of the malicious attack contract, triggered by the victim contract sending Ether to the malicious attack contract to achieve re-entry.
[0058] (B)Hook mechanism re-entry: The victim contract throws a Hook, and the malicious attack contract implements the function corresponding to the hook, and calls the victim contract within the function body to achieve re-entry.
[0059] (C)User-defined re-entry: When the victim contract calls this user-defined external function and does not update its internal state before completing all calls, the malicious attack contract re-enters the victim contract and calls its method again to achieve re-entry.
[0060] Then, according to whether the re-entry function changes, it is divided into three types: the most basic re-entry, cross-function re-entry, and cross-contract re-entry.
[0061] (1)Basic-reentrancy: The victim contract triggers the fallback function in the malicious attack contract, enabling the malicious attack contract to re-enter the same function in the victim contract.
[0062] (2)Cross-function-reentrancy: The victim contract triggers the fallback function in the malicious attack contract, causing the malicious attack contract to re-enter different functions of the victim contract.
[0063] (3)Cross-contract-reentrancy: The victim contract triggers the fallback function in the malicious attack contract, causing the malicious attack contract to re-enter other contracts different from the victim contract.
[0064] S2-3, Based on the existing types of reentrancy vulnerabilities, construct path trees to parse different types of attack scenarios into specific attack paths respectively, and then abstract and merge these types into three general path prompts (TP), as Figure 4 shown in the dotted box.
[0065] When selecting the corresponding attack path according to the type of reentrancy vulnerability, determine which type of malicious attack contract to choose for testing based on the analyzed possible reentrancy types and attack paths; then match the smart contract code with different types of attack contracts, and automatically select the most suitable attack contract according to the characteristics of the contract and the existing vulnerabilities; then provide options for functions and partial parameter configurations for the selected malicious attack contract path, retaining the ability of the large model to customize the attack logic to better simulate the specific strategies that the attacker may adopt; finally, feedback the test results for improving and adjusting the accuracy of vulnerability detection and providing detailed repair suggestions for contract developers.
[0066] S203, According to the detected reentrancy vulnerability, select a suitable generation path to provide a clear direction for the large language model. Combine the output of the static analysis stage with the selected path to form a Prompt that is easy for the large language model to understand, further guiding the model to generate a highly targeted malicious attack contract.
[0067] Specifically, it can be achieved through the following methods: (1)Through an interactive dialogue with the large language model, based on the designed Prompt, initially attempt to generate a malicious attack contract. In this process, the large language model will generate the corresponding malicious attack contract code according to the extracted reentrancy vulnerability detection report and the determined potential attack paths.
[0068] (2)If the malicious attack contract initially generated cannot be successfully compiled, re-integrate the feedback information of the compilation failure into the Prompt and perform multiple rounds of iterative optimization until a compilable malicious attack contract is generated, realizing a malicious attack contract generation mechanism with feedback.
[0069] The interactive dialogue process of the large language model can be designed. Through the structured information of preset Prompts and Answers, the large language model is guided to complete specific tasks, such as analyzing vulnerabilities, elaborating attack steps, and generating malicious attack contract codes. With the help of the large language model, the vulnerability detection report and the malicious attack contract template are integrated at the instruction level to generate detailed attack steps and malicious codes. Then, using the code understanding and generation capabilities of the generative large language model, based on the integrated prompts and templates, the security mechanism is bypassed to generate malicious attack codes.
[0070] S204, relying on the large language model, strategically design a small number of prompts according to the provided input to promote the interactive dialogue, ensure that the model comprehensively understands the context and purpose of the reentry vulnerability detection task, and achieve the generation of malicious smart contract codes.
[0071] In practical applications, the main components of the Prompt include: Role, endowing the large language model with corresponding capabilities, enabling it to simulate the role of an attacker, understand and execute the reentry attack.
[0072] Information, including the source code of the smart contract that may have vulnerabilities and a detailed vulnerability description, providing sufficient context information for the large language model.
[0073] Choice, providing path hints to guide the model to select the most appropriate attack path according to different types of reentry vulnerabilities.
[0074] The answer session of the large language model can include: Capability: The model needs to demonstrate the ability to design malicious behaviors, analyze and generate attack strategies from the perspective of an attacker.
[0075] Analysis: The model should deeply analyze the provided smart contract, identify exploitable vulnerabilities and formulate specific attack steps.
[0076] Result: The model finally outputs a structured malicious attack contract that can effectively perform a reentry attack on the target contract in a test environment.
[0077] S205, deploy the detected victim contract and the generated malicious attack contract on the virtual machine, and by simulating the behavior path of the reentry attack, observe the state variables of the victim contract to effectively verify the attack result.
[0078] (1) Deploy the victim contract and the optimized malicious attack contract in a virtual environment, simulate the reentry attack process, and detect the state variables of the victim contract to verify the effectiveness of the attack.
[0079] (2) If a malicious attack contract can obtain excess Ether outside the legal range, it is determined that the attack is successful and a re-entrancy vulnerability is confirmed; otherwise, the attack is considered a failure and the attack strategy needs to be further optimized.
[0080] Deploy the victim contract and the malicious attack contract on the Remix test chain, send the contract address to the malicious attack contract for attack. Then execute and test the generated malicious attack contract, and verify whether the re-entrancy vulnerability has been successfully triggered, including testing the contract's fund flow, state changes, and the results of re-entrancy behavior. Based on the initial test plan, combined with manual code auditing, test the functions of the smart contract to determine whether there is a real risk of re-entrancy vulnerability.
[0081] This application designs an efficient interactive questioning mode for large language models, and iteratively refines and optimizes the generation of compilable malicious attack contracts. Using automated prompt template filling, context learning, and multi-round repair, an improved Prompt template is designed. This not only avoids the need for a large amount of computing resources in the traditional model training and fine-tuning process, but also significantly improves the success rate of the generated malicious attack contracts, thus greatly improving the efficiency of the overall system.
[0082] This application aims to overcome the limitations of traditional static analysis tools in identifying re-entrancy vulnerabilities. These limitations may expose smart contracts to the risk of being attacked by malicious attack contracts, resulting in huge losses. By working in collaboration with large language models, this application uses the re-entrancy information report obtained from the static analysis module, converts it into a re-entrancy vulnerability description that the large language model can understand, enhances the model's understanding ability by designing effective prompt words, and realizes code repair of smart contracts by introducing an error feedback mechanism, ultimately generating a malicious attack contract that can be compiled and successfully attack the victim contract. In addition, this application develops multiple paths to enable the large language model to generate malicious attack contracts with a higher success rate according to different types of re-entrancy vulnerabilities.
[0083] As Figure 5 shown, it is a schematic diagram of a detection and repair system for smart contract re-entrancy vulnerabilities, which may include: A report generation module, used to extract the structural information and function call relationships of smart contracts, analyze potential re-entrancy vulnerabilities, and generate a re-entrancy vulnerability detection report; A path module, used to perform type checking according to the results of the re-entrancy vulnerability detection report, determine all functions that may have re-entrancy vulnerabilities, and determine potential attack paths according to each function that may have re-entrancy vulnerabilities; A prompt module, used to perform instruction-level engineering structuring on the re-entrancy vulnerability detection report and potential attack paths to obtain malicious attack contract generation prompts that the large language model can understand and learn; The malicious attack contract module is used to input the prompt for generating a malicious attack contract into the large language model, bypass the security warning of the large language model, and generate a malicious attack contract that can attack the victim contract; The testing module is used to deploy the victim contract and the malicious attack contract in a test environment, simulate the trigger conditions of the reentry vulnerability, and verify the reentry vulnerability through the interaction test between the victim contract and the malicious attack contract; The judgment module is used to judge whether the malicious attack contract has a reentry vulnerability according to the verification result; The repair module is used to adaptively repair the code of the victim contract with a reentry vulnerability by using the large language model according to the attack path to obtain a repaired contract; The repair judgment module is used to verify the reentry vulnerability again through the interaction test between the repaired contract and the malicious attack contract, and judge whether the repaired contract has a reentry vulnerability according to the result of the re-verification.
[0084] It should be noted that in the several embodiments provided in this application, it should be understood that the disclosed device and method can be implemented in other ways. For example, the system embodiment described above is only illustrative. For example, the division of each module is only a logical function division. In actual implementation, there may be other division methods. For example, multiple modules can be combined or integrated into another device, or some features can be ignored or not executed. The modules described as separate components may or may not be physically separated. The components shown as modules may be a physical unit or multiple physical units, that is, they can be located in one place, or they can be distributed to multiple different places. Some or all of the modules can be selected according to actual needs to achieve the purpose of the solution of this embodiment.
[0085] In addition, each module in the various embodiments of the present invention can be integrated in a processing unit, or each module can exist physically alone, or two or more modules can be integrated in a unit. The above integrated unit can be implemented in the form of hardware or in the form of a software functional unit.
[0086] This application embodiment also provides an electronic device, which may include one or more processors, a memory, and a communication interface.
[0087] Among them, the memory and the communication interface are coupled to the processor. For example, the memory and the communication interface can be coupled together through a bus.
[0088] Among them, the communication interface is used for data transmission with other devices. A computer program code is stored in the memory. The computer program code includes computer instructions. When the computer instructions are executed by the processor, the electronic device is caused to execute the steps of the method for detecting and repairing the above-mentioned smart contract reentrancy vulnerability.
[0089] Among them, the processor can be a processor or a controller. For example, it can be a Central Processing Unit (CPU), a general-purpose processor, a Digital Signal Processor (DSP), an Application-Specific Integrated Circuit (ASIC), a Field Programmable Gate Array (FPGA) or other programmable logic devices, transistor logic devices, hardware components or any combination thereof. It can implement or execute various exemplary logic blocks, modules and circuits described in conjunction with the present disclosure. The processor can also be a combination that implements computing functions, such as a combination of one or more microprocessors, a combination of a DSP and a microprocessor, and so on. The processor can be used to support the electronic device to execute the method steps provided in the above embodiments.
[0090] Among them, the bus can be a Peripheral Component Interconnect (PCI) bus or an Extended Industry Standard Architecture (EISA) bus, etc. The above bus can be divided into an address bus, a data bus, a control bus, etc.
[0091] A computer-readable storage medium provided by an embodiment of the present application. A computer program is stored in the computer-readable storage medium. When the computer program is executed by the processor, the steps of the method for detecting and repairing the above-mentioned smart contract reentrancy vulnerability are implemented.
[0092] The computer-readable storage medium involved in the present application includes a Random Access Memory (RAM), a memory, a Read-Only Memory (ROM), an Electrically Programmable ROM, an Electrically Erasable Programmable ROM, a register, a hard disk, a removable disk, a CD-ROM, or any other form of storage medium well-known in the technical field.
[0093] The above are only the preferred embodiments of the present application and are not used to limit the present application. For those skilled in the art, the present application can have various changes and modifications. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present application shall be included in the protection scope of the present application.
Claims
1. A method for detecting and fixing reentrancy vulnerabilities in smart contracts, characterized in that Including: Extract the structural information and function call relationships of smart contracts, analyze potential re-entrancy vulnerabilities, and generate a re-entrancy vulnerability detection report; Conduct type checking based on the results of the re-entrancy vulnerability detection report, determine all functions that may have re-entrancy vulnerabilities, and determine potential attack paths for each function that may have re-entrancy vulnerabilities; Perform instruction-level engineering structuring on the re-entrancy vulnerability detection report and potential attack paths to obtain prompts for generating malicious attack contracts that can be understood and learned by large language models; Input the prompts for generating malicious attack contracts into the large language model, bypass the security warnings of the large language model, and generate malicious attack contracts that can attack the victim contract; Deploy the victim contract and the malicious attack contract in a test environment, simulate the trigger conditions for re-entrancy vulnerabilities, and verify the re-entrancy vulnerabilities through the interaction test between the victim contract and the malicious attack contract; Judge whether the malicious attack contract has re-entrancy vulnerabilities according to the verification results; Based on the attack path, use the large language model to adaptively repair the code of the victim contract with re-entrancy vulnerabilities to obtain a repaired contract; Verify the re-entrancy vulnerability again through the interaction test between the repaired contract and the malicious attack contract, and judge whether the repaired contract has re-entrancy vulnerabilities according to the results of the re-verification.
2. The detection and repair method for the re-entrancy vulnerability of the smart contract according to claim 1, characterized in that The potential attack paths include the entry function of the attack, the calling function of the attack, specific instructions for guiding the behavior of the malicious attack contract during the interaction, and corresponding parameters.
3. The method for detecting and repairing re-entrancy vulnerabilities of smart contracts according to claim 2, characterized in that: The entry functions include Fallback re-entrancy, Hook re-entrancy, and custom re-entrancy; The calling functions include Basic-reentrancy, Cross-function-reentrancy, and Cross-contract-reentrancy.
4. The detection and repair method for the reentrancy vulnerability of the smart contract according to claim 1, characterized in that: The method for determining potential attack paths includes: Based on the type of re-entrancy vulnerability, construct a path tree, parse different types of attack schemes into specific attack paths respectively, and then abstractly merge each type of attack path into three general path prompts.
5. The detection and repair method of the smart contract re - entry vulnerability according to claim 1, characterized in that: The method for generating malicious attack contracts that can attack the victim contract includes: Through an interactive dialogue with the large language model, based on a preset Prompt, attempt to generate a malicious attack contract to obtain an initial malicious attack contract; If the initial malicious attack contract can be compiled, it is used as the malicious attack contract finally generated by the large language model. Otherwise, integrate the feedback information of the compilation failure into the preset Prompt, regenerate a new malicious attack contract, and through iterative optimization until a malicious attack contract that can be compiled is finally generated.
6. The detection and repair method for the re-entrancy vulnerability of the smart contract according to claim 1, characterized in that, The method for verifying re-entrancy vulnerabilities through the interaction test between the victim contract and the malicious attack contract, and the method for judging whether the malicious attack contract has re-entrancy vulnerabilities according to the verification results include: Deploy the victim contract and the malicious attack contract on the remix test chain, and send the victim contract address to the malicious attack contract for attack; Execute and test the generated malicious attack contract, and verify whether the re-entrancy vulnerability is triggered, as the initial test scenario; wherein, the test includes testing the contract's fund flow, state changes, and the results of re-entrancy behavior. Based on the initial test scenario, combined with manual code auditing, test the functions of the smart contract to determine whether there is a risk of re-entrancy vulnerability.
7. The method for detecting and fixing the re-entrancy vulnerability of the smart contract according to claim 1, wherein, The method for re-verifying the re-entrancy vulnerability through the interaction test between the repaired contract and the malicious attack contract, and judging whether the repaired contract has a re-entrancy vulnerability according to the re-verification result, includes: Deploy the repaired contract and the malicious attack contract on the remix test chain, and send the repaired contract address to the malicious attack contract for attack. Execute and test the generated malicious attack contract, and verify whether the re-entrancy vulnerability is triggered, as the initial test scenario; wherein, the test includes testing the contract's fund flow, state changes, and the results of re-entrancy behavior. Based on the initial test scenario, combined with manual code auditing, test the functions of the smart contract to determine whether there is a risk of re-entrancy vulnerability.
8. A detection and repair system for intelligent contract re - entry vulnerabilities, characterized in that, Includes: A report generation module, used to extract the structural information and function call relationships of the smart contract, analyze potential re-entrancy vulnerabilities, and generate a re-entrancy vulnerability detection report. A path module, used to perform type checking according to the results of the re-entrancy vulnerability detection report, determine all functions that may have re-entrancy vulnerabilities, and determine potential attack paths according to each function that may have a re-entrancy vulnerability. A prompt module, used to perform instruction-level engineering structuring on the re-entrancy vulnerability detection report and potential attack paths to obtain a malicious attack contract generation prompt that can be understood and learned by the large language model. A malicious attack contract module, used to input the malicious attack contract generation prompt into the large language model, bypass the security warning of the large language model, and generate a malicious attack contract that can attack the victim contract. A test module, used to deploy the victim contract and the malicious attack contract in a test environment, simulate the trigger conditions for the re-entrancy vulnerability, and verify the re-entrancy vulnerability through the interaction test between the victim contract and the malicious attack contract. A judgment module, used to judge whether the malicious attack contract has a re-entrancy vulnerability according to the verification result. A repair module, used to adaptively repair the code of the victim contract with a re-entrancy vulnerability using the large language model according to the attack path to obtain a repaired contract. A repair judgment module, used to re-verify the re-entrancy vulnerability through the interaction test between the repaired contract and the malicious attack contract, and judge whether the repaired contract has a re-entrancy vulnerability according to the re-verification result.
9. An electronic device, characterized in that, Includes: A memory and one or more processors; the memory is coupled to the processor; wherein, the memory stores computer program code, and the computer program code includes computer instructions. When the computer instructions are executed by the processor, the electronic device executes the steps of the method for detecting and repairing the re-entrancy vulnerability of the smart contract according to any one of claims 1-7.
10. A computer-readable storage medium, characterized in that, The computer program stored in the computer-readable storage medium is executed by the processor to implement the steps of the method for detecting and repairing the re-entrancy vulnerability of the smart contract according to any one of claims 1-6.
Citation Information
Cited By
Intelligent contract vulnerability detection method based on machine learning and dynamic and static combined analysis
CN121834827A