Intelligent contract vulnerability detection method based on graph neural network and related equipment
By converting the source code of the smart contract into a smart contract graph and using the graph neural network for training, the problem of difficult detection of complex vulnerability patterns in the existing technology is solved, and higher vulnerability detection accuracy and lower missed rate are achieved. .
Patent Information
- Application Number
- CN202411485898.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-10-23
- Publication Date
- 2025-02-14
AI Technical Summary
Existing smart contract vulnerability detection methods are difficult to effectively detect complex vulnerability patterns, resulting in a high misreport rate. With the rapid growth of smart contracts, it becomes challenging to manually design accurate vulnerability patterns.
A graph neural network-based method is adopted to generate a vulnerability detection model by converting the source code of the smart contract into a smart contract graph and using the graph neural network to train the graph. This method includes a message propagation phase and a time enhancement phase, extracting node features and edge features, reducing noise impact, and improving detection accuracy.
Effectively utilize the semantic information of the smart contract context, improve the accuracy of vulnerability detection, reduce the rate of missed reports, and can cope with complex and changeable smart contract application scenarios.
Smart Images

Figure CN119442249A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer technology, and in particular to a smart contract vulnerability detection method based on graph neural network and related equipment. Background Art
[0002] The main advantage of blockchain is that it creates an irreversible transaction history on a distributed ledger, allowing users to purchase items with digital currency without the need for trusted third-party processing and authentication. The three key elements of blockchain technology are distributed ledger technology with unchangeable records, consensus algorithms, and smart contracts. Smart contracts are an important part of blockchain technology. They are contracts written in code and automatically executed. This type of contract is implemented through a smart contract platform running on the blockchain and does not require third-party management or execution. The immutability of smart contracts means that once a vulnerability occurs, it will leave serious security risks and cause serious consequences. Therefore, it is very necessary to design an efficient tool for smart contract vulnerability detection.
[0003] In existing research, most smart contract vulnerability detection methods use static analysis to search for vulnerability patterns pre-defined by experts to detect target smart contracts. These manually defined vulnerability patterns are relatively simple and cannot cover some complex vulnerability patterns, resulting in a high false negative rate. In addition, with the rapid growth of smart contracts, it becomes challenging to design precise vulnerability patterns by a small number of experts. Summary of the invention
[0004] In order to cope with complex and changeable smart contract application scenarios and reduce the underreporting rate of smart contract vulnerability detection, the present invention provides a smart contract vulnerability detection method and related equipment based on graph neural network.
[0005] In a first aspect, the present invention provides a method for detecting smart contract vulnerabilities based on a graph neural network, comprising:
[0006] Step 1: Build a smart contract dataset with vulnerability labels;
[0007] Step 2: Convert each smart contract source code in the smart contract data into the corresponding smart contract graph;
[0008] Step 3: Use the smart contract graph corresponding to the smart contract dataset to train the preset graph neural network to obtain a smart contract vulnerability detection model;
[0009] Step 4: Input the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain the vulnerability detection result.
[0010] Furthermore, before converting the smart contract source code into the corresponding smart contract graph, it also includes: filtering out the honeypot contract source code and / or noise information in the smart contract source code.
[0011] Furthermore, extract function information and corresponding variable information from the given smart contract source code;
[0012] According to the extracted function information and corresponding variable information, the functions and key variables are used as nodes, and the relationship between the functions and key variables is used as edges, so as to generate the initial smart contract graph; among which, the functions are the main nodes and the key variables are the secondary nodes; among which, the edge types are divided into forward edges, data flow edges and control flow edges;
[0013] According to the overall execution order and data flow information of the given smart contract source code, a fallback node is introduced into the initial smart contract graph, and the edge type between the fallback node and the adjacent node is defined as a fallback edge, thereby generating the final smart contract graph.
[0014] Furthermore, step 2 specifically also includes: normalizing the final smart contract graph; the normalization process includes: retaining all main nodes in the smart contract graph, removing the remaining nodes and calculating the features of the removed nodes, and passing their features to adjacent main nodes; retaining the edges connected to the removed nodes, and moving the starting node or the end node of the edge to the corresponding main node; updating the features of the main node by aggregating the features of the removed nodes adjacent to the main node; and finally obtaining a normalized graph.
[0015] Furthermore, step 3 specifically includes:
[0016] Message propagation stage: define the edge in the smart contract graph as the time edge, define the two end nodes of the edge as the start node and end node of the time edge respectively, define the interaction process between the nodes in the smart contract graph as the message propagation process of the message passing from its start node to its end node along the time edge, update the node features according to the message propagation process, and obtain the first node feature h′ of the node i ;
[0017] Time enhancement stage: The graph attention mechanism is used to calculate the attention coefficient of each node in the smart contract graph to its neighbor nodes, which is defined as the node attention coefficient; and the attention coefficient of the edge between two adjacent nodes, which is defined as the edge attention coefficient; according to the node attention coefficient and edge attention coefficient of each node, the neighbor node features of the node are aggregated to obtain the second node feature h′ of the node vi ; Use the self-attention mechanism to the second node feature h′ of the node vi Perform linear transformation to obtain the node weight γ of each node i;
[0018] Detection phase: According to the node weights γ of all nodes i and the first node feature h′ i , generate vulnerability detection results for smart contracts.
[0019] Furthermore, in the message propagation phase, the hidden state of the end node is updated according to the following formula:
[0020]
[0021] m n =W n x n +q n
[0022]
[0023] Among them, ε n represents the nth time edge through which the message flows, Represents ε n The hidden state of the end node of n Indicates the edge type, Represents ε n The hidden state of the starting node, Represents the splicing symbol, x n Represents the original message, m n Represents x n The corresponding vector embedding is represents the intermediate vector embedding, U, Z and R all represent learnable matrices, and the matrix W n and vector q n is the network parameter, q 1 and q 2 Both represent learnable bias vectors, tanh is the activation function representing the learnable matrix, , and both represent learnable bias vectors, .
[0024] Furthermore, the graph attention mechanism is used to calculate the attention coefficient of each node in the smart contract graph to its neighbor nodes, which is defined as the node attention coefficient; and the attention coefficient of the edge between two adjacent nodes, which is defined as the edge attention coefficient, which specifically includes:
[0025] e ij =LeakyReLu(o[W 1 h i ‖W 1 h j ])
[0026]
[0027] εij =LeakyReLu(o[W 2 h i2 ‖W 2 h j2 ])
[0028]
[0029] Among them, e ij Represents node v i Its neighbor node v j The inter-node attention score between ij Represents node v i Its neighbor node v j The node attention coefficient between them, ε ij Represents node v i Its neighbor node v j The edge attention score between ij Represents node v i Its neighbor node v j The edge attention coefficient between 1 and W 2 represents the learnable matrix, h i and h j Respectively represent the node v i and its neighbor node v j The characteristics of h i2 and h j2 Respectively represent h i and h j The edge features in , o represents the learnable attention weight vector, || represents the concatenation operation of the vector, LeakyReLu and softmax are activation functions, and N(i) represents the node v i The set of neighbor nodes.
[0030] Furthermore, according to the node attention coefficient and edge attention coefficient of each node, the neighbor node features of the node are aggregated to obtain the second node feature h′ of the node vi , including:
[0031] Calculate the attention coefficient matrix A according to the following formula, and then use the attention coefficient matrix A to aggregate the node's neighbor node features according to the following formula to obtain the node's second node feature h′ vi ;
[0032] A=(1-p)*α ij +p*β ij
[0033] h′ vi =σ(∑ j∈N(i) A ij W′hj +h i )
[0034] Where p represents the preset weight, σ represents the sigmoid activation function, W′ is a learnable matrix, and N(i) represents the node v i The set of neighbor nodes.
[0035] Furthermore, according to the node weights γ of all nodes i and the first node feature h′ i , generate the vulnerability detection results of the smart contract, including:
[0036]
[0037] in, represents the predicted vulnerability label, ⊙ represents the element-wise product, sigmoid is the activation function, and |υ| represents the number of nodes in the smart contract graph.
[0038] In a second aspect, the present invention provides an electronic device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor implements the method described in the first aspect when executing the program.
[0039] In a third aspect, the present invention provides a non-transitory computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the method described in the first aspect.
[0040] Beneficial effects of the present invention:
[0041] (1) The present invention converts the smart contract source code into a smart contract graph, which can more effectively utilize the semantic information of the smart contract context, and then use the graph neural network to automatically detect vulnerabilities in the smart contract, so as to cope with complex and changeable smart contract application scenarios, improve the accuracy of vulnerability detection, and reduce the false negative rate of smart contract vulnerability detection.
[0042] (2) Before constructing the smart contract graph, the present invention purifies the noise nodes by eliminating unnecessary information in the smart contract source code (such as code comments, blank lines, and excessive spaces that do not meet programming standards); at the same time, considering the impact of some honeypot contracts on vulnerability detection, the collected data set is filtered once to remove some honeypot contracts that affect the experimental results, thereby improving the accuracy of vulnerability detection.
[0043] (3) The present invention extracts the node features of the smart contract graph and the node weights of the node features in the entire graph features through two independent feature updating stages, namely the message propagation stage and the time enhancement stage. It makes full use of the node's own features, inter-node features and edge features, retains sufficient contextual semantic features, and reduces the influence of noise nodes that are not related to the vulnerability, thereby further improving the accuracy of vulnerability detection and reducing the false negative rate. BRIEF DESCRIPTION OF THE DRAWINGS
[0044] Figure 1 A schematic diagram of a flow chart of a smart contract vulnerability detection method based on a graph neural network provided in an embodiment of the present invention;
[0045] Figure 2 A schematic diagram of a process for converting a smart contract source code into a smart contract graph provided by an embodiment of the present invention;
[0046] Figure 3(a) to Figure 3(c) The DH-GNN model structure provided by the embodiment of the present invention;
[0047] Figure 4 Comparison of detection results provided by the embodiments of the present invention: (a) is a comparison of detection results of different models for reentrancy vulnerabilities; (b) is a comparison of detection results of different models for timestamp dependency vulnerabilities;
[0048] Figure 5 This is a structural block diagram of an electronic device provided by an embodiment of the present invention. DETAILED DESCRIPTION
[0049] In order to make the purpose, technical solution and advantages of the present invention clearer, the technical solution in the embodiment of the present invention will be clearly described below in conjunction with the drawings in the embodiment of the present invention. Obviously, the described embodiment is a part of the embodiment of the present invention, not all the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0050] like Figure 1 As shown, an embodiment of the present invention provides a smart contract vulnerability detection method based on a graph neural network, comprising the following steps:
[0051] S101: Build a smart contract dataset with vulnerability labels;
[0052] Specifically, this embodiment first obtains a public data set for smart contract vulnerability detection from the github open source website, and then uses existing detection tools and expert knowledge to screen and classify the obtained public data set to obtain data containing reentry vulnerability and timestamp dependency vulnerability labels as a smart contract data set for subsequent training models.
[0053] S102: Convert each smart contract source code in the smart contract data set into a corresponding smart contract graph;
[0054] Specifically, before converting the source code into a graph, it is generally necessary to pre-process the source code to reduce data noise. For example, it includes: eliminating unnecessary information such as code comments, blank lines, and excessive spaces that do not meet programming standards in the smart contract source code; and considering that some honeypot contracts will not cause substantial harm to users in actual application environments, from a result-oriented perspective, vulnerabilities in honeypot contracts cannot be treated as real vulnerabilities. Therefore, this embodiment filters the data set to remove some honeypot contracts.
[0055] S103: Use the smart contract graph corresponding to the smart contract data set to train the preset graph neural network to obtain a smart contract vulnerability detection model (DH-GNN);
[0056] Specifically, in actual operation, the smart contract data set can be divided, and 80% of it can be randomly used as a training set and the other 20% can be used as a test set. The training set is used to train the model, and the test set is used to evaluate the model performance.
[0057] S104: Input the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain the vulnerability detection result.
[0058] The graph neural network-based smart contract vulnerability detection method provided by the embodiment of the present invention converts the smart contract source code into a smart contract graph, which can more effectively utilize the semantic information of the smart contract context, and then use the graph neural network to automatically perform vulnerability detection on the smart contract, thereby being able to cope with complex and changeable smart contract application scenarios, improve the accuracy of vulnerability detection, and reduce the underreporting rate of smart contract vulnerability detection.
[0059] In one embodiment, Figure 2 As shown, the process of converting the smart contract source code into the smart contract graph in the embodiment of the present invention specifically includes:
[0060] Extract function information and variable information from the smart contract source code, define functions and key variables as nodes, and convert the relationship between variables and functions into edges in the graph. Specifically, functions are primary nodes and key variables are secondary nodes; the types of edges are forward edges, data flow edges, and control flow edges.
[0061] It can be understood that key variables refer to variables selected from all variables that play a key role in the execution logic of the smart contract source code; the selection method can be customized by the user, and the present invention will not repeat it. Specifically, the node corresponding to the function is used as the main node, and the node corresponding to the face change is used as the secondary node.
[0062] Furthermore, considering that the main nodes and secondary nodes sometimes cannot truly and effectively reflect the execution order and data flow information of the smart contract, therefore, on the basis of the above-mentioned smart contract graph, the embodiment of the present invention also adds a fallback node, that is, the node types in the smart contract graph generated by the embodiment of the present invention mainly include main nodes, secondary nodes and fallback nodes. The smart contract graph can completely retain the node information, can better utilize the functions of the smart contract, and improve the accuracy of model detection. At the same time, after adding the fallback node, the edge type between the fallback node and the adjacent node is defined as a fallback edge; that is, at this time, four types of node edges can be constructed, namely control flow edges, data flow edges, forward edges and fallback edges. It can be understood that the introduction of edge types can better distinguish between data flow and control flow.
[0063] It can be understood that the edges in the smart contract graph describe the transmission process of data flow and control flow in the contract, and also reflect variable transfer and function calls. Therefore, in order to reflect the execution order of the program as much as possible, the edges can be numbered on the basis of classification.
[0064] Furthermore, in actual scenarios, different edge types sometimes also mean the probability of a contract containing a vulnerability. For example, in the reentrancy vulnerability graph structure, the data flow edge type of the account balance node can better highlight whether the contract contains a reentrancy vulnerability than the control flow edge type. Therefore, based on the above edge types, the embodiment of the present invention also assigns different priorities to each type of edge.
[0065] It can be understood that by numbering and classifying the edges, the semantic information and execution logic of the code can be maximized and the relational structure can be retained; and by setting priorities for the edges, the model can pay different degrees of attention to different types of edges during the learning process. Specifically, the smaller the priority value, the higher the degree of attention. It will be mentioned below that different weights are assigned to edges of different priorities through the time-enhanced attention network, so as to better improve the accuracy of vulnerability detection. Among them, the definition and priority setting of the edges are shown in Table 1.
[0066] Table 1 Edge types and corresponding priorities
[0067]
[0068] The final generated contract diagram is as follows Figure 2As shown in (a) and (b), function nodes M1, M2, and M3 are primary nodes, corresponding to withdraw, call.value, and deposit functions, respectively. Variables S1 and S2 in the function are secondary nodes, corresponding to balances[msg.sender] and _amount, respectively. The contract starts from M1 and reaches S1 through the forward edge. S1 reaches S2 through the data flow, and S2 reaches M2 through the control flow. S1 updates itself, triggering the ring data flow edge, and then reaches S2 again through the data flow. S2 triggers the M3 function call through the forward edge.
[0069] The contract graph extracted from a single smart contract according to the above process may be interfered by irrelevant functions, so the graph structure needs to be further simplified. In order to simplify the graph structure, the embodiment of the present invention normalizes the contract graph based on the smart contract graph generated by the above process, and marks the features of the edges between different nodes. The normalization process mainly includes: retaining all the main nodes in the contract graph, removing the remaining nodes and calculating their features, and passing their features to the adjacent main nodes; retaining the edges connected to the removed nodes, and moving the starting node or the end node of the edge to the corresponding main node; updating the features of the main node by aggregating the features of the removed nodes adjacent to the main node; and finally obtaining a normalized graph. At this time, the normalized graph is composed of function nodes, the link relationship is generated by the original edge link, and the function nodes are normalized by the original function features and the variable features associated with them.
[0070] The processed normalized graph is used as the input of the graph neural network model. During the training process, the neural network will receive a large number of normalized graphs constructed by smart contract functions and their true labels, and output vulnerability detection results after a large number of training times.
[0071] In one embodiment, as shown in FIG3 , the DH-GNN model in the embodiment of the present invention mainly includes a message propagation stage, a timing enhancement stage, and a detection stage.
[0072] Message propagation stage: define the edge in the smart contract graph as a time edge, define the start node and end node of the time edge as the nodes at both ends of the edge, and define the interaction process between the nodes in the smart contract graph as the message propagation process of the message being transmitted from its start node to its end node along the time edge. Update the node features according to the message propagation process to obtain the first node feature h′ of the node. i .
[0073] Specifically, in form, the smart contract graph can be represented as G = (υ, ε); where υ represents the set of nodes in the smart contract graph, ε represents the set of edges in the smart contract graph, and ε = {ε 1 ,ε2 ,…,ε k ,…,ε n}, that is, ε k In the message propagation stage, the model continuously transmits messages along the time edge in chronological order, with one edge per time step. In this embodiment, when the time step is 0, each node υ i The features are used to initialize its own hidden state It can also be understood as node v i Embedding in the initial state (state 0); then, the hidden state of the node is gradually updated in the message passing; when the time step is n, the message flows through the nth time edge ε n And update the hidden state of the end node.
[0074] At a certain time edge ε n As an example, the update process of the end node can be specifically expressed as follows: First, according to ε n The hidden state of the starting node and edge type t n Compute the original message x n , as shown in formula (1); then, the original message is converted into a vector embedding, as shown in formula (2); then, the end node can update its own hidden state according to the input original message features and its own historical hidden state, as shown in formulas (3) and (4).
[0075]
[0076] m n =W n x n +q n (2)
[0077]
[0078] in, Represents ε n The hidden state of the end node of ; Represents the splicing symbol, m n Represents x n The corresponding vector embedding is represents the intermediate vector embedding, U, Z and R all represent learnable matrices, and the matrix W n and vector q n , are network parameters, q 1 and q 2 Both represent learnable bias vectors, and tanh is an activation function used to map the transformed feature representation to the range between -1 and 1.
[0079] Time enhancement stage: The graph attention mechanism is used to calculate the attention coefficient of each node in the smart contract graph to its neighboring nodes, which is defined as the node attention coefficient; and the attention coefficient of the edge between two adjacent nodes, which is defined as the edge attention coefficient; according to the node attention coefficient and edge attention coefficient of each node, the neighboring node features of the node are aggregated to obtain the second node feature h′ of the node vi ; Use the self-attention mechanism to the second node feature h′ of the node vi Perform linear transformation to obtain the node weight γ of each node i ;
[0080] Specifically, in the time enhancement stage, the graph attention mechanism is first used to update the node features and edge features in the input smart contract graph, and then a new attention coefficient is calculated based on the updated smart contract graph to generate graph features. By combining with the graph attention mechanism, the relationship between nodes and the node's own features can be fully considered, thereby extracting more representative graph features and achieving the purpose of time series enhancement.
[0081] The calculation process of the node attention coefficient specifically includes:
[0082] S201: With node v i Its neighbor node v j For example, assume that the features of the two nodes after GNN training and updating are h i and h j , according to formula (5), we can calculate node v i Its neighbor node v j The inter-node attention score e ij ;
[0083] e ij =LeakyReLu(o[W 1 h i ||W 1 h j ]) (5)
[0084] Among them, LeakyReLu is the activation function, o is the learnable attention weight vector, o∈R 2F' ,|| represents the concatenation operation of vectors, W 1 is a learnable parameter matrix, W 1 ∈R F×F' ; F represents the dimension of node embedding, and F' represents the dimension of updated node embedding.
[0085] S202: For a given node v i , itself and its neighbor node v jThe attention scores between them are subjected to a softmax operation to generate attention weights α ij , that is, the node attention coefficient;
[0086]
[0087] Among them, exp(x) represents the calculation of the natural exponential function e x The value of , softmax is the activation function, N(i) represents the node v i The set of neighbor nodes.
[0088] Similarly, the calculation process of the edge attention coefficient includes:
[0089] According to formula (7) and formula (8), the attention coefficient β that describes the edge feature is obtained by updating the edge feature separately. ij ;
[0090] ε ij =LeakyReLu(o[W 2 h i2 ||W 2 h j2 ]) (7)
[0091]
[0092] Among them, W 2 The meaning of W 1 Similar, no further description is given here. i2 and h j2 Respectively represent h i and h j That is, α ij is learned from all the features of the node, and β ij It is only learned from the edge features of the nodes.
[0093] Furthermore, according to the node attention coefficient and edge attention coefficient of each node, the neighbor node features of the node are aggregated to obtain an updated node, specifically comprising: firstly adding the calculated node attention coefficient and edge attention coefficient according to a preset weight p (in this embodiment, the value of p is set according to the priority value of the edge) to obtain a new attention coefficient matrix A, as shown in formula (9), so as to enhance the influence of the temporal features of the edge on the classification result; and then using the new attention coefficient matrix A to aggregate the neighbor node features and update the node information, as shown in formula (10).
[0094] A=(1-p)*α ij +p*β ij (9)
[0095] h′vi =σ(∑ j∈N(i) A ij W′h j +h i ) (10)
[0096] Among them, σ represents the sigmoid activation function, W′ is the learnable matrix, and N(i) represents the node v i The neighbor node set A ij Represents node v i With node v j The attention coefficient, h′ vi Indicates the updated node information.
[0097] After obtaining the updated node information h′ vi After that, the self-attention mechanism is used to perform a linear transformation, and the node features and edge features are further integrated into the global representation of the graph, effectively capturing the dependency and semantic information between nodes and edges to obtain the contribution of the node to the entire graph feature γ i , also called node g i On all its neighbor nodes g k The influence ratio of ; as shown in formula (11) and formula (12).
[0098] g i =tanh(W G h′ vi +q) (11)
[0099]
[0100] Among them, W G is the weight matrix, q is the bias vector, and the tanh function maps the transformed feature representation to the range between -1 and 1, thus producing the potential weights of the normalized graph. i Between 0 and 1.
[0101] From the above process, we can see that by learning the potential connections between the category features of subgraphs through the self-attention mechanism, we can aggregate the features of each node and the edge features between different nodes to obtain the global representation of the graph, thereby capturing the overall features of the graph. This attention mechanism helps the model to understand the structure and semantic information of the graph more deeply, while integrating the global insights of nodes and edges, thereby enhancing the model's ability to express and generalize graph properties.
[0102] Detection phase: According to the node weights γ of all nodes i and the first node feature h′ i , generate vulnerability detection results for smart contracts.
[0103] Specifically, the detection process can be expressed as follows:
[0104]
[0105] in, represents the predicted vulnerability label, ⊙ represents the element-wise product, sigmoid is the activation function that maps the result to 0 or 1; |v| represents the number of nodes in the smart contract graph.
[0106] In the embodiment of the present invention, the semantic relationship of the smart contract context is fully considered when constructing the smart contract graph, and the smart contract fallback function is added to the construction of the smart contract graph. At the same time, different weights are assigned to edges of different priorities through the time-series enhanced attention network, and they are integrated into the attention coefficient matrix to obtain the final node weight γ i , thereby better improving the accuracy of vulnerability detection.
[0107] It is understandable that during the training process, the graph neural network will receive a large number of smart contract graphs (in this embodiment, normalized graphs are used) constructed from the smart contract source code and their real labels. During the testing process, the trained model is used to receive the normalized graph of the smart contract to be tested and generate vulnerability detection labels. The whole process is fully automated.
[0108] In order to comprehensively and reasonably evaluate the performance of the model of the present invention, the present invention also provides the following experimental data.
[0109] (1) Evaluation indicators: Accuracy, recall, precision, and F1 value are selected as evaluation indicators. Among them, accuracy measures the overall accuracy of model classification. Recall measures the model's ability to capture positive samples and is suitable for scenarios that focus on omissions or underreporting. Precision measures the accuracy of the model's prediction of positive samples and is suitable for scenarios that focus on misjudgments. F1 value is suitable for scenarios that require a trade-off between precision and recall, and can be used to evaluate the overall performance of the model. The calculation formulas for each indicator are as follows:
[0110]
[0111] (2) Experimental environment: A deep learning framework based on PyTorch 1.10.2 was established to verify the performance of the DH-GNN model. The language environment Python version is 3.8, the processor is the 13th Gen Intel(R) Core(TM) i7-13700H, the GPU is NVIDIAGeForceRTX4060, the operating system is Microsoft Windows 11, and the protocols and libraries required for deep learning are followed during the experiment.
[0112] (3) Training parameter setting: The adam optimizer is used in the DH-GNN model. Through continuous experiments, the optimal parameter settings are found: the learning rate is set to 0.001, the training round is set to 170, the patience is set to 200, and the hidden layer is set to 256. In order to overcome the problem of overfitting, the HoldOut cross-validation method is chosen. For each data set, 80% of it is randomly selected as the training set and the other 20% as the test set. Multiple tests are performed and the average results are reported.
[0113] The experimental results are as follows Figure 4 As shown in the figure, according to the comparison of experimental results, compared with traditional vulnerability detection methods such as Smartcheck, Mythril, Oyente, Securify, Slither, and new deep learning methods such as DR-GCN, Perculiar, TMP and AME, the model DH-GNN proposed in the present invention shows better performance in the detection of reentrancy vulnerabilities and timestamp dependency vulnerabilities.
[0114] Figure 5 An example of a physical structure diagram of an electronic device is shown in FIG. Figure 5 As shown, the electronic device may include: a processor 501, a communication interface 502, a memory 503 and a communication bus 504, wherein the processor 501, the communication interface 502 and the memory 503 communicate with each other through the communication bus 504. The processor 501 may call the logic instructions in the memory 503 to execute the smart contract vulnerability detection method, which includes: constructing a smart contract data set containing vulnerability labels; converting each smart contract source code in the smart contract data set into a corresponding smart contract graph; training a preset graph neural network using the smart contract graph corresponding to the smart contract data set to obtain a smart contract vulnerability detection model; inputting the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain a vulnerability detection result.
[0115] In addition, when the logic instructions in the above-mentioned memory 503 are implemented in the form of software functional units and sold or used as independent products, they can be stored in a computer-readable storage medium. Based on such an understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art or the part of the technical solution, can be embodied in the form of a software product, and the computer software product is stored in a storage medium, including several instructions for a computer device (which can be a personal computer, a server, or a network device, etc.) to perform all or part of the steps of the method described in each embodiment of the present invention. The aforementioned storage medium includes: various media that can store program codes, such as a USB flash drive, a mobile hard disk, a read-only memory (ROM), a random access memory (RAM), a magnetic disk or an optical disk.
[0116] An embodiment of the present invention also provides a computer program product, which includes a computer program stored on a non-transitory computer-readable storage medium, and the computer program includes program instructions. When the program instructions are executed by a computer, the computer can execute the methods provided by the above-mentioned method embodiments, for example, including: constructing a smart contract data set containing vulnerability labels; converting each smart contract source code in the smart contract data set into a corresponding smart contract graph; using the smart contract graph corresponding to the smart contract data set to train a preset graph neural network to obtain a smart contract vulnerability detection model; inputting the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain a vulnerability detection result.
[0117] An embodiment of the present invention also provides a non-transitory computer-readable storage medium having a computer program stored thereon. When the computer program is executed by a processor, the methods provided by the above-mentioned method embodiments are implemented, for example, including: constructing a smart contract data set containing vulnerability labels; converting each smart contract source code in the smart contract data set into a corresponding smart contract graph; using the smart contract graph corresponding to the smart contract data set to train a preset graph neural network to obtain a smart contract vulnerability detection model; inputting the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain a vulnerability detection result.
[0118] Through the description of the above implementation methods, those skilled in the art can clearly understand that each implementation method can be implemented by means of software plus a necessary general hardware platform, and of course, it can also be implemented by hardware. Based on this understanding, the above technical solution is essentially or the part that contributes to the prior art can be embodied in the form of a software product, and the computer software product can be stored in a computer-readable storage medium, such as ROM / RAM, a disk, an optical disk, etc., including a number of instructions for a computer device (which can be a personal computer, a server, or a network device, etc.) to execute the methods described in each embodiment or some parts of the embodiments.
[0119] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, rather than to limit it. Although the present invention has been described in detail with reference to the aforementioned embodiments, those skilled in the art should understand that they can still modify the technical solutions described in the aforementioned embodiments, or make equivalent replacements for some of the technical features therein. However, these modifications or replacements do not deviate the essence of the corresponding technical solutions from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A smart contract vulnerability detection method based on graph neural network, characterized in that: include: Step 1: Build a smart contract dataset with vulnerability labels; Step 2: Convert each smart contract source code in the smart contract data into the corresponding smart contract graph; Step 3: Use the smart contract graph corresponding to the smart contract dataset to train the preset graph neural network to obtain a smart contract vulnerability detection model; Step 4: Input the smart contract graph corresponding to the smart contract to be tested into the smart contract vulnerability detection model to obtain the vulnerability detection result.
2. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 1 is characterized in that: Before converting the smart contract source code into the corresponding smart contract graph, it also includes: filtering out the honeypot contract source code and / or noise information in the smart contract source code.
3. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 1 is characterized in that: Step 2 specifically includes: Extract function information and corresponding variable information from the given smart contract source code; According to the extracted function information and corresponding variable information, the functions and key variables are used as nodes, and the relationship between the functions and key variables is used as edges, so as to generate the initial smart contract graph; among which, the functions are the main nodes and the key variables are the secondary nodes; among which, the edge types are divided into forward edges, data flow edges and control flow edges; According to the overall execution order and data flow information of the given smart contract source code, a fallback node is introduced into the initial smart contract graph, and the edge type between the fallback node and the adjacent node is defined as a fallback edge, thereby generating the final smart contract graph.
4. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 3 is characterized in that: Step 2 specifically also includes: normalizing the final smart contract graph; the normalization process includes: retaining all main nodes in the smart contract graph, removing the remaining nodes and calculating the features of the removed nodes, and passing their features to adjacent main nodes; retaining the edges connected to the removed nodes, and moving the starting node or the end node of the edge to the corresponding main node; updating the features of the main node by aggregating the features of the removed nodes adjacent to the main node; and finally obtaining a normalized graph.
5. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 1 is characterized in that: Step 3 specifically includes: Message propagation stage: The edge in the smart contract graph is defined as a time edge, and the two end nodes of the edge are defined as the starting node and the ending node of the time edge respectively. The interaction process between the nodes in the smart contract graph is defined as the message propagation process of the message being transmitted from its starting node to its ending node along the time edge. The node features are updated according to the message propagation process to obtain the first node feature h of the node. ′ i ; Time enhancement stage: The graph attention mechanism is used to calculate the attention coefficient of each node in the smart contract graph to its neighbor nodes, which is defined as the node attention coefficient; and the attention coefficient of the edge between two adjacent nodes, which is defined as the edge attention coefficient; according to the node attention coefficient and edge attention coefficient of each node, the neighbor node features of the node are aggregated to obtain the second node feature h′ of the node vi ; Use the self-attention mechanism to the second node feature h′ of the node vi Perform linear transformation to obtain the node weight γ of each node i ; Detection phase: According to the node weights γ of all nodes i and the first node feature h′ i , generate vulnerability detection results for smart contracts.
6. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 5 is characterized in that: In the message propagation phase, the hidden state of the end node is updated as follows: Among them, ε n represents the nth time edge through which the message flows, Represents ε n The hidden state of the end node of n Indicates the edge type, Represents ε n The hidden state of the starting node, Represents the splicing symbol, x n Represents the original message, m n Represents x n The corresponding vector embedding is represents the intermediate vector embedding, U, Z and R all represent learnable matrices, and the matrix W n and vector q n are network parameters, q1 and q2 represent learnable bias vectors, and tanh is the activation function.
7. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 5 is characterized in that: The graph attention mechanism is used to calculate the attention coefficient of each node in the smart contract graph to its neighboring nodes, which is defined as the node attention coefficient; And the attention coefficient of the edge between two adjacent nodes, defined as the edge attention coefficient, specifically includes: e ij =LeakyReLu(o[W1h i ||W1h j ]) ε ij =LeakyReLu(o[W2h i2 ||W2h j2 ]) Among them, e ij Represents node v i Its neighbor node v j The inter-node attention score between ij Represents node v i Its neighbor node v j The node attention coefficient between them, ε ij Represents node v i Its neighbor node v j The edge attention score between ij Represents node v i Its neighbor node v j The edge attention coefficients between them, W1 and W2 represent the learnable matrices, h i and h j Respectively represent the node v i and its neighbor node v j The characteristics of h i2 and h j2 Respectively represent h i and h j The edge features in , o represents the learnable attention weight vector, || represents the concatenation operation of the vector, LeakyReLu and softmax are activation functions, and N(i) represents the node v i The set of neighbor nodes.
8. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 7 is characterized in that: According to the node attention coefficient and edge attention coefficient of each node, the neighbor node features of the node are aggregated to obtain the second node feature h′ of the node vi , specifically including: Calculate the attention coefficient matrix A according to the following formula, and then use the attention coefficient matrix A to aggregate the node's neighbor node features according to the following formula to obtain the node's second node feature h′ vi ; A=(1-p)*α ij +p*β ij h′ vi =σ(∑ j∈N(i) A ij W′h j +h i ) Where p represents the preset weight, σ represents the sigmoid activation function, W′ is a learnable matrix, and N(i) represents the node v i The set of neighbor nodes.
9. The method for detecting smart contract vulnerabilities based on graph neural network according to claim 5 is characterized in that: According to the node weights γ of all nodes i and the first node feature h′ i , generate the vulnerability detection results of the smart contract, including: in, represents the predicted vulnerability label, ⊙ represents the element-wise product, sigmoid is the activation function, and |υ| represents the number of nodes in the smart contract graph.
10. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein: When the processor executes the program, the method according to any one of claims 1 to 9 is implemented.