Intelligent contract vulnerability detection method and system based on semantic graph reasoning and context learning
By constructing semantic graph and context learning methods, combined with graph convolutional neural network and large language model, the accuracy and efficiency of existing smart contract vulnerability detection methods are solved, and more efficient vulnerability detection is achieved.
Patent Information
- Application Number
- CN202510496494.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-04-21
- Publication Date
- 2025-07-25
AI Technical Summary
Existing smart contract vulnerability detection methods are difficult to identify complex or new types of vulnerabilities, and have high false positive rates or excessive calculation overhead. Deep learning methods rely on large-scale annotation data, have limited generalization capabilities, and large language models lack inference capabilities when dealing with complex contract logic.
Using a method based on semantic graph inference and context learning, by constructing semantic graph representation, a graph convolution neural network is used to generate graph embedding vectors, a large language model is used to detect vulnerabilities, a thinking chain prompt template is used to guide inference, and a context learning is combined with vulnerability definition, semantic graph and similar graph.
It improves the accuracy and efficiency of smart contract vulnerability detection, reduces time cost, enhances the inference ability of complex contract logic, and provides higher classification accuracy.
Smart Images

Figure CN120372630A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to an intelligent contract vulnerability detection method and system based on semantic graph reasoning and context learning, and belongs to the field of intelligent contract security. Background Art
[0002] With the development of blockchain technology, intelligent contracts have been widely used in many industries such as finance, supply chain, healthcare, and insurance. Especially in the field of decentralized finance, through the automated execution of predefined protocols, it provides an efficient, transparent, and trustless execution mechanism for various financial transactions. This characteristic has enabled intelligent contracts to rapidly develop into the core infrastructure of numerous decentralized applications and financial services. However, once an intelligent contract is deployed, it cannot be changed, and the code is completely public. Although this immutability enhances the transparency and credibility of the contract, it also brings serious security risks. Once there are vulnerabilities or design flaws in the intelligent contract, attackers may maliciously exploit these vulnerabilities to obtain huge benefits, thereby causing significant economic losses. For example, the frequent occurrence of DeFi vulnerability attack events has not only led to huge losses of platform funds but also had a great impact on the stability of the entire blockchain ecosystem and user trust. Therefore, how to effectively detect and repair potential vulnerabilities in intelligent contracts has become a key task to ensure the security of the blockchain ecosystem. Intelligent contract vulnerability detection refers to analyzing and evaluating the code structure, execution logic, and data flow of intelligent contracts to identify potential security vulnerabilities to prevent malicious attacks and financial losses. Currently, common vulnerability detection methods mainly include static analysis and deep learning methods. Traditional static analysis and symbolic execution methods rely on predefined rules and pattern matching, which can discover known types of vulnerabilities but are difficult to identify complex or new types of vulnerabilities, and there are problems such as high false positive rates or excessive computational overhead. Although deep learning methods have improved the automation level of vulnerability detection, they have a high dependence on large-scale labeled data, limited generalization ability, and it is difficult to explain the detection results.
[0003] In recent years, large language models (LLMs) have made significant progress in code understanding and automatic reasoning, and some studies have begun to explore the application of LLMs in intelligent contract vulnerability detection. However, since LLMs are mainly trained on general text data and lack professional knowledge in the field of intelligent contracts, their vulnerability detection capabilities have certain limitations. In addition, LLMs have insufficient reasoning capabilities when dealing with complex contract logic and are prone to misjudgment or omission of vulnerabilities. Summary of the Invention
[0004] Objective of the Invention: Aiming at the deficiencies of the prior art, the objective of the present invention is to propose an intelligent contract vulnerability detection method and system based on semantic graph reasoning and context learning, which can combine structured code analysis, context learning, and reasoning capabilities of large language models to improve the accuracy of vulnerability detection, reduce the time cost, and improve the detection efficiency.
[0005] Technical Solution: To achieve the above objective of the invention, the present invention adopts the following technical solutions:
[0006] An intelligent contract vulnerability detection method based on semantic graph reasoning and context learning, comprising the following steps:
[0007] Collect an annotated intelligent contract dataset, preprocess the dataset, and remove irrelevant information such as comments;
[0008] Construct a semantic graph representation. Divide key nodes and ordinary nodes according to the vulnerability type, label different vulnerabilities for nodes, mark the code operations that may cause vulnerabilities as key nodes, and mark other operations as ordinary nodes. Extract function call information such as code control flow and data flow, and mark it as an edge in chronological order to construct a contract graph representation. The contract graph is used to generate a semantic graph, and node interpretation and edge interpretation are performed using the contract graph interpretation to endow the contract graph with semantic information, and a semantic graph containing clear semantic information is constructed;
[0009] Apply the contract graph to train a graph convolutional neural network, learn the contract graph structure information, generate a graph embedding vector representation, and store the processed graph embedding vector in the FAISS vector library, which is used for similar contract query;
[0010] Apply the cosine similarity algorithm to find the contract most similar to the retrieval target contract in the vector library, and construct a thought chain prompt in combination with the vulnerability definition, semantic graph, similar graph, and label. The thought chain prompt guides the large language model to think step by step. The definition and semantic graph are used for model reasoning, and the similar graph and its label are used for context learning;
[0011] Input the thought chain prompt into the large language model for reasoning, apply semantic graph reasoning and context learning, and finally output the detection result.
[0012] Furthermore, constructing the semantic graph representation includes two steps:
[0013] Construct a contract graph, divide key nodes and ordinary nodes according to vulnerability types, label nodes for different vulnerabilities. For re-entrancy vulnerabilities, key nodes include calls related to call.value and variables involved in balance operations. For timestamp dependency vulnerabilities, key nodes focus on block.timestamp and variables interacting with it. For integer overflow vulnerabilities, key nodes consist of variables participating in arithmetic operations. For delegate call vulnerabilities, key nodes cover the low-level call method delegatecall and variables operated in the method. Other nodes are marked as ordinary nodes. Extract function call information such as code control flow and data flow, and mark it as an edge in chronological order. The edges of the contract graph are constructed based on specific dependency relationships and combined with the interaction logic between code units. The types of edges mainly include control flow, data flow edges, forward edges, and backward edges, which are used to describe different logical relationships in the contract respectively. Control flow edges are used to describe the execution logic of the contract, including conditional judgments, loop structures, and exception handling. Data flow edges are used to represent variable assignments and data access. Forward edges are used to represent the natural execution order of the code, and backward edges are used to represent interactions with fallback functions;
[0014] Contract graph interpretation, conduct node interpretation of the contract graph, identify core operation nodes in the contract graph, analyze according to function calls, state modifications, and access control privilege attributes, and assign semantic representations to key nodes. The calculation formula is as follows:
[0015] L(n) = f(O(n), A(n)
[0016] where O(n) represents the specific operation content of the node, such as function calls, arithmetic operations, etc.; A(n) represents the access control of the node, such as public, private, internal;
[0017] Conduct edge interpretation of the contract graph, identify edges associated with key nodes in chronological order of the edges, and assign semantic representations to the edges according to the dependency relationships of the edges. The calculation formula is as follows:
[0018] L(e) = f(L(n i ), L(n j ), A(e))
[0019] where n i and n j represent the source node and the target node respectively, and A(e) represents the attribute of the edge.
[0020] Furthermore, the extraction of graph embedding vectors is divided into three stages:
[0021] Adjacency matrix normalization: Normalize the constructed contract graph, calculate the node degrees, add self-loop information so that each node can retain the original information when updating its own features, and adjust the data distribution through the degree matrix, thereby ensuring the balance of information propagation, improving the stability of model training, and ensuring the effective fusion of information of different nodes;
[0022] Feature aggregation and update: The model is updated layer by layer. Each layer is based on the node features of the previous layer and combines the adjacency relationship to weight and integrate the information, capture the local patterns of the graph, and gradually fuse the global information, making the final node representation more semantic and discriminative;
[0023] Graph embedding vector generation: Pool the information of the entire graph into a fixed-dimensional vector by taking the maximum value of all node features. This vector synthesizes the local and global feature information, can express the structure of the graph and the relationship between nodes more comprehensively, and store the vector in the FAISS vector library.
[0024] Furthermore, the method for constructing the chain of thought prompt template is as follows:
[0025] Similar graph query: Apply the cosine similarity algorithm to query the most similar contract graph in the FAISS vector library, and obtain its label and semantic graph representation according to the index. The calculation formula is as follows:
[0026]
[0027] where, z i and z j are the embedding vectors of two contract graphs respectively. |||| represents the Euclidean norm of the vector, · represents the dot product operation. The value of cosine similarity ranges from -1 to 1. The closer the value is to 1, the more similar the directions of the two graphs are in the embedding space, indicating higher similarity;
[0028] Combined prompt information: Based on the Solidity official documentation, obtain the definition of smart contract vulnerability types, and construct a chain of thought prompt for four-step thinking, including Step 1: Vulnerability definition knowledge, Step 2: Learn semantic graphs, Step 3: Compare similar cases, and Step 4: Make a judgment.
[0029] An intelligent contract vulnerability detection system based on semantic graph reasoning and context learning, including:
[0030] Data collection and preprocessing module: Collect the labeled intelligent contract dataset, preprocess the dataset, and remove irrelevant information such as comments;
[0031] The semantic graph construction module constructs a semantic graph representation, divides key nodes and ordinary nodes according to the vulnerability type, labels different vulnerabilities for nodes, marks the code operations that may cause vulnerabilities as key nodes, and marks other operations as ordinary nodes, extracts function call information such as code control flow and data flow, marks them as edges in chronological order, constructs a contract graph representation, the contract graph is used to generate a semantic graph, applies contract graph interpretation for node interpretation and edge interpretation, endows the contract graph with semantic information, and constructs a semantic graph containing explicit semantic information;
[0032] The graph embedding vector extraction module applies the contract graph to train a graph convolutional neural network, learns the contract graph structure information, generates a graph embedding vector representation, and stores the processed graph embedding vector in the FAISS vector library, and the vector library is used for similar contract queries;
[0033] The thought chain prompt construction module applies the cosine similarity algorithm to find the contract most similar to the retrieved target contract in the vector library, constructs a thought chain prompt by combining the vulnerability definition, semantic graph, similar graph and labels, the thought chain prompt guides the large language model to think step by step, the definition and semantic graph are used for model reasoning, and the similar graph and its labels are used for context learning;
[0034] And the vulnerability detection module inputs the thought chain prompt into the large language model for reasoning, applies semantic graph reasoning and context learning, and finally outputs the detection result.
[0035] A computer system includes a memory, a processor, and a computer program / instructions stored on the memory and executable on the processor. When the computer program / instructions are executed by the processor, the steps of the intelligent contract vulnerability detection method based on semantic graph reasoning and context learning are implemented.
[0036] A computer program product includes computer program / instructions. When the computer program / instructions are executed by the processor, the steps of the intelligent contract vulnerability detection method based on semantic graph reasoning and context learning are implemented.
[0037] Beneficial effects: The present invention combines a semantic graph containing semantic information and structural information with similar intelligent contracts, uses a thought chain prompt template to splice different information, and adopts a large language model for reasoning and context learning. It can automatically detect potential vulnerability patterns from the semantic graph, and can learn similar contracts to enhance domain knowledge. At the same time, the thought chain prompt guides the large language model to think step by step, enhances the reasoning accuracy, and provides an intelligent contract vulnerability detection method with higher classification accuracy. Brief Description of the Drawings
[0038] Figure 1 It is the overall process schematic diagram of the embodiment of the present invention.
[0039] Figure 2 It is a schematic diagram of the edge construction rule of the contract graph in the embodiment of the present invention.
[0040] Figure 3 It is a schematic diagram of the contract graph interpretation process in the embodiment of the present invention.
[0041] Figure 4 It is a schematic diagram of the thought chain prompt in the embodiment of the present invention. Specific implementation manners
[0042] The following further clarifies the present invention in conjunction with specific embodiments. It should be understood that these embodiments are only used to illustrate the present invention and not to limit the scope of the present invention. After reading the present invention, those skilled in the art's various equivalent modifications of the present invention all fall within the scope defined by the appended claims of this application.
[0043] As Figure 1 shown, an intelligent contract vulnerability detection method based on semantic graph reasoning and context learning provided by an embodiment of the present invention includes the following steps:
[0044] (1) Data collection and preprocessing: Collect the labeled intelligent contract data set from the public platform, preprocess the data set, and remove irrelevant information such as comments and blank lines;
[0045] (2) Semantic graph construction: First, divide the key nodes and ordinary nodes according to the vulnerability type, label different vulnerabilities for the nodes, mark the code operations that may cause vulnerabilities as key nodes, and mark other operations as ordinary nodes. Extract function call information such as code control flow and data flow, and mark it as an edge in chronological order; On the basis of the contract graph, further introduce semantic information, apply contract graph interpretation for node interpretation and edge interpretation, bind semantic labels to each node and edge, and construct a semantic graph containing clear semantic information;
[0046] (3) Graph embedding vector extraction: Use the graph convolutional neural network to train the constructed contract graph to learn the structural relationship and semantic dependence between nodes. The graph neural network outputs the embedding vector of the entire graph to represent the characteristics of the entire contract. Use global pooling to generate the graph-level vector, and uniformly store the generated vector in the efficient similarity search tool library FAISS of Facebook to achieve fast similarity retrieval of vectorization;
[0047] (4) Thought chain prompt construction: For the contract to be detected, extract its graph embedding vector, retrieve the most similar contract graph in the FAISS vector library, and obtain its corresponding vulnerability type and semantic graph structure. Combine the vulnerability definition, semantic graph, similar graph and label to construct a thought chain prompt, and the thought chain prompt guides the large language model to think step by step;
[0048] (5) Input the constructed chain-of-thought prompt into the large language model for reasoning and in-context learning. Apply semantic graph reasoning and in-context learning, and finally output the detection result.
[0049] In step (1), the specific content of data collection and preprocessing is as follows:
[0050] The collected smart contract dataset includes 4 types of vulnerability types, namely reentrancy vulnerability, timestamp vulnerability, integer overflow vulnerability, and delegate call vulnerability, and 1,093 contracts. The dataset source is the Github public dataset Smart Contract datasetResource2. These four types of vulnerabilities are common problems in smart contract security and are directly related to real-world attack losses. Data preprocessing includes removing comments, blank lines, and meta-information unrelated to vulnerabilities in the source code, and retaining the core code structure and semantic information.
[0051] In step (2), construct a contract graph for the collected smart contract dataset to be classified. The rules for constructing the edges of the contract graph are as Figure 2 shown. The specific steps are as follows:
[0052] Taking each contract as a unit, the nodes represent operations at the statement level. Any operation related to the root cause of the vulnerability is marked as a "critical node", and the rest are "ordinary nodes". For the reentrancy vulnerability, the critical nodes include calls related to call.value and variables involved in balance operations. For the timestamp dependency vulnerability, the critical nodes are concentrated on block.timestamp and variables interacting with it. For the integer overflow vulnerability, the critical nodes are composed of variables participating in arithmetic operations. For the delegate call vulnerability, the critical nodes cover the low-level call method delegatecall and variables operated in the method. Other nodes are marked as ordinary nodes. All code operations that do not conform to the above definition of critical nodes, such as internal operations, ordinary assignments, event triggers, etc., are marked as ordinary nodes to ensure the overall context integrity. The edges of the contract graph are constructed based on specific dependency relationships and combined with the interaction logic between code units. The types of edges mainly include control flow, data flow edges, forward edges, and backward edges, which are used to describe different logical relationships in the contract respectively. Control flow edges are used to describe the execution logic of the contract, including conditional judgments, loop structures, and exception handling. Data flow edges are used to represent variable assignments and data access. Forward edges are used to represent the natural execution order of the code, and backward edges are used to represent the interaction with the fallback function. All edges are directed edges to reflect the dependency or call order.
[0053] In step (2), the contract graph interpretation process is as Figure 3 shown. The specific steps are as follows:
[0054] Explanation of contract graph nodes, mainly focusing on the identification and semantic assignment of core operation nodes. In the contract graph, each node represents a basic code unit, such as function calls, variable assignments, arithmetic operations, or logical judgments. By analyzing the operation behaviors and access control attributes of these nodes, semantic tags of the nodes are constructed, and semantic representations are assigned to key nodes. The calculation formula is as follows:
[0055] L(n) = f(O(n), A(n)
[0056] Where O(n) represents the specific operation content of the node, such as function calls, arithmetic operations, etc.; A(n) represents the access control of the node, such as public, private, internal;
[0057] Explanation of contract graph edges, focusing on the semantic modeling of the dependency relationships and interaction paths between nodes. First, the edges are sorted according to the execution time order, the paths associated with key nodes are identified, and comprehensive analysis is carried out by combining the semantic information of the two nodes connected by the edge and the attributes of the edge itself to form the semantic representation of the edge. The calculation formula is as follows:
[0058] L(e) = f(L(n i ), L(n j ), A(e))
[0059] Where n i and n j represent the source node and the target node respectively. A(e) represents the attribute of the edge.
[0060] In step (3), graph embedding vector extraction is performed. The specific steps are divided into three stages:
[0061] Adjacency matrix normalization: The constructed contract graph is normalized, the node degrees are calculated, self-loop information is added, so that each node can retain the original information when updating its own features, and the data distribution is adjusted through the degree matrix, thereby ensuring the balance of information propagation, improving the stability of model training, and ensuring the effective fusion of information of different nodes;
[0062] Feature aggregation and update: In each layer of the graph neural network, the node collects the feature information from its neighbor nodes and combines it with its own features for update. Different nodes propagate their semantic information according to the graph structure, gradually building an understanding of the local and global environments. As the number of network layers deepens, the scope of information propagation also continuously expands. Nodes that can initially only perceive the local structure can finally perceive the context structure related to themselves in the entire graph. Through multiple layers of aggregation processes, the feature representations of the nodes gradually transform from the original and shallow-structured features to higher-level and more semantic representations;
[0063] Graph embedding generation: In the pooling operation, the most representative eigenvalue is selected from all nodes on each feature dimension, and the information of the entire graph is compressed into a vector with a fixed dimension. The pooling process is carried out by taking the maximum value of all node features. This vector synthesizes local and global feature information and can express the structure of the graph and the relationships between nodes more comprehensively. This vector is stored in a vector library constructed based on FAISS to achieve efficient vector similarity search. FAISS supports large-scale vector storage and can be used to quickly locate the graph representation most similar to the contract to be analyzed during the inference stage, thereby assisting in the detection of similar vulnerabilities.
[0064] In step (4), the chain of thought prompt is as Figure 4 shown, and the specific construction steps are as follows:
[0065] Similar graph query: Apply the cosine similarity algorithm to query the most similar contract graph in the FAISS vector library, and obtain its label and semantic graph representation according to the index. The calculation formula is as follows:
[0066]
[0067] where z i and z j are the embedding vectors of two contract graphs respectively, |||| represents the Euclidean norm of the vector, · represents the dot product operation, and the value of the cosine similarity ranges between -1 and 1. The closer the value is to 1, the closer the directions of the two graphs in the embedding space are, indicating higher similarity;
[0068] Combined prompt information: Based on the Solidity official documentation, obtain the definition of smart contract vulnerability types and construct a chain of thought prompt for four-step thinking. The entire prompt process is divided into four logical steps, focusing on vulnerability definition understanding, graph structure perception, similar case comparison, and comprehensive judgment analysis respectively;
[0069] For the convenience of description, we use a smart contract vulnerability detection method based on semantic graph reasoning and context learning to detect the 4 types of smart contract vulnerability data collected. The process is as follows:
[0070] (1) Data collection and preprocessing. A total of 4 types of labeled smart contract vulnerability data are collected. The number of samples of each type is shown in Table 1. At the same time, data preprocessing is carried out to remove irrelevant information such as comments and blank lines in the source code;
[0071] (2) Semantic graph construction. Key node extraction, ordinary node extraction, and edge extraction are carried out to generate a contract graph from the smart contract source code, and the contract graph is interpreted to generate a semantic graph;
[0072] (4) Graph embedding vector extraction: According to the 1093 contracts after data preprocessing, divide them according to different vulnerability types, randomly divide the data of each vulnerability type into 8 training sets and 2 test sets, use the samples in the 8 training sets to carry out model training, perform feature extraction, obtain graph embedding vectors, and store them in the FAISS vector library;
[0073] (5) Chain-of-thought prompt construction: Retrieve the most similar unique contract graph in the FAISS vector library, and construct chain-of-thought prompts by combining vulnerability definitions, semantic graphs, similar graphs, and labels;
[0074] (6) Vulnerability detection: Use the large language model Gemini for reasoning and context learning, input the constructed chain-of-thought prompts into Gemini, output the detection results, and repeat the experiment three times to count the results.
[0075] An intelligent contract vulnerability detection method is constructed through the above steps. Apply the detection method to the data samples in the test set for detection. For the 4 types of vulnerability types in the test set, the final detection effects are shown in Table 2, where the classification effects are evaluated using accuracy, precision, recall, and F1 value. TP (True Positive) is the number of samples that are determined to have vulnerabilities and actually have vulnerabilities, TN (True Negative) is the number of samples that are determined to have no vulnerabilities and actually have no vulnerabilities, FP (False Positive) is the number of samples that are determined to have vulnerabilities but actually have no vulnerabilities, and FN (False Negative) is the number of samples that are determined to have no vulnerabilities but actually have vulnerabilities.
[0076] Accuracy ACC represents the proportion of the number of correctly classified samples to the total number of samples, and the calculation formula is:
[0077]
[0078] Precision represents the ability of the model to accurately find positive samples, and the calculation formula is:
[0079]
[0080] Recall represents the ability of the model to find all positive samples, and the calculation formula is:
[0081]
[0082] The F1 value is a comprehensive consideration index of precision and recall, and the calculation formula is:
[0083]
[0084] Table 1 Information of 4 types of vulnerability samples
[0085] Vulnerability type Number of vulnerabilities Number of non - vulnerabilities Re - entry 73 200 Timestamp 179 170 Integer overflow 90 185 Delegate call 63 134
[0086] Table 2 Vulnerability Detection Results
[0087] Accuracy (%) Precision (%) Recall (%) F1 - score (%) Re - entry 90.30% 82.32% 82.22% 82.21% Timestamp 72.86% 69.74% 83.33% 75.91% Integer overflow 96.36% 90.00% 100% 94.74% Delegate call 77.50% 66.67% 61.54% 64.00%
[0088] As can be seen from Table 2, the large language model vulnerability detection method of the embodiments of the present invention can effectively improve the accuracy of intelligent contract vulnerability detection.
[0089] Based on the same inventive concept, an intelligent contract vulnerability detection system provided by an embodiment of the present invention includes: a data collection and preprocessing module for collecting an annotated intelligent contract data set and preprocessing the data set; a contract graph construction module for constructing a contract graph representation, marking code operations that may cause vulnerabilities as key nodes, and other operations as ordinary nodes, extracting function call information such as code control flow and data flow, and marking them as edges in chronological order; a semantic graph construction module for constructing a semantic graph representation, applying contract graph interpretation for node interpretation and edge interpretation, and endowing the contract graph with semantic information; a graph embedding vector extraction module for constructing a graph convolutional neural network model, extracting features using a training data set, learning the contract graph structure information, generating a graph embedding vector representation, and storing the processed graph embedding vector in a FAISS vector library; a thought chain prompt construction module for constructing a thought chain prompt template, finding the contract in the vector library that is most similar to the retrieved target contract, and constructing a thought chain prompt in combination with the vulnerability definition, semantic graph, similar graph, and labels, where the thought chain prompt guides the large language model to think step by step; and a vulnerability detection module for inputting the thought chain prompt into the large language model for reasoning and outputting the detection result.
[0090] For the specific working processes of the above-described modules, reference may be made to the corresponding processes in the foregoing method embodiments, which will not be elaborated herein. The division of the modules is only a logical function division, and there may be other division methods in actual implementation. For example, multiple modules may be combined or integrated into another system.
[0091] Based on the same inventive concept, an embodiment of the present invention provides a computer system, including a memory, a processor, and a computer program / instruction stored on the memory and executable on the processor, where when the computer program / instruction is executed by the processor, the steps of the intelligent contract vulnerability detection method based on semantic graph reasoning and context learning are implemented.
[0092] Based on the same inventive concept, an embodiment of the present invention provides a computer program product, including a computer program / instruction, where when the computer program / instruction is executed by the processor, the steps of the intelligent contract vulnerability detection method based on semantic graph reasoning and context learning are implemented.
[0093] Those skilled in the art can understand that the technical solution of the present invention, in essence or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to enable a computer system (which can be a personal computer, a server, or a network device, etc.) to execute all or part of the steps of the method described in the embodiments of the present invention. The storage medium includes: various media that can store computer programs such as USB flash drives, mobile hard disks, read-only memory ROM, random access memory RAM, magnetic disks, or optical discs.
[0094] Although the present invention has been illustrated and described with respect to the preferred embodiments, those skilled in the art should understand that various changes and modifications can be made to the present invention as long as they do not exceed the scope defined by the claims of the present invention.
Claims
1. An intelligent contract vulnerability detection method based on semantic graph reasoning and context learning, characterized in that The method includes the following steps: Collect an annotated smart contract dataset, preprocess the dataset, and remove irrelevant information such as comments; Construct a semantic graph representation. Divide key nodes and ordinary nodes according to vulnerability types, label different vulnerabilities for nodes, mark code operations that may lead to vulnerabilities as key nodes, and mark other operations as ordinary nodes. Extract function call information such as code control flow and data flow, mark it as an edge in chronological order, construct a contract graph representation. The contract graph is used to generate a semantic graph, apply contract graph interpretation for node interpretation and edge interpretation, endow the contract graph with semantic information, and construct a semantic graph containing explicit semantic information; Apply the contract graph to train a graph convolutional neural network, learn the contract graph structure information, generate a graph embedding vector representation, and store the processed graph embedding vector in a FAISS vector library. The vector library is used for similar contract queries; Apply the cosine similarity algorithm to find the contract most similar to the retrieval target contract in the vector library, and construct a chain of thought prompt by combining the vulnerability definition, semantic graph, similar graph, and labels. The chain of thought prompt guides the large language model to think step by step. The definition and semantic graph are used for model reasoning, and the similar graph and its labels are used for context learning; Input the chain of thought prompt into the large language model for reasoning, apply semantic graph reasoning and context learning, and finally output the detection result.
2. The intelligent contract vulnerability detection method based on semantic graph reasoning and context learning according to claim 1, wherein The construction of the semantic graph representation includes two steps: Construct a contract graph. Divide key nodes and ordinary nodes according to vulnerability types, label different vulnerabilities for nodes. For reentrancy vulnerabilities, key nodes include calls related to call.value and variables involved in balance operations. For timestamp dependency vulnerabilities, key nodes focus on block.timestamp and variables interacting with it. For integer overflow vulnerabilities, key nodes consist of variables participating in arithmetic operations. For delegate call vulnerabilities, key nodes cover the low-level call method delegatecall and variables operated in the method. Other nodes are marked as ordinary nodes. Extract function call information such as code control flow and data flow, mark it as an edge in chronological order. The edges of the contract graph are constructed based on specific dependency relationships and combined with the interaction logic between code units. The types of edges mainly include control flow, data flow edges, forward edges, and fallback edges, which are used to describe different logical relationships in the contract respectively. Control flow edges are used to describe the execution logic of the contract, including conditional judgment, loop structure, and exception handling. Data flow edges are used to represent variable assignment and data access. Forward edges are used to represent the natural execution order of the code. Fallback edges are used to represent the interaction with the fallback function; Contract graph interpretation. Conduct contract graph node interpretation, identify core operation nodes in the contract graph, analyze them according to function call, state modification, and access control privilege attributes, and endow key nodes with semantic representations. The calculation formula is as follows: L(n) = f(O(n), A(n)) where O(n) represents the specific operation content of the node, such as function call, arithmetic operation, etc.; A(n) represents the access control of the node, such as public, private, internal; Perform contract graph edge interpretation, identify the edges associated with key nodes according to the chronological order of the edges, and assign semantic representations to the edges based on the edge dependencies. The calculation formula is as follows: L(e) = f(L(n i ), L(n i ), A(e)) where n i and n j represent the source node and the target node respectively, and A(e) represents the attribute of the edge.
3. An intelligent contract vulnerability detection method based on semantic graph reasoning and context learning according to claim 1, characterized in that, The extraction of graph embedding vectors is divided into three stages: Adjacency matrix normalization: Normalize the constructed contract graph, calculate the node degrees, add self-loop information so that each node can retain the original information when updating its own features, and adjust the data distribution through the degree matrix, thereby ensuring the balance of information propagation, improving the stability of model training, and ensuring the effective fusion of information of different nodes; Feature aggregation and update: The model is updated layer by layer. Each layer is based on the node features of the previous layer and combines the adjacency relationship to weight and integrate the information, capture the local patterns of the graph, and gradually fuse the global information, making the final node representation more semantic and distinguishable; Graph embedding vector generation: Pooling is performed by taking the maximum value of all node features to compress the information of the entire graph into a vector with a fixed dimension. This vector synthesizes the local and global feature information, can more comprehensively express the structure of the graph and the relationships between nodes, and stores the vector in the FAISS vector library.
4. An intelligent contract vulnerability detection method based on semantic graph reasoning and context learning according to claim 1, characterized in that The method for constructing the chain of thought prompt is as follows: Similar graph query: Apply the cosine similarity algorithm to query the most similar contract graph in the FAISS vector library, and obtain its label and semantic graph representation according to the index. The calculation formula is as follows: where z i and z j are the embedding vectors of two contract diagrams respectively, |||| represents the Euclidean norm of the vectors, · represents the dot product operation, and the value of the cosine similarity ranges between -1 and 1. The closer the value is to 1, the closer the directions of the two diagrams in the embedding space, indicating a higher similarity; Combine prompt information: Based on the official Solidity documentation, obtain the definition of smart contract vulnerability types, and construct a chain of thought prompt for four-step thinking, including Step 1: Vulnerability definition knowledge, Step 2: Learn the semantic graph, Step 3: Compare similar cases, and Step 4: Make a judgment.
5. An intelligent contract vulnerability detection system based on semantic graph reasoning and context learning, characterized in that: Including: Data collection and preprocessing module: Collect the labeled smart contract dataset, preprocess the dataset, and remove irrelevant information such as comments; Semantic graph construction module: Construct a semantic graph representation, divide key nodes and ordinary nodes according to the vulnerability types, label different vulnerabilities for nodes, mark the code operations that may cause vulnerabilities as key nodes, and mark other operations as ordinary nodes. Extract function call information such as code control flow and data flow, mark it as an edge in chronological order, construct a contract graph representation. The contract graph is used to generate a semantic graph, and contract graph interpretation is applied for node interpretation and edge interpretation to endow the contract graph with semantic information and construct a semantic graph containing clear semantic information; Graph embedding vector extraction module: Apply the contract graph to train a graph convolutional neural network to learn the contract graph structure information, generate a graph embedding vector representation, and store the processed graph embedding vector in the FAISS vector library. The vector library is used for similar contract queries; Chain of thought prompt construction module: Apply the cosine similarity algorithm to find the contract most similar to the retrieved target contract in the vector library, and construct a chain of thought prompt by combining the vulnerability definition, semantic graph, similar graph, and label. The chain of thought prompt guides the large language model to think step by step. The definition and semantic graph are used for model reasoning, and the similar graph and its label are used for context learning; And a vulnerability detection module: Input the chain of thought prompt into the large language model for reasoning, apply semantic graph reasoning and context learning, and finally output the detection result.
6. An intelligent contract vulnerability detection system based on semantic graph reasoning and context learning according to claim 5, characterized in that The semantic graph construction module includes the following two steps: Construct a contract graph, divide key nodes and ordinary nodes according to vulnerability types, label different vulnerabilities for nodes. For reentrancy vulnerabilities, key nodes include calls related to call.value and variables involved in balance operations. For timestamp dependency vulnerabilities, key nodes focus on block.timestamp and variables interacting with it. For integer overflow vulnerabilities, key nodes consist of variables participating in arithmetic operations. For delegate call vulnerabilities, key nodes cover the low-level call method delegatecall and variables operated in the method. Other nodes are marked as ordinary nodes. Extract function call information such as code control flow and data flow, and mark it as an edge in chronological order. The edges of the contract graph are constructed based on specific dependency relationships and combined with the interaction logic between code units. The types of edges mainly include control flow edges, data flow edges, forward edges, and backward edges, which are used to describe different logical relationships in the contract respectively. Control flow edges are used to describe the execution logic of the contract, including conditional judgments, loop structures, and exception handling. Data flow edges are used to represent variable assignments and data accesses. Forward edges are used to represent the natural execution order of the code. Backward edges are used to represent interactions with the fallback function; Contract graph interpretation, perform contract graph node interpretation, identify core operation nodes in the contract graph, analyze according to function calls, state modifications, and access control privilege attributes, and assign semantic representations to key nodes. The calculation formula is as follows: L(n) = f(O(n), A(n)) Where O(n) represents the specific operation content of the node, such as function calls, arithmetic operations, etc.; A(n) represents the access control of the node, such as public, private, internal; Perform contract graph edge interpretation, identify the edges associated with key nodes according to the chronological order of the edges, and assign semantic representations to the edges according to the dependency relationships of the edges. The calculation formula is as follows: L(e) = f(L(n i ), L(n j ), A(e)) where n i and n j represent the source node and the destination node respectively, and A(e) represents the attribute of the edge.
7. An intelligent contract vulnerability detection system based on semantic graph reasoning and context learning according to claim 5, characterized in that, The graph embedding vector extraction is divided into three stages: Adjacency matrix normalization, perform normalization processing on the constructed contract graph, calculate the node degrees, add self-loop information, so that each node can retain the original information when updating its own features, and adjust the data distribution through the degree matrix, thereby ensuring the balance of information propagation, improving the stability of model training, and ensuring the effective fusion of information of different nodes; Feature aggregation and update, the model will be updated layer by layer. Each layer is based on the node features of the previous layer and combines the adjacency relationship to weight and integrate the information, capture the local patterns of the graph, and gradually fuse the global information, making the final node representation more semantic and distinguishable; Graph embedding vector generation, perform pooling processing by taking the maximum value of all node features, compress the information of the entire graph into a vector with a fixed dimension. This vector synthesizes local and global feature information, can more comprehensively express the structure of the graph and the relationships between nodes, and store the vector in the FAISS vector library.
8. An intelligent contract vulnerability detection system based on semantic graph reasoning and context learning according to claim 5, characterized in that, The method for constructing the chain of thought prompt is: Similar graph query, apply the cosine similarity algorithm to query the most similar contract graph in the FAISS vector library, and obtain its label and semantic graph representation according to the index. The calculation formula is as follows: where z i and z j are the embedding vectors of two contract diagrams respectively, |||| represents the Euclidean norm of the vector, · represents the dot product operation, and the value of the cosine similarity ranges between -1 and 1. The closer the value is to 1, the closer the directions of the two diagrams in the embedding space, indicating higher similarity; Combine the prompt information, obtain the definition of smart contract vulnerability types based on the Solidity official documentation, and construct a thought chain prompt for four-step thinking, including Step 1: Vulnerability definition knowledge, Step 2: Learn the semantic graph, Step 3: Compare similar cases, and Step 4: Make a judgment.
9. A computer system, comprising a memory, a processor, and a computer program / instructions stored on the memory and executable on the processor, characterized in that, When the computer program / instructions are executed by the processor, the steps of the smart contract vulnerability detection method based on semantic graph reasoning and context learning according to any one of claims 1-4 are implemented.
10. A computer program product, comprising a computer program / instructions, characterized in that, When the computer program / instructions are executed by the processor, the steps of the smart contract vulnerability detection method based on semantic graph reasoning and context learning according to any one of claims 1-4 are implemented.
Citation Information
Cited By
Code vulnerability detection method and device, computer equipment, storage medium and product
CN121435244A