A method and apparatus for detecting smart contract vulnerabilities based on particle-based computation and weighted path signature similarity.
By employing particle-based computation and weighted path signature similarity methods, the problem of insufficient accuracy in smart contract vulnerability detection is solved, enabling more precise vulnerability identification and defense mechanism judgment, and improving the security assessment of smart contracts.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-01-13
- Publication Date
- 2026-03-10
AI Technical Summary
Existing smart contract vulnerability detection methods are insufficient in accuracy. Traditional methods rely on manually defined expert rules, which are difficult to adapt to the diverse smart contract code. Deep learning methods fail to effectively consider the impact of vulnerability-irrelevant code and ignore the semantics of custom contract names.
By using particle sphere computation and weighted path signature similarity, sensitive functions in the source code of smart contracts are identified, control flow graphs are generated and reverse program slice analysis is performed, node weights are calculated by combining abstract syntax trees and program dependency graphs, word-vector mapping tables are constructed and weighted path signatures are generated, similarity comparisons are performed to identify potential vulnerability paths, and defense patterns are detected.
It improves the accuracy and efficiency of vulnerability detection, reduces the false positive rate, and can more accurately identify potential vulnerabilities and defense mechanisms, providing a comprehensive and reliable security assessment.
Smart Images

Figure CN119939602B_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The application belongs to the technical field of computers, and particularly relates to an intelligent contract vulnerability detection method and device based on granular ball calculation and weight path signature similarity. BACKGROUND
[0002] Blockchain technology has been widely applied in many fields such as finance, supply chain management and Internet of Things. The security of smart contract, as the core component of blockchain, plays a decisive role in the stable operation of the entire system and the safety of user assets. Therefore, the security research of smart contract vulnerabilities has become a key link to promote the development and application of blockchain technology. Through in-depth research on smart contract vulnerabilities, hackers can be effectively prevented from exploiting vulnerabilities to attack, and serious consequences such as economic losses and data breaches can be avoided, which makes smart contract vulnerability detection a hot research direction at present.
[0003] At present, there are mainly two types of methods for detecting smart contract vulnerabilities: traditional program analysis-based methods and deep learning-based methods. In the field of traditional program analysis, open-source static analysis tools like Slither parse contract code, build abstract syntax trees and control flow graphs, and use techniques such as symbolic execution and data flow analysis to find potential security issues. In the field of deep learning, the SaferSC model pioneered the use of deep learning to detect smart contract vulnerabilities. It analyzes the operation code of smart contracts and builds an Ethereum operation code sequence model using the LSTM network, thereby realizing the identification and detection of smart contract vulnerabilities.
[0004] Although existing methods have achieved certain results in smart contract vulnerability detection, there are still obvious deficiencies in accuracy, which can be summarized as follows:
[0005] Limitations of traditional program analysis methods: such methods are highly dependent on expert rules defined by humans. On the one hand, smart contract code is diverse in form and varies in coding style, making it extremely difficult to develop uniform and comprehensive rules. On the other hand, smart contracts mainly involve asset transactions, which are sensitive in operation and have unique transfer functions such as call.value(), resulting in logical vulnerabilities in most contract vulnerabilities, making it almost impossible to manually define a complete vulnerability pattern.
[0006] Defects of deep learning methods: this method does not fully consider the impact of vulnerability-irrelevant code. In smart contract projects, vulnerability-related code usually accounts for a small proportion, and sometimes a single statement can determine whether a contract has vulnerabilities. However, when learning contract representation, if all code is treated equally, due to the large proportion of vulnerability-irrelevant code, the model is difficult to learn the mapping relationship between effective vulnerability features and labels, thus leading to deviations in vulnerability detection results.
[0007] Neglect of contract custom name semantics: existing methods generally do not pay attention to the semantic importance of contract custom names (including function names and variable names). In fact, the naming of most contract variables has its actual meaning, and many names that are not synonyms express similar meanings. But the traditional program analysis method directly adopts the normalization method to erase the meaning of the custom name, and the deep learning method also fails to consider the connection between different words. For example, variable names credit, balance and contributions, and function names withdraw () and refund (). SUMMARY
[0008] In order to solve the problems in the background art, one aspect of the present application provides an intelligent contract vulnerability detection method based on granular ball calculation and weight path signature similarity, comprising:
[0009] S1: determining sensitive functions in the source code of the smart contract according to the given sensitive word list, and generating a control flow graph corresponding to each sensitive function, performing reverse program slicing analysis to obtain a set of sensitive paths in the control flow graph from the sensitive function entrance to the sensitive word, wherein the function where the sensitive word is located is referred to as the sensitive function;
[0010] S2: generating a program dependency graph of the sensitive function based on the abstract syntax tree and the control flow graph of the sensitive function, for each sensitive path in the set of sensitive paths, calculating the PageRank value of each node in the sensitive path in the program dependency graph as the weight value of the node in the path, and generating a weight path corresponding to the sensitive path;
[0011] S3: constructing a word-vector mapping table of the smart contract through the granular ball algorithm, generating a vector representation of each node in the sensitive path based on the word-vector mapping table; and fusing the vector representation of each node in the sensitive path and the weight path information to obtain a weight path signature;
[0012] S4: comparing the weight path signature of each sensitive path with the weight path signatures in the vulnerability signature library respectively, when there are N weight path signatures in the vulnerability signature library that are similar to the weight path signature of the sensitive path and greater than a set threshold, the sensitive path is considered as a potential vulnerability path of the vulnerability type corresponding to the vulnerability signature library;
[0013] S5: detecting from the source code of the smart contract whether the potential vulnerability path contains a defense mode of its corresponding vulnerability type, if not, determining that the source code of the smart contract contains the vulnerability of this type.
[0014] Another aspect of the present application provides a smart contract vulnerability detection device based on granular ball calculation and weight path signature similarity, comprising a processor and a memory; the memory is used for storing a computer program; the processor is connected with the memory and is used for executing the computer program stored in the memory, so that the smart contract vulnerability detection device based on granular ball calculation and weight path signature similarity executes the smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity.
[0015] Still another aspect of the present application provides a computer readable storage medium storing a program, which, when executed by a processor, implements the smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity.
[0016] The present application has at least the following beneficial effects
[0017] The present application can comprehensively obtain all sensitive path sets from the sensitive function entrance to the sensitive word by determining the sensitive function in the smart contract source code according to the given sensitive word list, generating a control flow graph and performing reverse program slicing analysis. Compared with the traditional method, this method is no longer limited to surface code analysis, but goes deep into the code, more comprehensively covers the area where vulnerabilities may exist, and greatly reduces the possibility of false negatives. The program dependence graph is generated based on the abstract syntax tree and the control flow graph of the sensitive function, and the PageRank value of each node in the sensitive path in the program dependence graph is calculated as the weight value to generate the weight path. This process fully considers the dependency relationship between nodes in the smart contract code and the importance of each node, changes the previous practice of treating all code nodes equally, makes the vulnerability analysis more accurate, and effectively improves the detection accuracy. The granular ball algorithm is used to construct the smart contract word-vector mapping table, generate a vector representation for each node in the sensitive path, and fuse the weight path information to obtain the weight path signature. This innovative representation method not only comprehensively describes the features of the smart contract code, but also fully considers the relationship between the words in the code, making up for the defects of the existing methods that ignore the semantics of contract custom names. By comparing the weight path signature of the sensitive path with various vulnerability signature libraries, potential vulnerability paths can be more accurately identified, the detection capability for new and complex vulnerabilities is enhanced, and the false positive rate is reduced. After detecting the potential vulnerability path, it is further detected from the smart contract source code whether the path contains the defense mode of the corresponding vulnerability type, and if not, it is determined that there is this type of vulnerability. This comprehensive detection method not only stops at discovering potential vulnerabilities, but also can judge whether the smart contract has effective defense mechanisms, providing a more comprehensive and reliable basis for the security evaluation of the smart contract. BRIEF DESCRIPTION OF DRAWINGS
[0018] Figure 1This is a schematic diagram of the method flow of the present invention. Detailed Implementation
[0019] The following specific examples illustrate the implementation of the present invention. Those skilled in the art can easily understand other advantages and effects of the present invention from the content disclosed in this specification. The present invention can also be implemented or applied through other different specific embodiments, and various details in this specification can be modified or changed based on different viewpoints and applications without departing from the spirit of the present invention. It should be noted that the illustrations provided in the following embodiments are only schematic representations of the basic concept of the present invention. Unless otherwise specified, the following embodiments and features can be combined with each other.
[0020] Please see Figure 1 One aspect of the present invention provides a smart contract vulnerability detection method based on particle-based computation and weighted path signature similarity, comprising:
[0021] S1: Determine the sensitive functions in the smart contract source code based on the given list of sensitive words, generate the control flow diagram corresponding to each sensitive function, and perform reverse program slice analysis to obtain the set of all sensitive paths from the entry point of the sensitive function to the sensitive word in the control flow diagram. The function where the sensitive word is located is called the sensitive function.
[0022] Preferably, the set of all sensitive paths from sensitive function entry points to sensitive words in the control flowchart includes:
[0023] S11: For each line of target code containing a sensitive word in a sensitive function, through... The function locates its basic block in the control flow graph. ;
[0024] S12: For each basic block containing the target line of code From the current basic block Traverse the control flow graph in reverse order to obtain all its parent blocks. ;
[0025] S13: and initialize ;
[0026] S14: Iterate through each ,Will join in and judge Is it the entry point of a sensitive function? If so, then join in and clear Conversely, from Traverse the control flow graph in reverse order to obtain all its parent blocks. ;
[0027] S15: Order Repeat steps S14-S15 until... Output the set of sensitive paths until the condition is empty. .
[0028] Preferably, given the smart contract source code, the system first uses static analysis techniques based on a sensitive keyword library (Table 1 provides examples of vulnerability types and corresponding sensitive keywords) and regularized matching to traverse the positions of sensitive words and the functions they reside in (referred to as sensitive functions). For each sensitive function, its control flow graph is generated using the existing tool cfgGen. Then, the sensitive positions it contains are analyzed one by one. For each target line of code, the basic block in which it resides is located.
[0029] Table 1 Examples of Vulnerability Types and Sensitive Keywords
[0030]
[0031] The following uses a simple smart contract example to illustrate the specific operation process of step S1 and its preferred implementation.
[0032] Suppose we have the following simple smart contract code:
[0033] contract Example {
[0034] uint balance;
[0035] function deposit() public payable {
[0036] balance += msg.value;
[0037] }
[0038] function withdraw() public {
[0039] if (msg.sender.call.value(balance)()) {
[0040] balance = 0;
[0041] }
[0042] }
[0043] function selfDestructContract() public {
[0044] selfdestruct(payable(msg.sender));
[0045] }
[0046] }
[0047] Sensitive functions are determined based on a sensitive keyword database and regularized matching.
[0048] Based on the given sensitive keyword library (Table 1), we use static analysis techniques to traverse the smart contract source code forward.
[0049] For example, regarding the "reentrancy vulnerability," the sensitive keyword is call.value. The withdraw function contains msg.sender.call.value(balance)(), therefore the withdraw function is identified as a sensitive function.
[0050] For "self-destruct operations without access control", the sensitive keyword is selfdestruct(). Since selfdestruct(payable(msg.sender)) appears in the selfDestructContract function, the selfDestructContract function is also identified as a sensitive function.
[0051] Control flow diagram for generating sensitivity functions
[0052] For each identified sensitive function, its control flow graph is generated using the existing tool cfgGen.
[0053] Taking the `withdraw` function as an example, the generated control flow graph includes the flow from the function entry point to each line of code and the relationships between code blocks.
[0054] Get sensitive path set
[0055] Taking the line of code `if (msg.sender.call.value(balance)())` in the `withdraw` function containing the sensitive word `call.value` as an example, this illustrates the process of obtaining the set of sensitive paths:
[0056] S11: Positioning Basic Block
[0057] The line2Block function locates the target code line containing the sensitive word within the basic block Cblock of the control flow graph.
[0058] S12: Reverse traversal to obtain the parent block
[0059] For this basic block Cblock, traverse the control flow graph backward from the current basic block Cblock to obtain all its parent blocks bblocks (1).
[0060] S13: Initialization
[0061] Initialize i = 1.
[0062] S14: Traversal and Judgment
[0063] Iterate through each bblocks(1), add bblocks(1) to cPath, and then determine whether bblocks(1) is the entry point start of the sensitive function withdraw. If not, continue to traverse the control flow graph in reverse from bblocks(1) to obtain all its parent blocks bblocks(2).
[0064] S15: Loop Operation
[0065] Let i = i + 1, and repeat steps S14 and S15 until bblocks(i) is empty. The final output sensitive path set pathSet contains all paths from the entry point of the sensitive function withdraw to the line of code containing the sensitive word call.value.
[0066] The same process applies to the `selfDestructContract` function. By performing a similar operation on the line of code containing the sensitive word `selfdestruct()`, a set of sensitive paths from the function's entry point to the sensitive word can be obtained.
[0067] Through the above steps, we have completed the operation of identifying sensitive functions in the source code of a smart contract based on a given list of sensitive words, and obtaining the set of sensitive paths from the entry point of the sensitive function to the sensitive words.
[0068] This invention identifies sensitive functions in smart contract source code based on a given list of sensitive words, generates a control flow graph, and performs reverse engineering and program slicing analysis. This allows for a comprehensive acquisition of all sensitive paths from the entry point of a sensitive function to the sensitive words. Compared to traditional methods, this approach goes beyond surface-level code analysis, delving into the code's internal workings to more comprehensively cover potentially vulnerable areas, significantly reducing the likelihood of missed detections.
[0069] S2: Generate the program dependency graph of sensitive functions based on the abstract syntax tree and the control flow graph of sensitive functions. For each sensitive path in the sensitive path set, calculate the PageRank value of each node in the sensitive path in the program dependency graph as the weight value of the node in the path, and generate the weighted path corresponding to the sensitive path.
[0070] Preferably, the PageRank value of each node in the computationally sensitive path in the program dependency graph includes:
[0071] S21: Create a size of adjacency matrix and transition probability matrix If the program depends on nodes in the graph To the node If there is an edge, then =1, otherwise =0; nodes in the transition probability matrix To the node State transition probability ,in, The program depends on the number of nodes in the graph; Represents a node The degree of departure;
[0072] S22: Initialize each node Value The initial state of all nodes Values are used in vectors express, ,in, Indicates the first The initial number of nodes value;
[0073] S23: Iteratively calculate each node value:
[0074]
[0075] in, Indicates the damping factor. Indicates the first All nodes after the second iteration value; Represents the transition probability matrix The transpose of the matrix;
[0076] S24: Repeat step S23 until... If the value is less than the set threshold, obtain the value of each node. value.
[0077] In this embodiment, PageRank values are calculated as node weights to reflect the relative importance of each node in the program dependency graph. In smart contract vulnerability detection, important nodes may be more closely related to the occurrence of vulnerabilities. For example, in code related to reentrancy vulnerabilities, certain key function calls or conditional judgment nodes may have relatively high PageRank values. By assigning higher weights to these nodes, more attention can be paid to these key nodes during vulnerability detection, improving the accuracy of detection.
[0078] In this embodiment, the PageRank value is calculated based on a program dependency graph, which reflects the dependencies between nodes in the code. These dependencies are crucial for vulnerability detection because vulnerabilities are often not caused by a single isolated node, but rather by the combined effect of multiple interdependent nodes. By considering the dependencies between nodes, the execution logic of smart contract code can be analyzed more comprehensively, leading to a more accurate identification of potential vulnerabilities.
[0079] In this embodiment, the generated weighted path can more accurately describe the characteristics of sensitive paths. When performing similarity comparisons with the vulnerability signature database, the weighted path signature provides richer and more accurate information, making the detection results more reliable, reducing false positives and false negatives, and further improving the accuracy of smart contract vulnerability detection.
[0080] S3: Construct a smart contract word-vector mapping table using the particle-ball algorithm, and generate a vector representation of each node in the sensitive path based on the word-vector mapping table; fuse the vector representation of each node in the sensitive path with the weighted path information to obtain the weighted path signature;
[0081] Preferably, constructing the smart contract word-vector mapping table includes:
[0082] S301: Collect a large-scale smart contract dataset, input the collected smart contract source code into the trained large language model, obtain the word vector representation of each word in the smart contract source code, and construct an initial word-vector mapping table based on the word vector representation of each word in the source code of the large-scale smart contract dataset;
[0083] In this embodiment, a large-scale smart contract dataset is collected. The source code of the smart contracts is input into a pre-trained large language model (BERT is selected here, but other sequence models can also be used) to obtain the word vector representation of each word. For example, words such as "contract", "Simple", "uint", and "balance" all have corresponding vectors. Based on the vector representations of words in all collected smart contract source code, an initial word-vector mapping table is constructed.
[0084] S302: Treat all word vectors in the initial word-vector mapping table as an initial parent sphere;
[0085] S303: Calculate the distance matrix between all word vectors in the parent ball, and find the two word vectors with the largest distance. and ; Traverse each word vector in the parent particle sphere If word vectors With word vectors The cosine distance is greater than the word vector. With word vectors The cosine distance will then be used to determine the word vectors. and word vectors If word vectors are assigned to the same sub-sphere, otherwise they will be assigned to different sub-spheres. and word vectors They are grouped into the same sub-sphere;
[0086] S304: Calculate the average distance of all word vectors in the two sub-spheres respectively, and sum the average distances of the two sub-spheres according to the number of word vectors in the two sub-spheres to obtain the weighted average distance;
[0087] S305: Determine whether the weighted average distance is less than the average distance of all word vectors in the parent ball. If so, retain two child balls; otherwise, do not retain them.
[0088] S306: Traverse each obtained sub-sphere, use each sub-sphere as the parent sphere in the next iteration, and repeat steps S33 to S36 until the number of spheres no longer changes;
[0089] S307: Update all word vectors within each sphere after partitioning to the center vector of that sphere and re-represent them to obtain the final word-vector mapping table.
[0090] Preferably, the vector representation of each node in the computation sensitive path includes:
[0091] S311: Convert each word in the target code line corresponding to each node in the sensitive path into a vector representation using a word-vector mapping table;
[0092] S312: Average the word vectors of all words in the target code line corresponding to each node to obtain the vector representation of the node.
[0093] Suppose that in the smart contract mentioned above, a sensitive path is detected, and the target code behavior corresponding to one of the nodes is `if (msg.sender.balance >= 10)`. Using a word-vector mapping table, the words "if", "msg.sender.balance", ">=", and "10" are converted into vector representations. The average of these word vectors is then used to obtain the vector representation of that node.
[0094] Preferably, obtaining the weighted path signature by fusing the vector representation and weighted path information of each node in the sensitive path includes: multiplying the vector representation of each node in the sensitive path by its corresponding weight value to obtain a weighted vector for each node; summing the weighted vectors of all nodes to obtain a weighted summation feature vector; and inputting the weighted summation feature vector into the mapping model to generate a fixed-length weighted path signature.
[0095] Preferably, the mapping model includes: a hash algorithm, a multilayer perceptron, or a principal component analysis algorithm.
[0096] In this embodiment, the initial word-vector mapping table is optimized using the grain-sphere algorithm. This algorithm allows for reasonable partitioning and adjustment based on the distance relationships between word vectors, resulting in higher similarity among word vectors within the same grain, thus improving the accuracy and rationality of word vector representation. Compared to word vectors generated directly using a large language model, word vectors processed by the grain-sphere algorithm better reflect the semantic relationships between words, helping to more accurately understand the semantic information of the code in subsequent vulnerability detection. Averaging the vectors of all words in the target code line corresponding to a node comprehensively considers the information of each word in the code line, fully reflecting the characteristics of the node and avoiding the problem of focusing only on a single word while ignoring the overall semantics. Integrating node vector representation with weight information considers both the semantic features of the node itself and its importance in program dependencies, enabling the generated weighted path signature to more comprehensively and accurately represent the characteristics of sensitive paths, enhancing the ability to describe vulnerabilities. Generating fixed-length weighted path signatures through the mapping model allows the characteristics of different sensitive paths to be compared in a unified format, facilitating similarity comparison with vulnerability signature databases and improving the efficiency and accuracy of vulnerability detection.
[0097] S4: Compare the similarity of the weighted path signature of each sensitive path with the weighted path signatures in various vulnerability signature databases. When there are N weighted path signatures in the vulnerability signature database that have a similarity greater than a set threshold with the weighted path signature of the sensitive path, the sensitive path is regarded as a potential vulnerability path of the vulnerability type corresponding to the vulnerability signature database.
[0098] Weighted path signatures are generated for sensitive paths of smart contracts, and there is a vulnerability signature library containing multiple vulnerability types, with a corresponding set of weighted path signatures for each vulnerability type.
[0099] Suppose there is a smart contract. After the previous steps, we have obtained three sensitive paths, which are denoted as SP1, SP2 and SP3 respectively. Their corresponding weighted path signatures are SPS1, SPS2 and SPS3 respectively.
[0100] The vulnerability signature database contains two vulnerability types: reentrancy vulnerabilities (RV) and arithmetic overflow vulnerabilities (AO). The reentrancy vulnerability signature database contains five weighted path signatures: RV_SPS1, RV_SPS2, RV_SPS3, RV_SPS4, and RV_SPS5; the arithmetic overflow vulnerability signature database contains three weighted path signatures: AO_SPS1, AO_SPS2, and AO_SPS3.
[0101] Set the similarity threshold to 0.7 (the similarity can be calculated using methods such as cosine similarity).
[0102] For the weighted path signature SPS1 of SP1:
[0103] The similarity between the signatures and those in the reentrancy vulnerability signature database was compared. The similarity between SPS1 and RV_SPS1 was 0.6, the similarity between SPS1 and RV_SPS2 was 0.55, the similarity between SPS1 and RV_SPS3 was 0.4, the similarity between SPS1 and RV_SPS4 was 0.3, and the similarity between SPS1 and RV_SPS5 was 0.65, all of which were less than 0.7.
[0104] A similarity comparison was performed with signatures in the arithmetic overflow vulnerability signature database. SPS1 showed a similarity of 0.75 with AO_SPS1, 0.3 with AO_SPS2, and 0.2 with AO_SPS3. Since there is one signature (AO_SPS1) with a similarity greater than 0.7 to SPS1, SP1 is considered a potential vulnerability path for the arithmetic overflow vulnerability type.
[0105] For the weighted path signature SPS2 of SP2:
[0106] By comparing the signatures with those in the reentrancy vulnerability signature database, the similarity between SPS2 and RV_SPS3 was calculated to be 0.8, and the similarity with RV_SPS5 was 0.72, with two cases greater than 0.7. Therefore, SP2 is considered a potential vulnerability path of the reentrancy vulnerability type.
[0107] For the weighted path signature SPS3 of SP3:
[0108] The similarity score was compared with all signatures in the reentrancy vulnerability signature database and the arithmetic overflow vulnerability signature database. All similarities were less than 0.7, so SP3 is not considered a potential vulnerability path for any known vulnerability type.
[0109] This invention compares the similarity of the weighted path signature of sensitive paths with signatures in a vulnerability signature database. Based on existing vulnerability feature information, it can accurately determine whether sensitive paths in a smart contract may contain known types of vulnerabilities. In the example above, the comparison successfully identified a potential arithmetic overflow vulnerability in SP1 and a potential reentrancy vulnerability in SP2, helping developers to promptly identify potential security risks. This method, based on signature comparison, significantly reduces the workload and time cost compared to a comprehensive, non-targeted analysis of the entire smart contract. By simply comparing the generated weighted path signature, the existence of potential vulnerabilities can be quickly determined, improving the efficiency of vulnerability detection and making it suitable for large-scale application in real-world projects. As vulnerability research deepens and new vulnerabilities are discovered, simply adding new vulnerability types and their corresponding weighted path signatures to the vulnerability signature database allows this method to be used to detect smart contracts and identify new types of potential vulnerabilities. It has excellent scalability and can adapt to constantly changing security needs. Determining the vulnerability type corresponding to a potential vulnerability path provides developers with a clear vulnerability direction. Developers can use this information to conduct targeted detailed reviews and repairs of relevant code areas in the smart contract, improving the efficiency and accuracy of vulnerability remediation.
[0110] S5: Detect whether the potential vulnerability path in the smart contract source code contains the defense mode for the corresponding vulnerability type. If not, it is determined that the smart contract source code contains this type of vulnerability.
[0111] Suppose that in the previous steps, we identified a potential vulnerability path as a "reentrancy vulnerability" by comparing the similarity of the weighted path signatures. Examples are given below for cases with and without a defense mechanism. Assume that the analysis previously determined that the path containing the code `msg.sender.call.value(10)()` in the `withdraw` function is a potential vulnerability path for reentrancy. A common defense against reentrancy vulnerabilities is to use a state variable to mark whether the function is currently executing, preventing re-entry before the function has finished executing. However, this contract's `withdraw` function does not have such a defense. Therefore, according to step S5, a reentrancy vulnerability is determined to exist in the smart contract's source code. Suppose that the path containing `msg.sender.call.value(10)()` in the `withdraw` function is also identified as a potential vulnerability path for reentrancy. However, this contract uses the state variable `isWithdrawing` to mark whether a withdrawal operation is in progress. This variable is checked at the beginning of the function; if a withdrawal is in progress, the function returns directly to avoid reentrancy; at the end of the function, the variable is reset to false. This method is a defense mechanism against reentrancy vulnerabilities. Therefore, according to step S5, it is determined that there is no reentrancy vulnerability in the source code of the smart contract.
[0112] This embodiment not only relies on identifying potential vulnerability paths but also delves into the existence of corresponding defense modes, avoiding misjudgments of vulnerability existence simply because the code structure or operation mode is similar to known vulnerabilities. In this way, it can more accurately determine whether a specific type of vulnerability truly exists in a smart contract, reducing false positives and providing developers with more reliable vulnerability detection results. During the detection process, if a potential vulnerability path is found but no corresponding defense mode is present, this clearly prompts the developer to improve the code and add appropriate defense mechanisms. If a defense mode exists, it indicates that the developer has considered the relevant security risks and taken measures when writing the code, helping the developer confirm the security of their code. This provides developers with clear guidance for optimizing smart contract code, promoting the improvement of smart contract security. Combining the previous steps of identifying potential vulnerability paths and this step of checking defense modes forms a complete process from vulnerability identification to defense mechanism checking. This comprehensive evaluation method can more comprehensively consider the security of smart contracts, providing richer and deeper security information compared to simple vulnerability detection methods, helping to ensure the stable operation of smart contracts in the blockchain system, protecting user asset security and system reliability.
[0113] Another aspect of the present invention provides a smart contract vulnerability detection device based on particle-sphere computation and weighted path signature similarity, comprising a processor and a memory; the memory is used to store a computer program; the processor is connected to the memory and is used to execute the computer program stored in the memory, so that the smart contract vulnerability detection device based on particle-sphere computation and weighted path signature similarity performs the smart contract vulnerability detection method based on particle-sphere computation and weighted path signature similarity.
[0114] Another aspect of the present invention provides a computer-readable storage medium storing a program, which, when executed by a processor, implements the aforementioned smart contract vulnerability detection method based on particle-sphere computation and weighted path signature similarity.
[0115] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. Any references to memory, storage, databases, or other media used in the embodiments provided in this application can include non-volatile and / or volatile memory. Non-volatile memory can include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memory can include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in various forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), dual data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link DRAM (SLDRAM), RAMbus direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and RAMbus dynamic RAM (RDRAM), etc.
[0116] In summary, this invention identifies sensitive functions in smart contract source code based on a given sensitive word list, generates a control flow graph, and performs reverse program slicing analysis, comprehensively acquiring the set of all sensitive paths from the entry point of the sensitive function to the sensitive words. Compared to traditional methods, this approach goes beyond surface-level code analysis, delving into the code's internals to more comprehensively cover potentially vulnerable areas, significantly reducing the likelihood of missed detections. A program dependency graph is generated based on the abstract syntax tree and the control flow graph of the sensitive functions, and the PageRank value of each node in the sensitive path is calculated as a weight value to generate weighted paths. This process fully considers the dependencies between nodes in the smart contract code and the importance of each node, changing the previous practice of treating all code nodes equally, making vulnerability analysis more accurate and effectively improving detection precision. A smart contract word-vector mapping table is constructed using the grain-sphere algorithm, generating a vector representation for each node in the sensitive path, and integrating weighted path information to obtain a weighted path signature. This innovative representation method not only comprehensively characterizes the features of the smart contract code but also fully considers the relationships between words in the code, overcoming the shortcomings of existing methods that ignore the semantics of custom contract names. By comparing the weighted path signatures of sensitive paths with various vulnerability signature databases, potential vulnerability paths can be identified more accurately, enhancing the detection capability for new and complex vulnerabilities and reducing the false positive rate. After detecting a potential vulnerability path, the smart contract source code is further examined to see if the path contains a defense mode for the corresponding vulnerability type. If not, the vulnerability of that type is determined to exist. This comprehensive detection method goes beyond simply discovering potential vulnerabilities; it also determines whether the smart contract has an effective defense mechanism, providing a more comprehensive and reliable basis for smart contract security assessment.
[0117] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and are not intended to limit it. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can be made to the technical solutions of the present invention without departing from the spirit and scope of the present invention, and all such modifications or substitutions should be covered within the scope of the claims of the present invention.
Claims
1. A smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity, characterized in that, The method comprises the following steps: S1: determining sensitive functions in the smart contract source code according to a given sensitive word list, and generating a control flow graph corresponding to each sensitive function, and performing reverse program slicing analysis to obtain a set of sensitive paths in the control flow graph from the entrance of the sensitive function to the sensitive word, wherein the function in which the sensitive word is located is referred to as a sensitive function; S2: generating a program dependency graph of the sensitive function based on the abstract syntax tree and the control flow graph of the sensitive function, calculating the PageRank value of each node in the sensitive path in the program dependency graph as the weight value of the node in the path for each sensitive path in the set of sensitive paths, and generating a weight path corresponding to the sensitive path; S3: constructing a smart contract word-vector mapping table through a particle ball algorithm, generating a vector representation of each node in the sensitive path based on the word-vector mapping table, and fusing the vector representation of each node in the sensitive path and the weight path information to obtain a weight path signature; The construction of the smart contract word-vector mapping table comprises the following steps: S301: collecting a large-scale smart contract dataset, inputting the collected smart contract source code into a trained large language model to obtain a word vector representation of each word in the smart contract source code, and constructing an initial word-vector mapping table based on the word vector representation of each word in the source code in the large-scale smart contract dataset; S302: regarding all word vectors of the initial word-vector mapping table as an initial parent particle ball; S303: Calculate the distance matrix between all word vectors in the parent grain ball, find the two word vectors with the largest distance and ; traverse each word vector in the parent grain ball , if the cosine distance between the word vector and the word vector is greater than the cosine distance between the word vector and the word vector , then the word vector and the word vector are divided into the same sub-grain ball, otherwise the word vector and the word vector are divided into the same sub-grain ball; S304: calculating the average distance of all word vectors of the two child particle balls respectively, and performing weighted summation on the average distances of the two child particle balls according to the number of word vectors of the two child particle balls to obtain a weighted average distance; S305: determining whether the weighted average distance is less than the average distance of all word vectors of the parent particle ball, and if yes, retaining the two child particle balls, and otherwise not retaining the two child particle balls; S306: traversing each child particle ball obtained to take each child particle ball as a parent particle ball in the next round of iteration, and repeating steps S33 to S36 until the number of particle balls no longer changes; S307: updating all word vectors in each particle ball after division to the center vector of the particle ball for re-representation to obtain a final word-vector mapping table; The fusion of the vector representation of each node in the sensitive path and the weight path information to obtain the weight path signature comprises: multiplying the vector representation of each node in the sensitive path by the corresponding weight value to obtain a weighted vector of each node; summing all weighted vectors of the nodes to obtain a weighted summation feature vector; and inputting the weighted summation feature vector into a mapping model to generate a fixed-length weight path signature; S4: comparing the weight path signature of each sensitive path with the weight path signatures in the vulnerability signature library respectively, and when there are N weight path signatures in the vulnerability signature library that have a similarity greater than a set threshold with the weight path signature of the sensitive path, the sensitive path is regarded as a potential vulnerability path of the corresponding vulnerability type in the vulnerability signature library; S5: detecting whether the potential vulnerability path contains a defense mode of the corresponding vulnerability type in the smart contract source code, and if not, determining that the smart contract source code contains the vulnerability of the type.
2. The smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity according to claim 1, characterized in that, The obtaining of the set of sensitive paths from the sensitive function entry to the sensitive word in the control flow graph comprises: S11: for each target code line containing a sensitive word in the sensitive function, locate the basic block in which the function is located in the control flow graph function locates its in the basic block of the control flow graph ; S12: For each basic block containing the target line of code from the current basic block traverse the control flow graph backwards, getting all of its parent blocks ; S13: and initialize ; S14: Iterate through each ,Will join in and judge Is it the entry point of a sensitive function? If so, then join in and clear Conversely, from Traverse the control flow graph in reverse order to obtain all its parent blocks. ; S15: Let , repeat steps S14-S15 until is empty, output the set of sensitive paths . 3.The smart contract vulnerability detection method based on granular computing and weight path signature similarity according to claim 1, characterized in that, The calculation of the PageRank value of each node in the sensitive path in the program dependency graph comprises: S21: Create a size of adjacency matrix and transition probability matrix If the program depends on nodes in the graph To the node If there is an edge, then =1, otherwise =0; nodes in the transition probability matrix To the node State transition probability ,in, The program depends on the number of nodes in the graph; Represents a node The degree of departure; S22: Initialize each node Value The initial state of all nodes Values are used in vectors express, ,in, Indicates the first The initial number of nodes value; S23: iteratively calculate the value of each node value: wherein, denotes a damping factor, denotes the value of all nodes after the th iteration; denotes the transpose matrix of the transition probability matrix . S24: repeatedly performing step S23 until less than a set threshold, obtaining a value of each node value.
4. The smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity according to claim 1, characterized in that, The calculation of the vector representation of each node in the sensitive path comprises: S311: converting each word of the target code line corresponding to each node in the sensitive path into a vector representation through a word-vector mapping table; S312: averaging the word vectors of all words of the target code line corresponding to each node to obtain the vector representation of the node.
5. The smart contract vulnerability detection method based on granular ball calculation and weight path signature similarity according to claim 1, characterized in that, The mapping model comprises a hash algorithm, a multi-layer perception machine or a principal component analysis algorithm.
6. An intelligent contract vulnerability detection device based on granular ball calculation and weight path signature similarity, characterized in that, The device comprises a processor and a memory; the memory is used to store a computer program; the processor is connected with the memory and is used to execute the computer program stored in the memory, so that the device executes the method.
7. A computer-readable storage medium storing a program, characterized in that, The program is executed by the processor to implement the method.
Citation Information
Patent Citations
Intelligent contract multi-vulnerability detection method and system based on source code graph representation learning
CN113360915A
Software supply chain security assessment method and system based on static analysis
CN118364462A