Intelligent contract vulnerability detection method based on heterogeneous graph attention network
By constructing a heterogeneous graph representation and heterogeneous graph attention network model for smart contracts, the accuracy and interpretability issues of smart contract vulnerability detection are solved, and efficient vulnerability detection and result interpretation are achieved.
Patent Information
- Application Number
- CN202510700916.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-28
- Publication Date
- 2025-09-26
AI Technical Summary
Existing smart contract vulnerability detection methods are difficult to adapt to the growing scale and complexity of contracts, have low detection accuracy and efficiency, and the detection results of deep learning models lack interpretability.
Construct a heterogeneous graph representation of smart contracts and use heterogeneous graph attention networks for vulnerability detection. By constructing SCIR, SCPG and SCHG, and combining the multi-layer heterogeneous graph attention network model MHGAN with node-level, path-level and graph-level attention layers, deep semantic modeling and vulnerability feature mining of smart contracts are achieved, improving detection accuracy and enhancing the interpretability of detection results.
It achieves efficient detection of smart contract vulnerabilities with a detection accuracy of 94.74%. It also improves the interpretability of vulnerability detection results by calculating the confidence of code lines, providing more effective and reliable security protection.
Smart Images

Figure CN120705873A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of computer technology, in particular to the field of smart contract security vulnerability detection technology, and specifically relates to a smart contract vulnerability detection method based on a heterogeneous graph attention network. Background Art
[0002] Smart contracts are autonomous programs written in high-level programming languages and deployed on distributed blockchain networks. Due to their decentralization, data transparency, and automated execution, they have been widely used in finance, gaming, intellectual property protection, and other fields. However, their immutable code and user anonymity make it possible for exploitation of contract vulnerabilities to cause irreversible and substantial losses. Therefore, efficient and accurate vulnerability detection for smart contracts is crucial.
[0003] Smart contract vulnerability detection technology has garnered widespread attention in recent years, with researchers proposing a variety of detection methods. Traditional approaches primarily rely on techniques such as symbolic execution, formal verification, fuzz testing, and intermediate representation-based analysis. While these traditional methods can detect security vulnerabilities in smart contracts to a certain extent, they often rely on complex rule matching or carefully designed test cases, making them difficult to adapt to the growing scale and complexity of smart contracts and limiting their accuracy and efficiency.
[0004] With the rise of deep learning technology, several deep learning-based smart contract vulnerability detection methods have emerged. These methods enable end-to-end detection and offer greater versatility than traditional approaches. For example, methods based on long short-term memory (LSTM) networks convert smart contract bytecode into a sequence of opcodes, leveraging LSTM's sequence modeling capabilities to capture contextual information about the execution path. Methods based on natural language processing (NLP) technology treat smart contract source code as a text sequence, converting it into a vector representation using a word embedding model, and then utilizing deep learning models for vulnerability detection. Existing deep learning-based smart contract vulnerability detection methods often represent contract source code or bytecode as serialized text or isomorphic graphs of a single node and edge type, leveraging the contextual semantic learning capabilities of neural network models such as LSTM and GCN to achieve efficient detection. However, these input data representations fail to fully utilize the structured semantic information of smart contracts (such as data dependencies and function calls), resulting in inadequate semantic modeling of the contract code, which in turn affects vulnerability detection accuracy. Furthermore, deep learning models exhibit a "black-box" nature, with detection results being either 0 or 1. These results lack interpretability, making it difficult for developers to intuitively understand and locate vulnerabilities. Summary of the Invention
[0005] The purpose of this invention is to provide a smart contract vulnerability detection method based on heterogeneous graph attention network.
[0006] The characteristics of the method of the present invention are: (1) By constructing a heterogeneous graph representation of smart contracts, the semantic relationships between elements such as variables, statements, and functions in the contract are fully utilized to achieve deep semantic modeling of the contract code. (2) With the powerful learning ability of the heterogeneous graph attention network, potential vulnerability characteristics can be effectively discovered, improving the detection accuracy. (3) The interpretability of the detection results is enhanced through the attention mechanism, providing a more effective and reliable solution for the security protection of smart contracts.
[0007] To achieve the above object, the technical solution of the present invention is:
[0008] Step (1) constructs the smart contract intermediate representation SCIR, as follows:
[0009] (1-1) Contract code preprocessing: First, remove redundant information from the smart contract, then uniformly replace statements or functions with the same semantic functions, and finally explicitly mark variables and functions related to the vulnerability;
[0010] (1-2) Construct the SCIR syntax specification, including defining data types, statement types, expression types, function types, and function call types;
[0011] (1-3) Convert and annotate the contract code according to the SCIR syntax specification, construct the smart contract intermediate representation SCIR, and renumber the variables when assigning values. Different numbers for the same variable represent its status at different stages;
[0012] Step (2) constructing the smart contract code property graph SCPG;
[0013] Based on the constructed smart contract intermediate representation SCIR, node types and their attributes are defined, and the smart contract code property graph SCPG is constructed by combining the abstract syntax tree AST, control flow graph CFG, call graph CG and data dependency graph DDG to comprehensively represent the syntax and semantic features of the smart contract; the node types include function nodes FN, variable nodes VN, statement nodes SN and expression nodes EN;
[0014] The smart contract code property graph SCPG is formally defined as a directed multigraph with edge labels and node attributes. , Representing multiple images The node set, represents a set of directed edges; Represents an edge labeling function, from the label table Assign a label to each edge in ; A map representing node attributes, is a set of keywords for the attributes, is a set of attribute values;
[0015] Step (3) constructing the smart contract heterogeneous graph SCHG;
[0016] Smart contract code heterogeneous graph ;in, express The node set in ; express The edge set of , represents the mapping function of the node type, It is the set of all node types in SCHG; represents the edge type mapping function, Represents all edge types in SCHG; Is a matrix that represents the characteristics of all nodes; in the smart contract code heterogeneous graph SCHG, the node type set and edge type set The size meets ;
[0017] Node Type Collection Contains four types of nodes: function node FN, variable node VN, statement node SN and core node CN, ; Among them, the core node CN is determined according to the core node judgment rule; for the first nodes, and its initial eigenvector is expressed as: ;in, Indicates the The number of the node; Indicates the The node type of each node; Represents a set of attribute keywords, Represents a splicing operation; Indicates the The node The attribute value corresponding to the attribute keyword; Indicates the The combination of all attribute values of a node;
[0018] Step (4) vulnerability detection; (4-1) based on the heterogeneous graph attention network model HAN, an improved multi-layer heterogeneous graph attention network model MHGAN is implemented. MHGAN includes a node-level attention layer, a path-level attention layer, and a graph-level attention layer. Graph embedding After that, MHGAN adopts The function is used as the activation function, and the multi-layer perceptron MLP is used to perform classification prediction on the graph embedding;
[0019] (4-2) The generated smart contract code heterogeneous graph SCHG is classified using the multi-layer heterogeneous graph attention network model MHGAN, which converts the vulnerability detection problem into a graph classification problem to achieve vulnerability detection; the confidence metric is introduced to quantify the degree of association between the statement nodes in SCHG and the vulnerability; based on the difference in the attention weight distribution of different nodes in the generated SCHG, the confidence of the vulnerability in each line of code in the smart contract is calculated to obtain the confidence distribution.
[0020] The proposed smart contract vulnerability detection method based on a heterogeneous graph attention network can effectively detect nine types of smart contract vulnerabilities, with a detection accuracy of up to 94.74%. Furthermore, the method can calculate the confidence level of each line of code in a smart contract and, by analyzing the differences in confidence levels, effectively improve the interpretability of vulnerability detection results. BRIEF DESCRIPTION OF THE DRAWINGS
[0021] Figure 1 It is the overall process framework diagram of the method of the present invention;
[0022] Figure 2 This is an example of equivalent replacement of modifer in the method of the present invention;
[0023] Figure 3 This is an example of SCIR conversion of the Victim contract in the method of the present invention;
[0024] Figure 4 Partial results of SCPG construction for the Victim contract in the method of the present invention;
[0025] Figure 5 is the initial feature representation of the SCHG node of the method of the present invention;
[0026] Figure 6 Schematic diagram of SCHG of the method of the present invention;
[0027] Figure 7 Schematic diagram of MHGAN of the method of the present invention;
[0028] Figure 8 Schematic diagram of the vulnerability detection explainability evaluation results of the method of the present invention. DETAILED DESCRIPTION
[0029] The present invention will be further described below with reference to the accompanying drawings and specific embodiments:
[0030] like Figure 1As shown in the figure, a smart contract vulnerability detection method based on a heterogeneous graph attention network first constructs a smart contract intermediate representation (SCIR). Code preprocessing is performed to explicitly annotate triggering conditions such as global variables and callback function calls that some vulnerability types rely on. During this process, the SCIR is constructed according to the SCIR syntax specification. Next, a smart contract code property graph (SCPG) is constructed. Based on the SCIR, various code graph structures, such as abstract syntax trees and control flow graphs, are organically integrated, and node attributes and edge types are precisely defined. Based on the SCPG, core node judgment rules are applied to further optimize the representation of the code graph structure and construct a smart contract heterogeneous graph (SCHG). Finally, a multi-level heterogeneous graph attention network model is constructed and trained to detect smart contract vulnerabilities. Furthermore, based on the differences in the attention weight distribution of different nodes in the SCHG, the confidence level of vulnerability presence in each line of smart contract code is calculated, resulting in a confidence distribution.
[0031] Step (1) constructs a smart contract intermediate representation (SCIR). On the one hand, the source code of the smart contract is full of redundant information that is irrelevant to vulnerability detection, and the rich and diverse syntax functions of Solidity significantly increase the complexity of the contract code in the graph structure representation. On the other hand, the vulnerability triggering conditions of some smart contracts, such as the callback function call that can trigger the reentrancy vulnerability, are not displayed in the code in an intuitive and obvious way, which undoubtedly brings great obstacles to the vulnerability detection work. In view of this, the present invention realizes the construction of SCIR under the premise of ensuring that the semantics of the contract code remain basically unchanged, thereby reducing the complexity of the contract code and further enriching the vulnerability-related features of the contract code, providing a unified and standardized syntax and semantic basis for the construction of SCPG. The details are as follows:
[0032] (1-1) Contract code preprocessing:
[0033] First, remove redundant information from the smart contract, including comments, unused functions that cannot be accessed, event-related code, unused state variables, unreferenced imported libraries, test-related code, and empty functions or functions with no actual operations. Table 1 summarizes some common types of redundant information that can be removed, code examples, and elimination conditions.
[0034] Table 1 Examples of codes that can be eliminated
[0035]
[0036] Then, the statements or functions with the same semantic functions are uniformly replaced. Figure 2As shown in (a), in Solidity, modifiers can prioritize the execution of specific code snippets before a function is executed. They are often used in pre-processing operations such as conditional checking and permission control. Figure 2 As shown in (b), by replacing these conditional control statements with equivalent if-else statements in Solidity, we can effectively reduce the number of edge types during SCHG construction and reduce the complexity of the code graph structure. Similarly, there is a require function, which is used to confirm valid input and can also be converted into an equivalent if-else statement based on its execution logic.
[0037] Finally, explicitly annotate variables and functions related to vulnerabilities. For example, global variables like block.timestamp (block timestamp) and msg.sender (message sender address) (stored in the contract account and shared across the entire chain) are predefined in the Solidity language, and their values are dynamically generated based on the blockchain's environment during runtime. These variables are closely linked to vulnerabilities such as timestamp dependency and access control. However, the contract code does not contain definitions for these global variables. Explicitly annotating these global variables in the code and building corresponding node and data dependencies in SCPG based on this helps enhance SCPG's representation of vulnerability-related features. Furthermore, calls to callback functions (receive and fallback) also require explicit annotation in the code.
[0038] (1-2) Build the SCIR syntax specification. Based on the intermediate representation frameworks of SCVHunter and Slither and the static single assignment form (SSA), and based on the contract code preprocessing strategy, the SCIR syntax specification was built. As shown in Table 2, this syntax specification implements modeling enhancements in the following aspects to meet the needs of smart contract vulnerability detection:
[0039] Table 2 SCIR syntax specifications
[0040]
[0041]
[0042] (1-3) Build SCIR: Figure 3 The results of SCIR construction of the Victim contract code containing a reentrancy vulnerability are shown based on the SCIR syntax specification generated in step 1.2. Figure 3(a) is the Victim contract code before construction. This code implements the user withdrawal function by defining the withdraw function. First, according to the contract code preprocessing strategy, the require function is equivalent to an if-else statement, and the global variable msg.sender and the callback call FallbackCall are explicitly annotated. Then, according to the core idea of SSA, the variables are renumbered when they are assigned. Finally, we get the following Figure 3 (b) shows the SCIR construction result. By constructing the SCIR, the definition and usage chain of the user balance variable (userBalance) are clearly presented. Different numbers for the same variable represent its status at different stages, avoiding data flow ambiguity caused by multiple assignments to the same variable in the contract source code. Similarly, Solidity's unique callback mechanism is clearly presented through explicit annotations.
[0043] Step (2) constructs the smart contract code attribute graph SCPG. The traditional single-dimensional code graph structure representation method has inherent defects. For example, although the abstract syntax tree can present the code hierarchy structure, it loses the control flow jump information; although the control flow graph can track the execution path, it cannot obtain data dependencies. Smart contract vulnerability detection often requires comprehensive consideration of multiple aspects of code syntax, control flow, and data flow. In view of this, the present invention further implements a graph structure representation method for the attribute graph SCPG of the smart contract code based on the generated SCIR. By parsing the syntax specification of SCIR, defining nodes and their attributes, and organically integrating the abstract syntax tree, control flow graph, data dependency graph, and call flow graph, SCPG can efficiently establish semantic associations between nodes, making up for the shortcomings of single-dimensional code graph representation.
[0044] The smart contract code property graph SCPG is formally defined as , is a directed multigraph with edge labels and node attributes. Represents a set of nodes in a graph; represents a set of directed edges; Represents an edge labeling function, from the label table Assign a label to each edge in ; A map representing node attributes, is a set of keywords for the attributes, A collection of attribute values.
[0045] Nodes and node properties:
[0046] Table 3 summarizes the attribute keywords of the function node ( ) set and the corresponding value ( )gather.
[0047] Table 3 Function node properties
[0048]
[0049] Table 4 summarizes the attribute keywords of variable nodes ( ) set and the corresponding value ( )gather.
[0050] Table 4 Variable node attributes
[0051]
[0052] According to the description of expressions and statements generated by SCIR, Table 5 summarizes the attribute keywords of statement nodes and expression nodes ( / ) set and the corresponding value ( / )gather.
[0053] Table 5 Statement node and expression node attributes
[0054]
[0055] Edge and code graph structure representation:
[0056] The Abstract Syntax Tree (AST) captures the grammatical structure of the generation in a tree-like data structure. For a statement in SCIR, the AST is defined as: .in, They correspond to three types of nodes: root nodes, non-terminal nodes, and terminal nodes. The root node represents the entry point to the entire statement, i.e., the statement node. Non-terminal nodes represent expression nodes within a statement, describing the grammatical structure of the statement. Terminal nodes represent variable nodes, including literals and constants. Represents all the edges in the AST that point from parent nodes to child nodes. These edges are marked by the function Marking, where , clearly identifying the structure as an abstract syntax tree.
[0057] A control flow graph (CFG) is a code graph structure that describes the order in which code is executed and the conditional selection of execution paths. For a function in SCIR, the control flow graph CFG is defined as: Among them, the node set , including statement nodes and function nodes; express The set of all edges in the node, which reflects the execution order between nodes; the labeling function Assign a specific label to each edge, label set Specifically: For the relationship between statement nodes, According to each edge Middle starting node To judge by type If represents a conditional statement, then the edge label is or , respectively, represent the execution path when the condition is true or false. Is a non-conditional statement, then the edge label is , indicating the path of sequential execution. In addition, for the relationship between function nodes and statement nodes, function nodes are connected through a The edge points to the first statement node to call the function, thus continuing the execution path.
[0058] The call graph (CG) is used to explicitly represent the call relationship between statements and functions in a program. For the entire smart contract, the call graph CG is defined as: Among them, the node set , representing the function nodes and statement nodes in the contract; the edge set Indicates the calling relationship between functions. An edge Represents a function or statement node For function nodes To more accurately describe the calling relationship, mark the function Each edge is assigned a label based on the call type defined by SCIR. Label set: , representing low-level call, built-in call, internal call, external call and callback call respectively.
[0059] The Data Dependent Graph (DDG) clearly and intuitively presents the data dependencies between statements and variables in a program. This paper defines these dependencies as: the dependencies between variable definitions and uses within statement nodes, as well as the read and write dependencies between variable nodes and between variables and statement nodes. For a smart contract or function, the Data Dependency Graph (DDG) is defined as: Among them, the node set , including statement nodes and variable nodes; Represents a set of dependency edges between nodes; labeling function Assign a label to each dependency edge. Label set , used to distinguish dependency types. Specifically, an edge The following situations exist: 1) If and Both represent statement nodes, then they represent nodes Using the node Variables defined or assigned in ); 2) If If the node is a variable node, it represents a variable node The writing of the variable node depends on Read ( ), or statement nodes The execution depends on the node Read and write ( or ).
[0060] According to the above description of nodes and node attributes, The node collection in and node attribute mapping It can be further expanded into:
[0061] ;
[0062] ;
[0063] ;
[0064] According to the above The definition of the four code graph structures in of and edge labeling function Further expanded to:
[0065] ;
[0066] ;
[0067] Figure 4 This shows the results of constructing the SCPG portion of the smart contract code property graph for the Victim contract code. Figure 4 In the intermediate representation of the contract code in (a), the SCPG construction module first extracts nodes, obtains four types of nodes and assigns attributes. Then, four code graph structures are constructed and fused, and finally the Figure 4 (b) SCPG construction result. This graph can comprehensively and systematically reflect the syntax structure, control flow, call flow, and data dependency of the smart contract code, providing a comprehensive representation framework for constructing smart contract heterogeneous graphs.
[0068] Step (3) constructs the smart contract heterogeneous graph SCHG. Although SCPG can fully reflect the syntax and semantic features of smart contracts, the key to vulnerability detection is to efficiently utilize these features. It should be noted that not all nodes are equally important in vulnerability detection. Therefore, extracting key features from massive nodes directly affects the efficiency and accuracy of vulnerability detection. To address this problem, this method combines common vulnerability types, deeply analyzes the attributes and edge types of each node in the code attribute graph, and designs corresponding core node CN (Core Node) judgment rules. These rules help to better identify high-risk nodes related to vulnerabilities during model training and vulnerability detection. On this basis, a smart contract code heterogeneous graph SCHG representation is further implemented. SCHG is a further optimization of the SCPG generated in step (2), aiming to provide more efficient and discriminative input for subsequent model training by constructing high-quality feature representations of each node.
[0069] The core node judgment rule is formally defined as and A predicate combination of . Among them, Determine any node exist The attribute value in whether it is true; Determine any edge In the subgraph Tags in Is true, and according to to select the core node. Representation node As the core node, Represents a set of secondary edge types; Representation node As the core node; Indicates that both are core nodes. Any node that meets the true predicate expression is considered a core node. In addition, you can also use ( ) and or ( ) and other predicates to express complex judgment rules. Table 6 summarizes the core node judgment rules for several vulnerabilities. Taking the reentrancy vulnerability as an example, its core node judgment rules focus on the state variable representing the balance, writes to this variable, low-level calls, and regression calls.
[0070] Table 6 Core node judgment rules for some types of vulnerabilities
[0071]
[0072] The smart contract code heterogeneous graph is defined as ;in, express The node set in ; express The edge set of , represents the mapping function of the node type, is the set of all node types in the graph; represents the edge type mapping function, where Represents all edge types; Is a matrix that represents the characteristics of all nodes. nodes, whose initial eigenvector is In the smart contract code heterogeneous graph, the node type set and edge type set The size meets This means that the graph contains at least two different types of nodes or edges, thus reflecting the diversity of heterogeneous graphs.
[0073] In the smart contract code heterogeneous graph SCHG, the node type set There are four types of nodes: function node FN, variable node VN, statement node SN and core node CN. Compared with SCPG, SCHG has optimized the node type division, removed the expression node EN, and added a core node. Therefore, the node type set It can be expressed as: For the nodes, and its initial eigenvector can be formally expressed as: .in, Indicates the The number of the node; Indicates the The node type of each node; Indicates the The present invention uses the form of one-hot vector to represent all attribute values of nodes. Each component in is encoded and then concatenated together as the initial feature representation of the node.
[0074] Figure 5 The initial feature representation of each node in SCHG is shown in detail. SCHG uses different representations for different types of nodes. Although expression nodes exist in SCPG, they are removed in SCHG. Their features are extracted from the AST of the corresponding statement node through an in-order traversal and spliced into the feature representation of the statement node. Therefore, the features of the expression node are still retained, but no longer appear as independent nodes in the contract heterogeneous graph. Core nodes are selected from function nodes, variable nodes, and statement nodes based on specific judgment rules. Their node feature representation remains unchanged, and they are only differentiated by the node type (NodeType) field.
[0075] As shown in Table 7 and Figure 6 As shown, SCHG divides edge types into two levels: the first level edge ( ) There are eleven types, which describe the microscopic connections of node characteristics; the second-level edge , reflecting dynamic execution information such as smart contract execution order, variable dependencies and function calls, and embodies the macro characteristics of the contract.
[0076] Table 7 SCHG edge types
[0077]
[0078] Step (4) vulnerability detection;
[0079] (4-1) Based on the heterogeneous graph attention network model HAN, an improved multi-layer heterogeneous graph attention network model MHGAN is implemented. MHGAN includes node-level attention layer, path-level attention layer and graph-level attention layer. The details are as follows:
[0080] Node-level attention layer: This layer of the network can learn the importance of each node's neighbor nodes based on the meta-path, and aggregate the feature representations of these key neighbor nodes to form a more discriminative node embedding. Meta-Path Defined as a heterogeneous graph of smart contract code A path in: The path defines two node types: and A composite neighbor relationship between .in," " indicates a compound operator; Represents a meta path length.
[0081] For each type of node, first use the transformation matrix , mapping the node features into the same feature space.
[0082] ;in, and Represents the nodes before and after the mapping feature representation.
[0083] Then, MHGAN uses the self-attentive mechanism to learn the weights of the nodes. For a given pair of nodes , through the metapath connected, express The secondary edge type in Node-level attention mechanism can learn node For nodes Importance , the calculation formula is as follows:
[0084] ;
[0085] in, Represents a deep neural network that computes node-level attention, whose parameters are automatically learned via backpropagation. For a given meta-path , all nodes based on this path share , this is because there are some similar connection patterns under a meta-path. From the above formula, we can see that in a given meta-path Next, the node pair The weights of the features depend on their own characteristics. , that is, node Couplet Importance and nodes For Node The importance of nodes is not equal. Therefore, node-level attention can maintain asymmetry, which is an important property of heterogeneous graphs.
[0086] After obtaining the importance between node pairs based on meta-path, the softmax function is used to normalize them to obtain the weight coefficient :
[0087] ;
[0088] in, represents the activation function, Representation node Based on meta path Neighbor nodes of " indicates a splicing operation. Indicates a meta path specific Trainable node-level attention vector for .
[0089] Then, MHGAN performs node attention mechanism Repeat the learning process independently, learning different node embeddings each time, and The embeddings learned are concatenated to obtain the node Node embedding under specific meta-path semantics :
[0090] ;
[0091] Finally, for a given secondary edge type A set of meta-paths on ,get The semantic node embedding of the group-specific meta-path is represented as Specifically, for any meta-path , whose semantic node embedding is .in, express middle The number of meta-paths in the subgraph; Indicates the number of nodes. Figure 7 (a) shows the above process.
[0092] Path-level attention layer: This layer of network can learn the importance weights of different meta-paths for the final vulnerability detection, thereby improving MHGAN's ability to detect complex vulnerability patterns. The semantic node embeddings under multiple meta-paths learned from the node-level attention layer are used as input to calculate the same subgraph. The weight values of different meta paths under , the calculation formula is as follows:
[0093] ;
[0094] ;
[0095] ;
[0096] With the help of nonlinear transformation and attention vector , calculate the average similarity of different meta-paths to each node , and then calculate the weight value of a specific meta-path through normalization operation Finally, using the weight value Node-level semantic embedding Weighted summation to obtain path-level node semantic embedding , , express middle The number of meta-paths in the subgraph, represents any meta-path, Indicates the number of nodes. Figure 7 (b) shows the above process.
[0097] ;
[0098] Graph-level attention layer: This layer of the network fully considers The impact of path-level semantic embedding under different subgraphs on vulnerability detection tasks. The calculation formula is as follows:
[0099] ;
[0100] ;
[0101] ;
[0102] in, 、 and are learnable parameters shared by all subgraphs, namely the weight matrix for nonlinear changes, the bias vector, and the graph-level attention vector used to calculate similarity. is the contribution of different code graph structure types to vulnerability detection tasks. Obviously, The higher the value, the more important it is to vulnerability detection. As coefficients, the final semantic embedding of all nodes is obtained by linear combination, and the graph embedding is obtained by combining , Indicates the secondary edge type. Figure 7 (c) shows the above process.
[0103] Finally, after getting Graph embedding After that, MHGAN adopts The function is used as the activation function, and the multi-layer perceptron (MLP) is used to perform classification prediction on the graph embedding. At the same time, the cross entropy loss function is used to measure the difference between the predicted result and the true label, and the back propagation of the gradient descent algorithm is used to learn the parameters of the model. Figure 7 (d) shows the above process.
[0104] ;
[0105] ;
[0106] (4-2) We use the Multi-Layer Heterogeneous Graph Attention Network (MHGAN) model to classify the generated smart contract code heterogeneous graph (SCHG), transforming the vulnerability detection problem into a graph classification problem to achieve vulnerability detection. We introduce the confidence metric to quantify the degree of association between statement nodes in the SCHG and vulnerabilities. Based on the differences in the attention weight distribution of different nodes in the generated SCHG, we calculate the confidence level of each line of smart contract code that contains a vulnerability, and obtain the confidence distribution.
[0107] The present invention introduces confidence to quantify the degree of association between the statement node and the vulnerability in SCHG. According to the above calculation of node attention weight The method is to sum up the attention weights of the same node in multiple subgraphs in SCHG and perform normalization operations. The confidence of the node The definition and calculation of are as follows:
[0108] ;
[0109] ;
[0110] in, Represents a collection of expression nodes (including core nodes); Represents the weight coefficient. By calculating the confidence of each expression node and analyzing their differences, the interpretability of the model is significantly enhanced and provides support for subsequent vulnerability repairs.
[0111] Algorithm: Smart Contract Vulnerability Detection
[0112] Input: Smart contract source code , detection model MHGAN and supported vulnerability types ;
[0113] Output: Confidence of each row and the types of vulnerabilities detected ;
[0114] 1 / / Smart contract intermediate code conversion;
[0115] 2 / / Smart contract code attribute graph conversion;
[0116] 3 / / Smart contract code heterogeneous graph conversion;
[0117] 4 / / Extract meta path;
[0118] 5 ;
[0119] 6 ;
[0120] 7 For in :
[0121] 8 / / Vulnerability detection;
[0122] 9 IF :
[0123] 10 / / Add the detected vulnerability type;
[0124] 11 For in :
[0125] 12 / / Locate the row number of the statement node;
[0126] 13 / / Calculate node confidence;
[0127] 14 ;
[0128] 15 End For;
[0129] 16 End IF;
[0130] 17 End For;
[0131] 18 Return.
[0132] This algorithm shows the vulnerability detection process in detail. The input of this algorithm is the source code of the smart contract to be tested ( ) and the set of vulnerability types supported by the detection model MHGAN ( The output of this algorithm is a set of detected vulnerability types ( ) and the confidence level of each line of code ( ). Used to locate nodes The source code line number.
[0133] The present invention constructs the MIXED-DB dataset as the training set and validation set for this experiment. The mixed dataset consists of three parts. The first part comes from Smartbugs Curated. This dataset is obtained by analyzing and collecting vulnerabilities on some GitHub repositories, blog sites, and the Ethereum network. It covers a total of 9 vulnerability types and contains 143 annotated smart contracts, of which 208 vulnerabilities are marked. The second part comes from SolidiFI-Benchmark. This dataset is synthesized by injecting 9,369 vulnerabilities into 350 different smart contracts and contains seven different vulnerabilities. The third part comes from Smartbugs Wild and contains 47,398 Ethereum smart contracts.
[0134] This paper uses DAPPSCAN-SOURCE as the test set for this experiment and for experimental comparison. This dataset is a real-world dataset and the first large-scale smart contract vulnerability dataset. Based on audit reports of decentralized application (DApp) projects on the Ethereum platform, this dataset compiles 1,199 open-source audit reports published by 29 security teams. It covers 682 real-world DApp projects, totaling 39,904 Solidity files, with an average of 7,885 lines of code. Given the large variation in the number of data samples for different vulnerability types, this experiment focuses on the five types with the largest number of samples: integer overflow (IOU), reentrancy (RE), unchecked call value (UCR), denial of service (DoS), and transaction order dependency (TOD).
[0135] The present invention uses the parameter configuration in Table 8 to train and verify the MHGAN model on the MIXED-DB dataset, and finally obtains the vulnerability detection results after seven-fold cross-validation as shown in Table 9.
[0136] Overall, HGAT-SVD demonstrates excellent performance in smart contract vulnerability detection, with average accuracy, precision, recall, and F1-score reaching 92.21%, 88.36%, 92.47%, and 90.35%, respectively. A horizontal comparison of detection results for different vulnerability types reveals some discrepancies. For example, the F1-scores for access control vulnerabilities (AC), integer overflow vulnerabilities (IOU), transaction order dependency vulnerabilities (TOD), and unprotected self-destruct vulnerabilities (USI) all exceed 90%, while the F1-scores for other vulnerability types are lower. This discrepancy is due to two factors: first, some vulnerability types are less common in the MIXED-DB dataset, resulting in a lack of sufficient training data, which can be addressed by increasing the number of training samples; and second, some vulnerability types have a wide range of triggering scenarios. For example, scenarios that trigger a denial of service (DoS) vulnerability include, but are not limited to, gas exhaustion, self-destruction or permission lockout, and external call failures. Complex triggering scenarios can mislead MHGAN's judgment, but this can be addressed by refining vulnerability types through different triggering scenarios. By comparing the validation results of the same type of vulnerability across different evaluation metrics, we found that recall is generally higher than precision. This result suggests that HGAT-SVD uses a more conservative vulnerability detection strategy, attempting to detect all possible vulnerabilities.
[0137] Table 8 Experimental parameter details
[0138]
[0139] Table 9 Detection results of HGAT-SVD on the MIXED-DB dataset
[0140]
[0141] In addition, the interpretability of HGAT-SVD vulnerability detection results is also evaluated. Figure 8 As shown in the figure, after the smart contract code containing the reentrancy vulnerability on the left is successfully detected by HGAT-SVD, the confidence of each line of code on the right is obtained ( Comparing these confidence levels reveals that lines 3 and 5 have higher confidence levels, indicating that these lines of code contribute more significantly to the detection of reentrancy vulnerabilities, consistent with empirical findings. This experimental result demonstrates that HGAT-SVD can effectively improve the interpretability of vulnerability detection results by calculating the confidence level of each line of code, and can provide guidance for subsequent vulnerability remediation.
[0142] In order to further evaluate the effectiveness and generalization ability of HGAT-SVD for smart contract vulnerability detection, the present invention conducted the following comparative experiments. In this experiment, HGAT-SVD was comprehensively compared with a variety of traditional vulnerability detection methods and deep learning-based detection methods to obtain strong evidence for demonstration. Among them, traditional vulnerability detection methods include: Securify, Smartian and Slither, which represent smart contract vulnerability detection methods based on symbolic execution, fuzz testing and intermediate representation, respectively. The deep learning-based detection methods include: LSTM detection method based on sequence representation and TMP detection method based on isomorphic graph representation. To ensure the fairness of the experiment, this experiment was conducted on the DAPPSCAN-SOURCE dataset and F1-score was used as the evaluation indicator of vulnerability detection effectiveness. The experimental results are shown in Table 10. Among them, "-" indicates that the corresponding detection model does not support the vulnerability type.
[0143] Table 10 F1-score comparison experimental results of multiple methods on the DAPPSCAN-SOURC dataset
[0144]
[0145] Preliminary analysis shows that the Securify, Smartian, and Slither methods generally achieve F1-scores below 50% for the five smart contract vulnerability detection methods, failing to fully cover all five vulnerability categories. This is due to the rigid and single-minded nature of these traditional detection methods. When applied to real-world vulnerability scenarios in the DAPPSCAN-SOURCE dataset, they suffer from high rates of both false positives and false negatives, and their generalization to new vulnerability types is limited. In contrast, the LSTM and TMP methods achieve significant improvements in F1-score, achieving at least 32.85%, 18.29%, 9.97%, 15.2%, and 16.98% gains across the five vulnerability types, respectively. These results fully demonstrate the superiority of deep learning for smart contract vulnerability detection.
[0146] Further analysis reveals that the TMP method, based on isomorphic graph representations, achieves an F1-score improvement of 2.4% to 11.12% compared to the LSTM method, based on sequence representations. This result demonstrates that simply treating smart contract code as a text sequence while ignoring implicit structured information such as control flow and data flow is a poor approach, and indirectly demonstrates the advantages of graph neural networks in handling structured text classification tasks.
[0147] Judging from the final experimental results, compared with the best detection results of the current mainstream smart contract vulnerability detection methods, HGAT-SVD improved the F1-score of the five vulnerabilities by 9.63% to 20.46%. This result effectively proves that the detection method proposed in this invention has better effectiveness and generalization ability in the smart contract vulnerability detection task than the existing methods.
[0148] The embodiments of the present invention are described in detail above with reference to the accompanying drawings, but the present invention is not limited to the described embodiments. It is apparent to those skilled in the art that various changes, modifications, substitutions, and variations to these embodiments may be made without departing from the principles and spirit of the present invention, and these changes and modifications still fall within the scope of protection of the present invention.
Claims
1. A smart contract vulnerability detection method based on heterogeneous graph attention network, characterized by: Step (1) constructs the smart contract intermediate representation SCIR, as follows: (1-1) Contract code preprocessing: First, remove redundant information from the smart contract, then uniformly replace statements or functions with the same semantic functions, and finally explicitly mark variables and functions related to the vulnerability; (1-2) Construct the SCIR syntax specification, including defining data types, statement types, expression types, function types, and function call types; (1-3) Convert and annotate the contract code according to the SCIR syntax specification, construct the smart contract intermediate representation SCIR, and renumber the variables when assigning values. Different numbers for the same variable represent its status at different stages; Step (2) constructing the smart contract code property graph SCPG; Based on the constructed smart contract intermediate representation SCIR, node types and their attributes are defined, and the smart contract code property graph SCPG is constructed by combining the abstract syntax tree AST, control flow graph CFG, call graph CG and data dependency graph DDG to comprehensively represent the syntax and semantic features of the smart contract; the node types include function nodes FN, variable nodes VN, statement nodes SN and expression nodes EN; The smart contract code property graph SCPG is formally defined as a directed multigraph with edge labels and node attributes. , Representing multiple images The set of midpoints, represents a set of directed edges; Represents an edge labeling function, from the label table Assign a label to each edge in ; A map representing node attributes, is a set of attribute keywords, is a set of attribute values; Step (3) constructing the smart contract heterogeneous graph SCHG; Smart contract code heterogeneous graph ;in, express The node set in ; express The edge set of , represents the mapping function of the node type, It is the set of all node types in SCHG; represents the edge type mapping function, Represents all edge types in SCHG; Is a matrix that represents the characteristics of all nodes; in the smart contract code heterogeneous graph SCHG, the node type set and edge type set The size meets ; Node Type Collection Contains four types of nodes: function node FN, variable node VN, statement node SN and core node CN, ; Among them, the core node CN is determined according to the core node judgment rule; for the first nodes, and its initial eigenvector is expressed as: ;in, Indicates the The number of the node; Indicates the The node type of each node; Represents a set of attribute keywords, Represents a splicing operation; Indicates the The node The attribute value corresponding to the attribute keyword; Indicates the The combination of all attribute values of a node; Step (4) vulnerability detection; (4-1) Based on the heterogeneous graph attention network model HAN, an improved multi-layer heterogeneous graph attention network model MHGAN is implemented. MHGAN includes node-level attention layer, path-level attention layer and graph-level attention layer; after obtaining Graph embedding After that, MHGAN adopts The function is used as the activation function, and the multi-layer perceptron MLP is used to perform classification prediction on the graph embedding; (4-2) The generated smart contract code heterogeneous graph SCHG is classified using the multi-layer heterogeneous graph attention network model MHGAN, which converts the vulnerability detection problem into a graph classification problem to achieve vulnerability detection; the confidence metric is introduced to quantify the degree of association between the statement nodes in SCHG and the vulnerability; based on the difference in the attention weight distribution of different nodes in the generated SCHG, the confidence of the vulnerability in each line of code in the smart contract is calculated to obtain the confidence distribution.
2. The smart contract vulnerability detection method based on heterogeneous graph attention network according to claim 1 is characterized in that: The conversion described in steps (1-3) is to convert the require function into an equivalent if-else statement, and the annotation is to explicitly annotate the global variable msg.sender and the callback call FallbackCall.
3. The smart contract vulnerability detection method based on heterogeneous graph attention network according to claim 1 is characterized in that: In step (2), the abstract syntax tree AST is defined as ; Among them, the AST node set They correspond to three types of nodes: root node, non-terminal node and terminal node; the root node represents the entrance to the entire statement, that is, the statement node; the non-terminal node represents the expression node in the statement, which is used to describe the grammatical structure of the statement; the terminal node represents the variable node, including literals and constants; Represents all the edges in the AST that point from parent nodes to child nodes. These edges are marked by the function Marking, AST tag set ; The control flow graph CFG is defined as ; Among them, the CFG node set , including statement nodes and function nodes; express The set of all edges in the node, which reflects the execution order between nodes; the labeling function Assign a specific label to each edge, CFG label set ; The call graph CG is defined as ; Among them, the CG node set , representing the function nodes and statement nodes in the contract; CG edge set Indicates the calling relationship between functions; marks functions According to the call type defined by SCIR, each edge is assigned a label; CG label set: , Represent low-level call, built-in call, internal call, external call and callback call respectively; The data dependency graph DDG is defined as ; Among them, the DDG node set , including statement nodes and variable nodes; Represents a set of dependency edges between nodes; labeling function Assign a label to each dependency edge; DDG label set , used to distinguish dependency types.
4. The smart contract vulnerability detection method based on heterogeneous graph attention network according to claim 1 is characterized in that: The core node judgment rule described in step (3) is formally defined as and The predicate combination of ; among them, Determine any node exist The attribute value in whether it is true; Determine any edge In the subgraph Tags in Is true, and according to Select the core node. Indicates the secondary edge type; Representation node As the core node; Representation node As the core node; Indicates that both are core nodes; nodes that meet the true predicate expression are determined to be core nodes.
5. The smart contract vulnerability detection method based on heterogeneous graph attention network according to claim 1 is characterized in that: In step (4-1), the node-level attention layer can learn the importance of each node's neighbor nodes based on the meta-path, and aggregate the feature representations of these key neighbor nodes to form a more discriminative node embedding; meta-path Defined as a heterogeneous graph of smart contract code A path in: ; This path defines two node types and A composite neighbor relationship between ;in, Represents a compound operator; Represents a meta path length; The path-level attention layer can learn the importance weights of different meta-paths for the final vulnerability detection, thereby improving MHGAN's ability to detect complex vulnerability patterns; the semantic node embeddings under multiple meta-paths learned from the node-level attention layer are used as input to calculate the same subgraph The weight values of different meta paths under ; Using weight value Node-level semantic embedding Weighted summation to obtain path-level node semantic embedding , , express middle The number of meta-paths in the subgraph, represents any meta-path, Indicates the number of nodes; The calculation formula of the graph-level attention layer is as follows: ; ; ; in, express Attention weights on subgraphs, express Attention weights on subgraphs, is the intermediate weight, is the normalized weight value, and the superscript T indicates transposition; 、 and These are learnable parameters shared by all subgraphs, namely the weight matrix for nonlinear changes, the bias vector, and the graph-level attention vector used to calculate similarity; is the path-level node semantic embedding, The contribution of different code graph structure types to vulnerability detection tasks; The higher the value, the more important it is to vulnerability detection; finally, the weight value As coefficients, the final semantic embedding of all nodes is obtained by linear combination, and the graph embedding is obtained by combining ; Indicates the secondary edge type.
6. The smart contract vulnerability detection method based on heterogeneous graph attention network according to claim 1 is characterized in that: In step (4-2), The confidence of the node , No. The weight coefficient of each node , Represents a collection of expression nodes, Indicates the The weight coefficient of each node, Represents a meta-path based The node attention weights, Representation node exist Subgraph based on metapath neighbor nodes.
Citation Information
Cited By
Intelligent contract security vulnerability automatic detection and protection early warning method and system
CN120951341A
Code searching method and system based on multi-structure chart fusion
CN121050768A
A code search method and system based on multi-structure graph fusion
CN121050768B
Intelligent contract vulnerability automatic repair method and system based on genetic algorithm
CN121959575A
Intelligent contract vulnerability detection method, system and device and storage medium
CN122286785A