Intelligent contract vulnerability automatic repair method and system based on genetic algorithm

By employing an automatic smart contract vulnerability repair method based on genetic algorithms, combining test coverage information and vulnerability detection confidence to locate suspicious vulnerable statements, and utilizing the NSGA-II algorithm to optimize the patch search space, high-quality patches are generated. This solves the problems of low repair success rate, patch overfitting, and high gas consumption in existing technologies, and achieves efficient, economical, and readable patch generation.

CN121959575APending Publication Date: 2026-05-01HANGZHOU DIANZI UNIV
View PDF 1 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
HANGZHOU DIANZI UNIV
Filing Date
2026-01-20
Publication Date
2026-05-01

AI Technical Summary

Technical Problem

Existing smart contract vulnerability repair technologies struggle to efficiently generate high-quality patches while ensuring functional correctness, and suffer from issues such as low repair success rates, patch overfitting, decreased code readability, or significantly increased gas consumption.

Method used

An automatic vulnerability repair method for smart contracts based on genetic algorithms is adopted. Suspicious vulnerable statements are located by fusing test coverage information and vulnerability detection confidence. A patch search space is constructed by combining predefined vulnerability repair templates and the NSGA-II algorithm. Fine-grained patch representation and multi-dimensional fitness function are used for multi-objective optimization to generate high-quality patches.

Benefits of technology

It achieves the goal of improving the success rate of repairs and the correctness of patches, while also taking into account the readability and cost-effectiveness of patches. The generated patches can be compiled and tested with reasonable gas consumption.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121959575A_ABST
    Figure CN121959575A_ABST
Patent Text Reader

Abstract

The invention discloses an intelligent contract vulnerability automatic repair method and system based on a genetic algorithm. The method comprises the following steps: (1) positioning an LBS of a statement to be repaired in an intelligent contract by fusing test coverage information and vulnerability detection confidence; (2) generating a repair component set for insertion, replacement and deletion around the LBS, and constructing and expanding a search space of the patch in combination with a predefined vulnerability repair template; and (3) encoding patch modification positions, operation types and repair component parameters by adopting fine-grained patch representation, and constructing a multi-dimensional fitness function to comprehensively evaluate patch quality from the targets of effectiveness, correctness, readability and economy. And searching and outputting patches meeting requirements in the patch search space constructed in the step (2) by using an NSGA-II multi-target genetic algorithm, and generating a repair result. While the repair success rate and the patch correctness are improved, the readability and economy of the patch are considered, and the automatic high-quality repair of the intelligent contract vulnerability is realized.
Need to check novelty before this filing date? Find Prior Art

Description

A Method and System for Automatic Repair of Smart Contract Vulnerabilities Based on Genetic Algorithms Technical Field

[0001] This invention belongs to the field of blockchain and smart contract security technology, and particularly relates to the field of automatic repair and program patching of smart contract vulnerabilities. Specifically, it relates to a method and system for automatic repair of smart contract vulnerabilities based on genetic algorithms. Background Technology

[0002] Smart contracts are autonomous programs written in high-level languages ​​such as Solidity and deployed on blockchain networks. They possess characteristics such as decentralization, automatic execution, and immutability, and have been widely applied in decentralized finance, digital asset trading, and on-chain governance. However, once deployed, smart contracts are often difficult to roll back or repair, and code defects can lead to irreversible asset losses. Common vulnerabilities in actual attacks include reentrancy vulnerabilities, access control flaws, denial-of-service attacks, timestamp dependencies, and failure to check external call return values. Therefore, how to efficiently generate high-quality patches while ensuring functional correctness is an important research direction in the field of smart contract security.

[0003] Existing smart contract vulnerability remediation technologies mainly include template-based automatic remediation methods and heuristic search-based automatic remediation methods. The former solidifies common vulnerability remediation patterns into code templates through predefined rules, offering advantages such as strong targeting and fast patch generation. However, it is usually limited by the template's coverage and struggles to handle code obfuscation, variant vulnerabilities, and unknown vulnerability types. The latter searches for patches in a predefined mutation space through operations such as insertion, deletion, and replacement, offering generality. However, the initial population construction is limited by the size of the contract's native code, resulting in a limited patch search space. Furthermore, it lacks fine-grained representation of complex remediation logic and multi-objective optimization capabilities, easily leading to problems such as low remediation success rates, patch overfitting, decreased code readability, or a significant increase in gas consumption. Summary of the Invention

[0004] To address the aforementioned problems in existing technologies, this invention provides a method and system for automatically repairing smart contract vulnerabilities based on genetic algorithms. This method improves the success rate and correctness of repairs while also considering the readability and cost-effectiveness (Gas consumption) of patches, thereby achieving automated and high-quality patching of smart contract vulnerabilities.

[0005] To achieve the above objectives, the technical solution of the present invention is as follows:

[0006] The automatic repair method for smart contract vulnerabilities based on genetic algorithms has the following specific steps:

[0007] Step (1), locate the suspected vulnerable statement LBS (Likely-Buggy Statement):

[0008] By integrating test coverage information and vulnerability detection confidence, LBS is used to locate suspicious vulnerable statements in smart contracts that need to be fixed.

[0009] Step (2), determine the patch search space:

[0010] The system generates a set of repair components for insertion, replacement, and deletion based on LBS, and combines them with predefined vulnerability repair templates to build and expand the patch search space.

[0011] Step (3), multi-objective patch search based on the NSGA-II algorithm:

[0012] Fine-grained patch representation is adopted to achieve precise encoding of patch modification location, operation type and repair component parameters. A multi-dimensional fitness function is constructed to comprehensively evaluate patch quality from the perspectives of effectiveness, correctness, readability and economy. The NSGA-II multi-objective genetic algorithm is used to search for and output patches that meet the requirements in the patch search space constructed in step (2) to generate repair results.

[0013] Preferably, step (1) involves locating the suspected vulnerable statement LBS, as follows:

[0014] (1-1) Obtain the source code of the smart contract to be repaired and its test case set T; execute the test cases and divide them into a positive test case set T according to the execution results. pos With negative test case set T neg At the same time, the execution path coverage information of each test case is recorded;

[0015] (1-2) Perform vulnerability detection on the smart contract to be patched and obtain the vulnerability confidence score (conf) for each line of code in the contract. i ;

[0016] (1-3) Based on the four test coverage scenarios (covered only by positive tests, covered only by negative tests, covered by both positive and negative tests, and not covered) and combined with the confidence score, calculate the suspicion value (susp) for each statement. i Based on the threshold γ min Filter and sort, retaining statements with a suspicion level higher than the threshold as suspected vulnerability statements LBS.

[0017] Preferably, step (2) determines the search space for the patch, as follows:

[0018] (2-1) Generating Repair Components Based on the Statement Redundancy Hypothesis: Candidate statements S are collected under the scope constraints of LBS. The first type of filtering rule and the second type of filtering rule are applied in sequence to eliminate statements that do not meet the requirements in terms of syntax, scope and security, thus obtaining the set of repair components R for the replacement operation. jWith the set of repair components I used for insertion operations j ;

[0019] (2-2) Generating Remediation Components Based on Vulnerability Remediation Templates: A remediation template set RT is constructed for vulnerability types such as reentrancy, arithmetic overflow / underflow, access control, denial of service, timestamp dependency, and unchecked call values. The corresponding remediation template is applied to each LBS and its related statements to transform them, and the transformed statements are added to RT as remediation components. j with I j This expands the patch search space.

[0020] Preferably, step (3) is a multi-objective patch search based on the NSGA-II algorithm, as follows:

[0021] (3-1) Fine-grained patch representation: Define a set of general operation types O={Delete,Replace,Insert} and number the LBS and repair component sets. Encode individual patches as quintuples so that each LBS can be independently selected for whether to edit, select the operation type such as replacement / insert / delete, and further select repair components from different sources; where Delete, Replace, and Insert represent deletion, replacement, and insertion operations, respectively.

[0022] (3-2) Multi-dimensional fitness function: The quality of patches is evaluated from four dimensions: effectiveness, correctness, readability and economy. Effectiveness is verified by vulnerability detection tools to see if the vulnerability has been fixed. Correctness is measured by regression defect rate and persistent failure rate to measure the impact of the patch on the original function and the degree of improvement of defective function. Readability is measured by the edit distance change rate to measure the scale of code changes. Economy is measured by the gas consumption change rate to measure the change in operating costs.

[0023] (3-3) Patch search: Initialize the patch population and evaluate multi-dimensional fitness; execute fast non-dominated sorting, crowding distance calculation and elite selection strategy to obtain the parent population; generate the offspring population through selection, semi-uniform crossover and mutation operator distinguished by data type; merge the parent and offspring and repeat the above process until the maximum number of iterations or the convergence condition is met.

[0024] (3-4) Patch selection and output: Select the correct patch from the final population that satisfies the condition that the vulnerability has been fixed and all test cases have passed; when there are multiple correct patches, prioritize the patch with the lower gas consumption change rate and the smaller edit distance change rate, and output it as the fixed smart contract code.

[0025] This invention also discloses an automatic smart contract vulnerability repair system based on a genetic algorithm, used to execute the above method, comprising the following modules:

[0026] Suspicious Vulnerable Statement LBS Location Module: Locates suspicious vulnerable statements in smart contracts by fusing test coverage information and vulnerability detection confidence.

[0027] Patch search space determination module: Generates a set of repair components for insertion, replacement and deletion based on LBS, and builds and expands the patch search space by combining predefined vulnerability repair templates;

[0028] Multi-objective patch search module: Employs fine-grained patch representation to achieve precise encoding of patch modification location, operation type, and repair component parameters. Constructs a multi-dimensional fitness function to comprehensively evaluate patch quality from objectives such as effectiveness, correctness, readability, and economy. Utilizes the NSGA-II multi-objective genetic algorithm to search for and output patches that meet the requirements in the patch search space, generating repair results.

[0029] The present invention has the following significant technical effects: (1) It integrates vulnerability detection confidence and test case coverage information to accurately locate suspicious vulnerability statements and narrow the scope of repair; (2) It combines statement redundancy hypothesis and predefined vulnerability repair template to construct and expand patch search space, thereby alleviating the problem of limited search space; (3) It adopts fine-grained patch representation and multi-dimensional fitness function, and uses NSGA-II multi-objective genetic search to output high-quality patches, and finally generates compilable, testable and high-quality repair results. Attached Figure Description

[0030] Figure 1 is a flowchart of a preferred embodiment of the present invention for an automatic repair method of smart contract vulnerabilities based on genetic algorithms;

[0031] Figure 2 is a schematic diagram of the calculation of suspiciousness based on confidence level and test coverage scenario in a preferred embodiment of the present invention;

[0032] Figure 3 is a schematic diagram of the generation of repair components based on the repair template in a preferred embodiment of the present invention;

[0033] Figure 4 is a schematic diagram of fine-grained patch representation encoding in a preferred embodiment of the present invention;

[0034] Figure 5 is a schematic diagram of the hybrid strategy genetic operator in a preferred embodiment of the present invention;

[0035] Figure 6 shows the distribution of the edit distance change rate of the patches generated by this invention on the PVD and EV-DS datasets;

[0036] Figure 7 is a distribution of the gas consumption change rate of the generated patches on the PVD and EV-DS datasets according to a preferred embodiment of the present invention.

[0037] Figure 8 is a block diagram of a smart contract vulnerability automatic repair system based on genetic algorithm according to a preferred embodiment of the present invention.

[0038] In Figure 3, LBS represents Likely Buggy Statements, indicating the location of the j-th Likely Buggy Statement to be patched. In Figure 4, Insert, Delete, and Replace represent the three basic editing operations: insert, delete, and replace, respectively, used for fine-grained patch representation and encoding. Detailed Implementation

[0039] The invention will now be further described with reference to the accompanying drawings.

[0040] As shown in Figure 1, this embodiment provides an automatic smart contract vulnerability repair method based on a genetic algorithm, mainly comprising three stages: locating suspicious vulnerability statements (LBS), determining the patch search space, and multi-target patch search based on NSGA-II. This method can be implemented on general-purpose computing devices, where the processor executes program instructions in memory to complete the automatic repair of contract vulnerabilities. Each step is described in detail below.

[0041] Step (1) Locate the suspected vulnerable statement LBS. This step accurately locates the statement to be repaired by fusing test coverage information and vulnerability detection confidence, reducing the search space. The specific steps are as follows:

[0042] (1) Test Case Execution and Coverage Records: Let the contract to be repaired be sc, and the set of test cases be T. Based on the actual execution results of T in the contract to be repaired sc, T is divided into T0, T1, and T2, T3, T4, and T5, respectively. pos and T neg Two parts. T pos T represents the set of positive test cases. pos The execution result matches the expected functionality of sc; T neg T represents the set of negative test cases. neg The execution result does not match the expected result of sc, and the set of statements covered by each test case on the execution path is recorded.

[0043] (2) Vulnerability Detection Confidence Acquisition: A vulnerability detection tool is executed on contract sc, using HGAT-SVD (a smart contract vulnerability detection method based on heterogeneous graph attention networks) to obtain the vulnerability confidence conf for each statement i. i This is used to characterize the degree of correlation between a statement and the target vulnerability.

[0044] In this embodiment, HGAT-SVD can be implemented using Chinese Patent Application Publication No. CN120705873A, Publication Date: September 26, 2025, Application No.: 2025107009166, entitled "A Smart Contract Vulnerability Detection Method Based on Heterogeneous Graph Attention Network". The process is briefly described as follows: It parses the source code of the smart contract under test into a heterogeneous program graph containing various semantic relationships. Nodes can be set as statement nodes, variable / identifier nodes, and function nodes, etc.; edges can be set as syntactic structure relationships (such as AST parent-child relationships), control flow relationships (such as sequential execution and branch jumps), and data dependency relationships (such as definition-use relationships). Based on the heterogeneous program graph, attention aggregation and fusion are performed on adjacent nodes under different types of relationships to obtain the contextual semantic representation of statement nodes, thereby comprehensively characterizing the syntactic structure, execution path, and data flow impact of statements. Finally, the vulnerability detection confidence score confi for each statement is output to characterize the degree of correlation between statement i and the target vulnerability type, and serves as the basis for subsequent calculation of statement suspiciousness and location of suspicious vulnerability statement set LBS by fusing with test coverage information.

[0045] Of course, the above-mentioned vulnerability detection method is only a preferred method. This invention does not limit the specific vulnerability detection method. Any detection model or tool that can output statement-level vulnerability confidence for fusion calculation can be used as a substitute, such as smart contract vulnerability detection methods based on graph neural networks like HGAT or SCVHunter, or other detection tools that can output statement-level risk scores. This invention can adopt these methods and achieve the purpose of this invention.

[0046] (3) Coverage scenario segmentation: For the i-th statement in smart contract sc, its coverage scenario segmentation is calculated in T. pos With T neg The coverage situation is divided into four scenarios:

[0047] ①Only by T pos Coverage: This indicates that all execution paths have passed the test case for the i-th statement.

[0048] ②Only by T neg Coverage: This indicates that none of the test cases that pass through the i-th statement in the execution path have passed the test.

[0049] ③ Simultaneously T pos T neg Coverage: This means that among the test cases in the execution path that pass the i-th statement, some of them pass the test.

[0050] ④ Not covered by T: This means that the execution path of any test case does not pass through the i-th statement.

[0051] (4) Calculation of statement suspicion level: For the above four situations, assign a suspicion level (susp) to each statement. i This indicates the degree of suspicion that the statement contains a vulnerability, and its calculation formula is as follows:

[0052]

[0053] Among them, conf i Confidence level for vulnerability detection. susp i The larger the value, the more valuable the fix for that statement. To narrow down the scope of vulnerability remediation, for susp... i Less than the threshold γ min Statements exceeding the threshold γ will be ignored. min The statements will be preserved and referred to as LBS.

[0054] As shown in Figure 2, the above-mentioned suspiciousness calculation and screening process forms a location link from "test coverage / confidence → suspiciousness → LBS".

[0055] Step (2) determines the patch search space. This step involves generating a set of repair components around the LBS that can be used for insertion, replacement, and deletion to support subsequent genetic searches. This step is detailed below:

[0056] (1) Define patch editing operations: The smallest unit constituting a patch is the specific operation performed on a particular LBS. Operation types are divided into three categories: deletion, replacement, and insertion. For replacement and insertion operations, R is defined... j and I j , representing the set of statements that can be used to replace LBS and the set of statements that can be inserted before LBS, respectively, i.e., the repair components. The three operation types and their corresponding repair components interact to jointly construct the most basic search space for patches.

[0057] (2) Generating Repair Components Based on the Statement Redundancy Hypothesis: A set of candidate statements S is collected under the scope constraints of each LBS. To characterize the correlation between candidate statements s and LBSs, a set of variables V is defined. S and V LBS Let V represent the set of variables involved in the LBS and the candidate statement, respectively; bef and V aft Let represent the sets of variables in the context statements before and after the LBS. The formulas for calculating the similarity sim(s,LBS) and relevance cor(s,LBS) are as follows:

[0058]

[0059] On the candidate statement set S, firstly, based on the Solidity syntax characteristics, the first type of filtering rule is applied to eliminate statements that lack independent semantics, are limited by specific syntactic structures, or cannot be inserted / replaced independently. Then, the second type of filtering rule is applied to the insertion and replacement operations respectively to further exclude candidate statements that are incompatible in type, have mismatched control flow structures, may introduce new risks, or cannot be compiled. Finally, the replacement and repair component set R is obtained. j With insertion repair component set I j .

[0060] To ensure that the candidate statements extracted from the contract to be repaired meet the Solidity syntax constraints and have independently transferable semantics, this invention first sets a first type of filtering rules to perform preliminary screening of the candidate statements. The specific rules are shown in Table 1.

[0061] Table 1. Type I Filtering Rules

[0062]

[0063] After completing the first type of filtering, in order to further ensure that the candidate statements can adapt to different editing operations (insert or replace) and avoid problems such as type mismatch and control flow disruption, this invention proposes a second type of repair filtering rules, as shown in Table 2.

[0064] Table 2. Category II Repair Filtering Rules

[0065]

[0066] (3) Generating Remediation Components Based on Vulnerability Remediation Templates: A set of remediation templates (RT) is established for common vulnerability types, and each LBS is matched with the corresponding template according to its vulnerability type for adaptation and conversion. Taking reentrancy vulnerabilities as an example, the template can move the state variable update statement forward or insert reentrancy locks and other protective logic through the "Check-Impact-Interact (CEI)" mode. Through variable substitution, function matching, and statement rearrangement in the template, code snippets that can be used for insertion or replacement are generated, and R is added accordingly. j or I j This expands the patch search space.

[0067] In response to the typical triggering patterns of reentrancy vulnerabilities, this invention summarizes the remediation ideas such as "check first, update the status, and then interact with externally" and forms a template that can be directly instantiated. Examples of the templates are shown in Table 3.

[0068] Table 3 Reentrancy Vulnerability Repair Template

[0069]

[0070] To address access control vulnerabilities (such as lack of permission verification or overly broad permission scope), this invention summarizes commonly used permission checking and modifier constraint strategies and forms templates, with examples shown in Table 4.

[0071] Table 4 Access Control Vulnerability Remediation Template

[0072]

[0073] For arithmetic vulnerabilities such as integer overflow / underflow, this invention summarizes remediation methods such as boundary checks, using secure arithmetic libraries, or explicit assertions, and forms templates, with examples of the templates shown in Table 5.

[0074] Table 5 Integer Overflow Vulnerability Repair Template

[0075]

[0076] For denial-of-service vulnerabilities (such as process blocking caused by external call failure, or exceptions that can be maliciously triggered in a loop), this invention summarizes the corresponding fault tolerance and structural adjustment strategies and forms templates, with examples of the templates shown in Table 6.

[0077] Table 6 Denial-of-Service Vulnerability Remediation Template

[0078]

[0079] For timestamp-dependent vulnerabilities, this invention summarizes and forms templates for remediation methods such as avoiding the use of unreliable time signals and adopting more robust constraints. Examples of the templates are shown in Table 7.

[0080] Table 7 Timestamp Dependency Vulnerability Remediation Template

[0081]

[0082] To address the vulnerability of unchecked call values, this invention summarizes and forms a template for remediation strategies that involve explicit validation and exception handling of external call return values. Examples of the templates are shown in Table 8.

[0083] Table 8 Unchecked Call Value Vulnerability Remediation Template

[0084]

[0085] To facilitate the unified use and matching of repair templates for different vulnerability types in subsequent genetic algorithm patch searches, this invention summarizes various vulnerability templates by number to form a template set, as shown in Table 9.

[0086] Table 9 Collection of Smart Contract Vulnerability Repair Templates

[0087]

[0088] Figure 3 illustrates the generation and instantiation of "template repair components". The left side of the figure shows a repair template library organized by vulnerability type (such as condition checks, access control, reentrancy protection, return value validation, arithmetic boundary handling, etc.). Each template describes the modification action (inserting "+", deleting "-", replacing "- / +" combinations) in the form of "editable script / differential fragments" and includes placeholder parameters (variable name, threshold constant, modifier, function call, etc.). The middle part represents the extraction of context information (available variable set, field set, call point information, etc.) centered on LBS, used to constrain template placeholders and generate candidates. The right side output is a set of repair components that can be directly used for genetic search: that is, specific code fragments that are "insertable / replaceable / deletable" obtained after binding the template with context parameters, ensuring that the generated candidate patches can be implemented in terms of syntax and scope.

[0089] Step (3) Multi-objective patch search based on NSGA-II. This step models the patch search as a multi-objective optimization problem, comprehensively optimizing repair quality, readability, and economy. The specifics of this step are as follows:

[0090] (1) Fine-grained patch representation: Patch operations are encoded independently for each LBS. First, a set of common operation types (or editing types) for all statements is defined, O = {Delete, Replace, Insert}. Then, for each LBS and set R... j I j The element numbers in the array are j∈{1,2,…,n}, where n represents the number of LBS in the contract. Based on this, the patch is encoded as the following quintuple:

[0091]

[0092] Among them, b j ∈{0,1} indicates whether to edit the j-th LBS. "0" means do not participate in editing, and "1" means participate in editing; This represents the set of operation types for the j-th LBS. This indicates the number of all subsets of the general operation type; different integers are used to identify different combinations of operations. This indicates that if the replacement operation is selected, R will be chosen. j p in j The statement replaces the j-th LBS; similarly, This indicates that if you choose to use the insert operation, you will select I.j The qth j The statement is inserted before the j-th LBS; d j ∈{0,1} and b j Similarly, it indicates whether to choose to delete the j-th LBS.

[0093] Figure 4 illustrates the fine-grained patch representation encoding. This encoding can be restored to an executable patch editing script through "decoding mapping," and corresponding changes can be implemented at the contract source code or AST level. This fine-grained encoding enables genetic operators to be combined and optimized at the "position," "operation," "component," and "parameter" levels, thereby improving search efficiency and patch quality controllability.

[0094] (2) Multidimensional fitness function: To guide the genetic search to converge toward high-quality patches, the fitness is defined to consist of four dimensions: effectiveness, correctness, readability and economy.

[0095] Validity: After applying the patch, the contract is recompiled and vulnerability checks are performed. If the target vulnerability is fixed, it is marked as "passed" and recorded as 1; otherwise, it is marked as 0. The definition formula is as follows:

[0096]

[0097] Correctness: Run all test cases and calculate the Regression Defect Rate (RDR) and Persistent Failure Rate (PFR). The relevant calculation formulas are as follows:

[0098]

[0099] Here, TS(sc,x,t) is used to determine whether the smart contract sc after applying patch x can pass the test case t. This indicates that the test was unsuccessful. When the regression defect rate is 0, RDR(x,sc) = 0. A lower regression defect rate means that while patching the target vulnerability, it minimizes the disruption to the original normal functionality.

[0100]

[0101] A high persistent failure rate indicates that the patch is ineffective in resolving functional failures caused by contract vulnerabilities and has failed to properly fix the related issues; while a low persistent failure rate means that the patch has successfully improved these functions that failed due to the vulnerability to some extent and has played a good role in fixing the contract vulnerability.

[0102] The overall correctness measure f2(x,sc) adopts a harmonic form of the two, and the calculation formula is as follows:

[0103]

[0104] The lower the value of f2(x,sc), the better the correctness of the repaired contract program. When f2(x,sc)=1, it means that all test cases have passed.

[0105] Readability: Measured by edit distance, indicating the scale of patch changes. Let the code text before the fix be s1, and the text after the fix be s2. The Levenshtein distance is lev. i,j The recursive formula is as follows:

[0106]

[0107] The edit distance change rate f3 is further defined and calculated using the following formula:

[0108]

[0109] Among them, lev i,j pd and pd constitute the state transition equation for calculating the edit distance. s1 and s2 represent the strings before and after the sc repair, respectively. The smaller f3(x,sc) is, the fewer times the patch edits the original contract, and the more readable the repaired contract is.

[0110] Economic Efficiency: Every execution of a smart contract incurs gas consumption. This invention estimates the total gas consumption of the smart contract by analyzing its gas consumption across different test cases. The economic efficiency of the patch is then measured by calculating the rate of change in gas consumption before and after the fix. The gas consumption of a single instruction can be expressed by the following formula:

[0111]

[0112] in, This represents the runtime environment before an instruction `inst` is executed; This indicates the gas consumption during the execution of the instruction `inst`. This indicates when the contract execution reaches the program counter. All opcodes corresponding to the position. This represents the gas consumption incurred due to memory usage during the execution of the instruction `inst`. The formula for calculating gas consumption during the execution of a single test case is as follows:

[0113]

[0114] Where path=(inst0,inst1,inst2,…,inst m ) represents all instruction sequences along the execution path of test case t, and m represents a variable-length sequence; The average gas consumption before and after the fix is ​​obtained by averaging the gas consumption across multiple paths on the test case set. bef and GAS aft And define the gas consumption change rate f4, the calculation formula is as follows:

[0115]

[0116] The smaller f4(x,sc) is, the better the cost-effectiveness of the patch.

[0117] After comprehensively considering the quality of patches across four dimensions—effectiveness, correctness, readability, and cost-effectiveness—the final multi-dimensional fitness function is obtained, calculated as follows:

[0118]

[0119] Here, f1(x,sc) and f2(x,sc) are combined into one dimension, which can simultaneously represent the validity and correctness of the patch.

[0120] (3) Genetic Search and Convergence Determination: For the contract sc to be repaired, construct a patch population P0 with an initial size of 2N. The edit flag b for each patch individual x∈P0. j The probability of initializing it to 1 is: .in, These are predefined parameters. The remaining components of patch individual x are based on the repair component R. j and I jConstraints on the search space are imposed, and random initialization is performed. Then, the multi-dimensional fitness function value (x.fitness) of each individual in P0 is calculated one by one (specifically: for each individual x: first, apply the patch to the contract to obtain sc′; if it cannot be compiled, set the fitness to the worst; run vulnerability detection on sc′ to obtain f1; then run all test cases to calculate RDR and PFR to obtain f2; at the same time, calculate the rate of change of edit distance to obtain f3; and calculate the rate of change of gas consumption to obtain f4)). After the fast non-dominated sorting (FastNonDominatedSort), crowding distance calculation (specifically: within each non-dominated front, sort each target dimension according to the target value; set the crowding distance of boundary individuals to infinity; the crowding distance of other individuals is the sum of the normalized differences of adjacent individuals in that target dimension) (CrowdingDistance), and the elite selection strategy (EliteSelect) of the NSGA-II algorithm, a first-generation population P1 of size N is obtained, and the formula for the change of crowding distance ΔHV of the first non-dominated front is defined as follows:

[0121]

[0122] in, This represents the first non-dominant frontier in the contemporary population, while This represents the first non-dominated front of the previous generation. The smaller ΔHV is, the higher the convergence of the algorithm.

[0123] (4) Hybrid Genetic Operator: A hybrid genetic strategy is used to generate offspring. First, the Half-Uniform Crossover operator (HUX) is applied to the parent individuals to generate intermediate offspring; then, single-point mutation and numerical mutation are used specifically for different data types of coding patches, i.e., for b... j and d j Applying single-site mutation to u j p j and q j Numerical mutation is applied. Through genetic computation, the offspring population Q after crossover and mutation is obtained. g .

[0124] Algorithm: Patch Heuristic Search Algorithm (Multi-objective Patch Search Based on NSGA-II Algorithm)

[0125] Input: The smart contract to be repaired (sc), test case (T) pos and T neg Repair component R = {R1, R2, ..., R} n} and I={I1,I2,…,I n}

[0126] Output: Correct patch pitch.

[0127]

[0128]

[0129]

[0130]

[0131]

[0132]

[0133]

[0134]

[0135]

[0136]

[0137]

[0138]

[0139]

[0140]

[0141]

[0142] 16

[0143]

[0144]

[0145]

[0146]

[0147]

[0148]

[0149]

[0150]

[0151]

[0152]

[0153]

[0154]

[0155]

[0156]

[0157] This algorithm is used to prioritize searching for patches that are more likely to fix vulnerabilities and have lower costs in the patch space consisting of a set of suspicious statements (LBS) and repair components / templates. It follows a heuristic strategy of "generating candidate patches - compiling and testing verification - filtering and iterating by fitness" to quickly obtain the optimal repair solution that meets the constraints.

[0158] Figure 5 first employs an NSGA-II-based selection mechanism: candidate patches are non-dominated based on multi-objective fitness, and population diversity is maintained by incorporating crowding distance, preserving elite individuals for the next generation; the crossover operator exchanges gene fragments between two parent patches, with the exchange granularity covering "repair location fragments (exchange between different LBSs)," "repair component fragments (exchange component indices within the same LBS)," or "parameter fragments (exchange template parameter values)"; the mutation operator perturbs the genes with a certain probability, such as switching operation types, replacing repair components, modifying parameter candidates, or adjusting whether to enable repair on a certain LBS. Through this hybrid strategy of "multi-granularity crossover + targeted mutation," effective repair fragments can be inherited quickly, while also escaping local optima and increasing the probability of generating correct patches.

[0159] (5) Patch selection and output: Select the patch that meets the condition of "passing vulnerability detection and all test cases pass" from the final population as the correct patch; if there are multiple correct patches, select the patch with smaller Gas consumption change rate and smaller edit distance change rate as the preferred criteria, and output the repaired smart contract code.

[0160] To ensure the reproducibility of the multi-objective patch search process based on NSGA-II, this invention sets key parameters such as population size, number of iterations, and crossover / mutation probability. Parameter details are shown in Table 10.

[0161] Table 10 Experimental Parameter Details

[0162]

[0163] Figure 6 illustrates the distribution of "correct patches" generated by this invention on different datasets in terms of edit distance change rate. This demonstrates the "restraint" of this invention in modifying source code while ensuring successful repair: the more concentrated the distribution is in areas with lower change rates, the more likely that most patches only modify a few statements or local structures, better preserving the original contract semantics and improving patch readability and auditability; if some sample distributions show a long tail, it indicates that the corresponding vulnerability or scenario requires more complex structural modifications, and this invention can still obtain feasible repairs through a combination of templates and search.

[0164] Figure 7 illustrates the distribution of the "correct patch" generated by this invention in terms of Gas consumption change rate. This reflects the invention's ability to control repair costs: when the distribution is concentrated in a region close to 0, it indicates that most patches do not significantly increase on-chain execution costs while fixing vulnerabilities; if a small negative value region appears, it means that some patches can eliminate vulnerabilities while also optimizing unnecessary overhead; if a positive long tail exists, it suggests that some templates will bring higher security redundancy costs. In this case, a multi-objective selection strategy can be used to prioritize outputting patch schemes with smaller Gas consumption change rates that simultaneously pass testing and eliminate vulnerabilities.

[0165] Furthermore, Table 11 shows the comparison results of the repair correctness of the GA-SVR of the present invention with the typical comparison methods sGuard and sGuard+ on the PVD and EV-DS datasets, demonstrating the advantages of the present invention in terms of repair quantity and patch correctness.

[0166] In Table 11, "251" represents the total number of contracts used for evaluation, which is the sum of the sample sizes of the PVD and EV-DS datasets. Therefore, the "number of repaired contracts" in the table is presented using the combined statistical method of "number of successful repairs / 251".

[0167] Table 11. Experimental results comparing the repair correctness of each method on the PVD and EV-DS datasets.

[0168]

[0169] In summary, the preferred embodiment of this invention proposes an automatic smart contract vulnerability repair method based on genetic algorithms. This method achieves precise location of the vulnerability to be repaired by fusing test coverage information and vulnerability detection confidence, and constructs a set of suspicious statements (LBS) to narrow the patch search space. Furthermore, it combines the statement redundancy hypothesis with vulnerability repair templates to generate repair components, and forms high-quality candidate domains through filtering rules and threshold constraints. Finally, it uses NSGA-II to balance and optimize multiple objectives such as vulnerability elimination, regression correctness, modification scope, and gas cost, iteratively filtering to obtain the optimal patch that meets the constraints, thereby improving the efficiency, controllability, and stability of automatic repair.

[0170] The experimental results show that the present invention can repair up to 198 contracts with a repair success rate of 78.88%, which is better than the comparative method. At the same time, the RDR is 13.68%, the PFR is 19.64%, and the overall accuracy is 74.77%, indicating that the present invention can effectively reduce regression defects and the risk of continuous failure while improving the repair coverage. Combined with the statistical results of edit distance and gas consumption changes, it shows that the patch changes are more concentrated and the execution cost is more controllable, which has high engineering practical value and prospects for promotion and application.

[0171] In summary, this invention proposes a closed-loop framework of "LBS suspicious statement localization—patch search space construction—NSGA-II multi-objective genetic search," forming an interpretable and controllable automatic repair process. In this invention, the localization phase integrates test coverage information and vulnerability detection confidence, outputting a statement-level suspicious set (LBS), significantly reducing the search space and improving convergence efficiency. The search space is simultaneously composed of "statement redundancy repair components + vulnerability repair template components," and filtering rules and similarity / relevance thresholds are set to reduce uncompileable and invalid patches. This invention employs fine-grained patch representation (hierarchical encoding of location / operation / component / parameter) and a multi-dimensional fitness function, balancing multiple objectives between vulnerability elimination, regression correctness, modification amount, and gas cost. Experimental results show that the repair success rate and overall accuracy are higher on 251 contracts in PVD and EV-DS, with lower RDR and PFR, demonstrating the advantages of "broader repair coverage, more stable regression, and more controllable cost."

[0172] As shown in Figure 8, this embodiment discloses an automatic smart contract vulnerability repair system based on a genetic algorithm, used to execute the above method, including the following modules:

[0173] Suspicious Vulnerable Statement LBS Location Module: Locates suspicious vulnerable statements in smart contracts by fusing test coverage information and vulnerability detection confidence.

[0174] Patch search space determination module: Generates a set of repair components for insertion, replacement and deletion based on LBS, and builds and expands the patch search space by combining predefined vulnerability repair templates;

[0175] Multi-objective patch search module: Employs fine-grained patch representation to achieve precise encoding of patch modification location, operation type, and repair component parameters. Constructs a multi-dimensional fitness function to comprehensively evaluate patch quality from objectives such as effectiveness, correctness, readability, and economy. Utilizes the NSGA-II multi-objective genetic algorithm to search for and output patches that meet the requirements in the patch search space, generating repair results.

[0176] Other aspects of this embodiment can be found in the above method embodiments.

[0177] In summary, this invention employs a three-stage "location-construction-search" approach to transform patch generation from unconstrained rewriting to controlled search, balancing efficiency and correctness. LBS location fusion, combining coverage differences and detection confidence, narrows the scope while maintaining focus on high-risk statements even with insufficient coverage. The search space is constructed jointly from redundant and template components, incorporating filtering rules and threshold control to reduce the proportion of uncompileable / invalid patches. A multi-dimensional fitness function and NSGA-II Pareto optimization achieve an interpretable trade-off between "safety, correctness, readability, and cost," resulting in more stable and usable patches.

[0178] The above description, in conjunction with the accompanying drawings, details the implementation of the automatic smart contract vulnerability repair method and system based on genetic algorithms of the present invention. However, the present invention is not limited to the described implementation. For those skilled in the art, various changes, modifications, substitutions, and variations can be made to the construction method of the repair components, fitness evaluation indicators, and genetic operator parameters without departing from the principles and spirit of the present invention, and these variations still fall within the protection scope of the present invention.

Claims

1. An automatic vulnerability repair method for smart contracts based on genetic algorithms, characterized by: The specific steps are as follows: Step (1), Locate the suspicious vulnerability statement LBS: Locate the suspicious vulnerability statement LBS in the smart contract by fusing test coverage information and vulnerability detection confidence; Step (2), Determine the patch search space: Generate a set of repair components for insertion, replacement and deletion around the LBS, and construct and expand the patch search space by combining predefined vulnerability repair templates; Step (3), Multi-objective patch search based on NSGA-II algorithm: Use fine-grained patch representation to encode the patch modification location, operation type and repair component parameters, construct a multi-dimensional fitness function to comprehensively evaluate the patch quality from the objectives of effectiveness, correctness, readability and economy, and use the NSGA-II multi-objective genetic algorithm to search for and output patches that meet the requirements in the patch search space constructed in step (2) to generate repair results.

2. The method for automatically repairing smart contract vulnerabilities based on genetic algorithms as described in claim 1, characterized in that, Step (1) is as follows: (1-1) Obtain the source code of the smart contract to be repaired and its test case set T; execute the test cases and divide them into a positive test case set T according to the execution results. pos With negative test case set T neg Record the execution path coverage information of each test case; (1-2) Perform vulnerability detection on the smart contract to be repaired and obtain the vulnerability detection confidence score conf for each line of code in the contract. i (1-3) Calculate the suspiciousness value (susp) of each statement based on the test coverage scenarios and the vulnerability detection confidence. i Based on the threshold γ min Filter and sort, retaining statements with a suspicion level higher than the threshold as suspected vulnerability statements LBS.

3. The automatic smart contract vulnerability repair method based on genetic algorithm as described in claim 2, characterized in that, In step (1-1), test case execution and coverage recording: Let the contract to be repaired be sc; based on the actual execution results of the test case set T in the contract to be repaired sc, divide T into T0, T1, T2, T3, T4, T5, T6, T7, T8 pos and T neg The process consists of two parts, simultaneously recording the set of statements covered by each test case along the execution path; in steps (1-2), vulnerability detection confidence is obtained: vulnerability detection is performed on contract sc to obtain the vulnerability confidence conf for each statement i. i In steps (1-3), the coverage scenario is divided as follows: For the i-th statement in contract sc, its coverage in T is calculated. pos With T neg The coverage situation is divided into four scenarios: ① Only covered by T pos Coverage: This indicates that all execution paths passing through the test case of the i-th statement have passed the test; ② Only those executed by T neg Coverage: Indicates that none of the test cases along the execution path that pass through the i-th statement pass the test; ③ Simultaneously, it is T pos T neg Coverage: Indicates that among the test cases whose execution path passes through the i-th statement, some have passed the test; ④ Not covered by T: Indicates that the execution path of no test case passes through the i-th statement; In steps (1-3), the calculation of the statement suspicion value: For the above four scenarios, assign a suspicion value of susp to each statement. i This indicates the degree of suspicion that the statement contains a vulnerability, calculated as follows: Among them, conf i For vulnerability detection confidence; for susp i Less than the threshold γ min Statements that are ignored are greater than the threshold γ. min The statement is preserved as an LBS.

4. The automatic smart contract vulnerability repair method based on genetic algorithm as described in claim 3, characterized in that, Step (2) is as follows: (2-1) Generate repair components based on the statement redundancy hypothesis: Collect candidate statements S under the scope constraints of LBS, apply filtering rules to remove statements that do not meet the requirements, and obtain the set of repair components R for replacement operation. j With the set of repair components I used for insertion operations j (2-2) Generate remediation components based on vulnerability remediation templates: Construct a set of remediation templates RT for each vulnerability type, apply the corresponding remediation template to transform the LBS and its related statements, and add the transformed statements as remediation components to RT respectively. j with I j This is to expand the patch search space.

5. The automatic smart contract vulnerability repair method based on genetic algorithm as described in claim 4, characterized in that, In step (2), first define the patch editing operations: the operation types are divided into deletion, replacement, and insertion operations; for replacement and insertion operations, define R. j and I j Let S represent the set of statements used to replace LBS and the set of statements used to insert before LBS, respectively; in step (2-1), repair components are generated based on the statement redundancy hypothesis: a set of candidate statements S is collected under the scope constraints of each LBS, and a set of variables V is defined. S and V LBS Let V represent the set of variables involved in the LBS and the candidate statement, respectively; bef and V aft Let represent the sets of variables for the context statements before and after LBS; the formulas for calculating similarity sim(s,LBS) and relevance cor(s,LBS) are as follows: On the candidate statement set S, firstly, based on the Solidity syntax characteristics, the first type of filtering rule is applied to eliminate statements that lack independent semantics, are limited by specific syntactic structures, or cannot be inserted / replaced independently. Then, for insertion and replacement operations, the second type of filtering rule is applied separately to exclude candidate statements that are incompatible with types, have mismatched control flow structures, introduce new risks, or fail to compile. Finally, the replacement and repair component set R is obtained. j With insertion repair component set I j In step (2-2), remediation components are generated based on the vulnerability remediation template: the vulnerability type is a reentrancy vulnerability, and the state variable update statement is moved forward or reentrancy lock protection logic is inserted through the "inspect-impact-interaction CEI" mode; through variable substitution, function matching and statement rearrangement in the template, code snippets for insertion or replacement are generated, and R is added respectively. j or I j This is to expand the patch search space.

6. The automatic smart contract vulnerability repair method based on genetic algorithm as described in claim 5, characterized in that, Step (3) is as follows: (3-1) Fine-grained patch representation: Define a set of general operation types O={Delet,Replace,Insert} and number the LBS and repair component sets, encode individual patches as quintuples, and select repair components from different sources; (3-2) Multi-dimensional fitness function: Evaluate patch quality from four dimensions: effectiveness, correctness, readability, and economy. Among them, effectiveness is verified by vulnerability detection tools to see if the vulnerability has been fixed; correctness is measured by regression defect rate and persistent failure rate to measure the impact of the patch on the original function and the degree of improvement of the defective function; readability is measured by edit distance change rate to measure the scale of code changes; and economy is measured by Gas consumption. Gas consumption change rate measures the change in operating costs; (3-3) Patch search: Initialize the patch population and evaluate multi-dimensional fitness; execute fast non-dominated sorting, crowding distance calculation and elite selection strategies to obtain the parent population; generate the offspring population through selection, semi-uniform crossover and mutation operators distinguished by data type; merge the parent and offspring and repeat the above process until the maximum number of iterations or convergence conditions are met; (3-4) Patch screening and output: screen patches from the final population that meet the conditions that the vulnerability is fixed and all test cases pass as correct patches; when there are multiple correct patches, prioritize the patch with lower gas consumption change rate and smaller edit distance change rate, and output it as the fixed smart contract code.

7. The automatic smart contract vulnerability repair method based on genetic algorithm as described in claim 6, characterized in that, In step (3-1), the fine-grained patch representation is as follows: Patch operations are independently encoded for each LBS; first, a general operation type or edit type set O = {Delete, Replace, Insert} is defined for all statements; then, the LBS and set R are processed... j I j The element number in the contract is j∈{1,2,…,n}, where n represents the number of LBS in the contract; the patch is encoded as the following quintuple: Among them, b j ∈{0,1} indicates whether to edit the j-th LBS, where "0" means not to participate in the editing and "1" means to participate in the editing; This represents the set of operation types for the j-th LBS. This indicates the number of all subsets of the general operation type; different integers are used to identify different combinations of operations. This indicates that if the replacement operation is selected, R will be chosen. j p in j The statement replaces the j-th LBS; This indicates that if you choose to use the insert operation, you will select I. j The qth j The statement is inserted before the j-th LBS; d j ∈{0,1} indicates whether to choose to delete the j-th LBS.

8. The method for automatically repairing smart contract vulnerabilities based on genetic algorithms as described in claim 7, characterized in that, In the multi-dimensional fitness function of step (3-2): Validity: The contract after applying the patch is recompiled and vulnerability detection is performed. If the target vulnerability is fixed, it is judged as "passed" and recorded as 1; otherwise, it is recorded as 0. The formula is defined as follows: Correctness: Run all test cases and calculate the Regression Defect Rate (RDR) and Persistent Failure Rate (PFR) using the following formulas: Here, TS(sc,x,t) is used to determine whether the smart contract sc after applying patch x can pass the test case t. This indicates that the test was not passed; when When , RDR(x,sc)=0; The formula for calculating the overall correctness metric f2(x,sc) is as follows: Where, a lower f2(x,sc) indicates better correctness of the repaired contract program; readability: measured by edit distance; let the code text before repair be s1, and the text after repair be s2, and the Levinstein distance lev i,j The recursive formula is as follows: Define the edit distance change rate f3 as follows: Among them, lev i,j pd and pd constitute the state transition equation for calculating the edit distance; s1 and s2 represent the strings before and after sc repair, respectively; Economy: Gas consumption per instruction is expressed by the following formula: in, This indicates the runtime environment before an instruction `inst` is executed; This indicates the gas consumption during the execution of the instruction `inst`. This indicates when the contract execution reaches the program counter. All opcodes corresponding to the position; This represents the gas consumption incurred due to memory usage during the execution of the instruction `inst`. The gas consumption calculation formula for a single test case execution is as follows: Where path=(inst0,inst1,inst2,…,inst m ) represents all instruction sequences along the execution path of test case t, and m represents a variable-length sequence; The average gas consumption before and after the fix is ​​obtained by averaging the gas consumption across multiple paths on the test case set. bef and GAS aft And define the rate of change of gas consumption f4, which is calculated as follows: After comprehensively considering the quality of patches across four dimensions—effectiveness, correctness, readability, and cost-effectiveness—the final multi-dimensional fitness function is obtained, calculated as follows: 。 9. The method for automatically repairing smart contract vulnerabilities based on genetic algorithms as described in claim 8, characterized in that, Step (3-3) is as follows: For the contract sc to be repaired, construct a patch population P0 with an initial size of 2N; the edit flag b for each patch individual x∈P0. j The probability of initializing it to 1 is: ;in, For predefined parameters; the remaining components of patch individual x are based on the repair component R. j and I j Constraints on the search space are imposed, and random initialization is performed. Then, the multi-dimensional fitness function value x.fitness of each individual in P0 is calculated. After passing through the NSGA-II algorithm's FastNonDominatedSort, CrowdingDistance calculation, and EliteSelect strategy, a first-generation population P1 of size N is obtained, and the formula for the change in crowding distance ΔHV of the first non-dominated frontier is defined as follows: in, This represents the first non-dominant frontier in the contemporary population. This represents the first non-dominated frontier of the previous generation; then, a hybrid genetic strategy is used to generate offspring; first, the semi-uniform crossover operator HUX is applied to the parent individuals to generate intermediate offspring; then, based on the different data types of the encoding patches, b... j and d j Applying single-site mutation to u j p j and q j Numerical mutation is applied; through genetic computation, the offspring population Q after crossover and mutation is obtained. g Merge the parent and child generations and repeat the above process until the maximum number of iterations or the convergence condition is met.

10. A smart contract vulnerability automatic repair system based on genetic algorithms, used to perform the method as described in any one of claims 1-9, characterized in that, Includes the following modules: Suspicious Vulnerable Statement LBS Location Module: This module locates suspicious vulnerable statements in smart contracts by fusing test coverage information and vulnerability detection confidence. The patch search space determination module generates a set of repair components for insertion, replacement, and deletion based on LBS (Location-Based Service), and constructs and expands the patch search space by combining it with predefined vulnerability repair templates. The multi-objective patch search module uses fine-grained patch representation to encode the patch modification location, operation type, and repair component parameters. It constructs a multi-dimensional fitness function to comprehensively evaluate patch quality from the objectives of effectiveness, correctness, readability, and economy, and uses the NSGA-II multi-objective genetic algorithm to search for and output patches that meet the requirements in the patch search space, generating repair results.

Citation Information

Patent Citations

  • Intelligent contract vulnerability detection method based on heterogeneous graph attention network

    CN120705873A