Intelligent contract vulnerability detection method based on code slices and neural network

Through the method based on code slicing and neural network, smart contract code is statically analyzed, timestamp dependence vulnerabilities and unchecked external call vulnerabilities, and vulnerability detection is solved, which is difficult to efficiently detect smart contract vulnerabilities in the existing technology, and accurate and efficient detection of complex contracts is achieved.

CN119720217AInactive Publication Date: 2025-03-28CHINA UNIV OF PETROLEUM (EAST CHINA)

Patent Information

Application Number
CN202411785652.0
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Priority Date
2024-11-11
Filing Date
2024-12-06
Publication Date
2025-03-28
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

It is difficult to accurately and effectively detect smart contract vulnerabilities in the existing technology, especially when facing complex contracts, path explosion and rapid growth in resource consumption, which is difficult to detect efficiently.

Method used

Using a smart contract vulnerability detection method based on code slicing and neural networks, a control flow graph is generated through static analysis, deep priority traversal detects timestamp dependency vulnerabilities and unchecked external call vulnerabilities, normalizes the code and converts code statements into vector representations using Doc2Vec technology to build a multi-layer graph convolutional neural network for vulnerability detection.

Benefits of technology

It realizes accurate and efficient detection of smart contract vulnerabilities, can effectively identify vulnerabilities in complex contracts, and improves the accuracy and efficiency of detection.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119720217A_ABST
    Figure CN119720217A_ABST
Patent Text Reader

Abstract

The invention provides an intelligent contract vulnerability detection method based on code slices and a neural network, and relates to the technical field of contract vulnerability detection, and the method specifically comprises the following steps: carrying out the static analysis of an intelligent contract code; checking a program execution path through depth-first traversal of the control flow diagram, detecting timestamp dependent vulnerabilities and unchecked external call vulnerabilities, and positioning vulnerability paths in the control flow diagram according to nodes corresponding to vulnerability statements; normalizing the smart contract code, removing smart contract code annotations, unifying variables and function naming, not renaming related state information related variables, converting a smart contract code statement into vector representation, and training and updating a vector; constructing a multilayer graph convolutional neural network as a neural network model for training and detecting vulnerabilities; and outputting a detection result by the multilayer graph convolutional neural network. According to the technical scheme, the problem that the intelligent contract vulnerability cannot be accurately and effectively detected in the prior art is solved.
Need to check novelty before this filing date? Find Prior Art

Description

[0001] This patent application claims priority to Chinese patent application No. 2024115973799 filed on November 11, 2024. Technical Field

[0002] The present invention relates to the technical field of contract vulnerability detection, and in particular to a smart contract vulnerability detection method based on code slicing and neural network. Background Art

[0003] Blockchain has the characteristics of decentralization and data immutability, and was originally used to implement cryptocurrency. The emergence of Ethereum has promoted the development of blockchain technology. The Ethereum platform supports smart contracts, and its programming language Solidity enables developers to execute complex program logic on the blockchain, expanding the application scenarios of blockchain. Based on the immutable characteristics of blockchain, smart contracts can be used as distributed ledgers, and the immutable characteristics of its data make it applicable in many fields such as finance, Internet of Things, and law.

[0004] There are some security issues with smart contracts. First, the writing and running of smart contracts are highly coupled, and there are dependencies between different contract codes, which increases the difficulty of development and easily leads to logical vulnerabilities and unexpected code execution. Secondly, the underlying code of Solidity smart contracts is written in C++, runs on a computer platform, and stores data in binary format. Therefore, traditional vulnerabilities in the C++ language and common vulnerabilities in computer languages ​​will reappear in smart contracts, such as integer overflow vulnerabilities. Furthermore, blockchain data cannot be tampered with. If there are vulnerabilities after the deployment of smart contracts, they cannot be repaired by traditional patching methods. Losses can only be reduced by stopping transactions or forking. Finally, the source code of smart contracts is transparent. The source code of most mainstream blockchains and public chains is open, and the stack-based virtual machine implementation is relatively simple. Attackers can easily decompile the compiled bytecode to obtain the source code, which reduces the attack threshold and provides convenience for attackers to analyze the source code and discover vulnerabilities.

[0005] In order to ensure the security of smart contract code, researchers have conducted research on automated detection methods for smart contract vulnerabilities. Existing vulnerability detection methods include symbolic execution technology and fuzz testing technology, but there are problems when used alone. Symbolic execution technology can achieve high code coverage and traverse all code paths in sufficient time, but when dealing with complex code, path explosion will occur, resulting in low detection efficiency. Fuzz testing technology detects vulnerabilities by improving the number and quality of test cases and monitoring abnormal behaviors during execution. The execution process is more efficient, but blind testing may not cover most areas of the program, lacks fine-grained search strategies, and is difficult to test complex conditional branches.

[0006] In the field of smart contract vulnerability detection, relevant research has been conducted at home and abroad. Although tools based on symbolic execution technology such as Oyente, Osiris, Manticore, SmarTest, ExGen, etc. provide references for subsequent research, they face the problems of path explosion and rapid growth of resource consumption, and it is difficult to efficiently detect complex contracts. Tools based on fuzz testing technology such as ContractFuzzer, sFuzz, SmartGift, ItyFuzz, EF / CF, etc. have the problem of difficulty in covering complex conditional branches. Smart contract vulnerability detection tools based on machine learning and deep learning, such as SmartEmbed, S-gram, SCScan, methods based on improved convolutional neural networks, smart contract honeypot vulnerability detection solutions based on machine learning, methods combining abstract syntax trees and code slicing, Eth2Vec, etc., bring new insights to blockchain security. These tools still face challenges in fully capturing key contract code and extracting vulnerability-related features.

[0007] Therefore, there is a need for a smart contract vulnerability detection method based on code slicing and neural networks that can accurately and effectively detect smart contract vulnerabilities. Summary of the invention

[0008] The main purpose of the present invention is to provide a smart contract vulnerability detection method based on code slicing and neural network to solve the problem that the prior art cannot accurately and effectively detect smart contract vulnerabilities.

[0009] To achieve the above object, the present invention provides a smart contract vulnerability detection method based on code slicing and neural network, which specifically includes the following steps:

[0010] S1, static analysis of smart contract code, including: using Python's evm_cfg_builder library to generate control flow graph CFG and extract data dependencies.

[0011] S2, checks the program execution path by depth-first traversal of the control flow graph, detects timestamp dependency vulnerabilities and unchecked external call vulnerabilities, and locates the vulnerable path in the control flow graph according to the corresponding nodes of the vulnerable statements.

[0012] S3, standardizes the smart contract code, removes smart contract code comments, unifies variable and function names, does not rename variables related to relevant status information, uses Doc2Vec technology to convert smart contract code statements into vector representations, and trains and updates vectors.

[0013] S4, builds a multi-layer graph convolutional neural network as a neural network model for training and detecting vulnerabilities.

[0014] In S5, a multi-layer graph convolutional neural network determines whether the new contract has vulnerabilities based on the learned vulnerability patterns and features, and finally outputs the detection results.

[0015] Furthermore, step S1 specifically includes the following steps:

[0016] S1.1, use Python's evm_cfg_builder library to analyze the statement execution relationship in the smart contract code and generate the control flow graph CFG corresponding to the smart contract code. In the control flow graph, the node represents each line of statement in the smart contract code, and the connection edge between the nodes represents the jump relationship between statements; in each node, define a variable to store the information of the parent node corresponding to the node.

[0017] S1.2, by performing backward analysis on the key nodes in CFG and backtracing along the control flow path, during the backtracing process, the variables in each statement and the data dependencies of the variables are extracted, and the dependency chain of the variables on the key path related to the vulnerability is gradually constructed, where the key nodes include: the statement nodes where the vulnerability exists.

[0018] Furthermore, step S2 specifically includes the following steps:

[0019] S2.1, use the depth-first traversal algorithm to traverse the control flow graph in depth first, starting from a starting node of the control flow graph, visiting nodes along a path until it is impossible to move forward, then backtracking to the last node that was not fully explored, and continue to explore other paths to check the various execution paths of the smart contract code.

[0020] S2.2, Detect timestamp dependency vulnerabilities.

[0021] S2.3, for the detection of unchecked external call vulnerabilities, first check whether there is a call to the send or call function in the smart contract code. If so, then continue to check whether the return result of the function call is checked using a conditional statement. If there is no conditional statement to check the return result, then the smart contract code has an unchecked external call vulnerability.

[0022] S2.4, based on the node corresponding to the vulnerable statement, perform backward analysis in the control flow graph of the smart contract code to locate the path corresponding to the vulnerable statement node from the smart contract code input.

[0023] Furthermore, in step S2.2, for the timestamp dependency vulnerability, two situations are detected:

[0024] In the first case, if there is a conditional statement such as if or while in the smart contract code, and a variable is used in the corresponding condition of the conditional statement, then the conditional statement will be marked as a statement with a timestamp dependency vulnerability.

[0025] In the second case, if a variable is used for a transfer operation, and the variable’s data dependency contains a timestamp variable called block.timestamp, then the statement containing the variable also has a vulnerability.

[0026] Furthermore, step S3 specifically includes the following steps:

[0027] S3.1, in the process of statement normalization, first remove the comments in the smart contract code, and then rename the variables to "VARn" in the order of their appearance in the smart contract code, where n represents an integer number, and the functions are named "FUNCn" in order.

[0028] S3.2, only rename state variables and function local variables, do not rename variables related to state information on the chain.

[0029] S3.3, use Doc2Vec technology to convert smart contract code statements into vector representations. Given a training sequence w1,w2,w3,…w consisting of words in the smart contract code, T , the Doc2Vec function formula is shown in formula (1):

[0030]

[0031] Among them, N is the normalization factor used to find the average value, w i For prediction tasks, p is the probability distribution of the current word segmentation, T is a specific value that determines the upper limit of the summation, and k is a specific value that determines the starting position of the summation;

[0032] Use multi-classifier softmax to complete the prediction task. The specific formula is shown in formula (2):

[0033]

[0034] Where exp is the natural exponential function, Represents the jth element in the output word segmentation vector.

[0035] In formula (2) Represents the jth element in the output word segmentation vector, It is calculated from the unnormalized logarithmic probability distribution vector, and the calculation formula is:

[0036]

[0037] Among them, W is the word segmentation matrix, b and U are the parameters of the softmax classifier, and the h function represents the connection operation of the word vector.

[0038] S3.4, use the stochastic gradient descent algorithm to automatically train and update the vector composed of smart contract code statements.

[0039] Furthermore, step S4 specifically includes the following steps:

[0040] S4.1, build a graph convolutional neural network. The core formula in the graph convolutional neural network is as follows:

[0041]

[0042] Among them, H (l) represents the feature matrix of the lth layer, σ represents the nonlinear activation function, Represents the degree matrix of the nodes in the graph, W (l) represents the trainable weight matrix of layer l, Represents the graph adjacency matrix after adding self-connection, that is:

[0043]

[0044] Where A represents the original adjacency matrix and I represents the identity matrix.

[0045] S4.2, building a multi-layer graph convolutional neural network model includes: three layers of graph convolutional neural network, two random inactivation layers and a linear layer connected in sequence.

[0046] The present invention has the following beneficial effects:

[0047] The present invention proposes a vulnerability detection method for smart contracts based on code slicing and neural networks. Through key path extraction, code normalization and vulnerability detection schemes, modeling is performed at the code statement level. The smart contract source code is used as input. After static analysis, vulnerability location, code normalization and graph neural network training, a model that can detect vulnerabilities is obtained. BRIEF DESCRIPTION OF THE DRAWINGS

[0048] In order to more clearly illustrate the specific implementation of the present invention or the technical solutions in the prior art, the following will briefly introduce the drawings required for the specific implementation or the prior art description. Obviously, the drawings described below are some implementations of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without creative work. In the drawings:

[0049] Figure 1Smart contract vulnerability detection training phase and vulnerability detection phase models based on code slicing and neural networks.

[0050] Figure 2 The structure diagram of the neural network model built for smart contract vulnerability detection based on code slicing and neural networks. DETAILED DESCRIPTION

[0051] The technical solution of the present invention will be described clearly and completely below in conjunction with the accompanying drawings. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of 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.

[0052] like Figure 1 The smart contract vulnerability detection method based on code slicing and neural network shown in the figure specifically includes the following steps:

[0053] S1, static analysis of smart contract code, including: using Python's evm_cfg_builder library to generate control flow graph CFG and extract data dependencies.

[0054] S2, checks the program execution path by depth-first traversal of the control flow graph (i.e., checks the smart contract code execution path) to detect timestamp dependency vulnerabilities and unchecked external call vulnerabilities, and locates the vulnerability path in the control flow graph according to the corresponding nodes of the vulnerability statements.

[0055] S3, standardizes the smart contract code, removes smart contract code comments, unifies variable and function names, does not rename variables related to relevant status information, uses Doc2Vec technology to convert smart contract code statements into vector representations, and trains and updates vectors.

[0056] S4, builds a multi-layer graph convolutional neural network as a neural network model for training and detecting vulnerabilities.

[0057] In S5, a multi-layer graph convolutional neural network determines whether the new contract has vulnerabilities based on the learned vulnerability patterns and features, and finally outputs the detection results.

[0058] like Figure 1As shown, in the smart contract vulnerability detection training phase, a lightweight static analysis is performed on the labeled smart contract dataset to obtain the program control flow graph. The defined smart contract vulnerability detection rules (i.e., leaky copper rules) are used to locate the key path of the code from the program control flow graph, and the parent node is traced back upward until the program input is reached. Then, the Doc2Vec embedding method is used to embed the key path related to the extracted smart contract code vulnerability, thereby obtaining the word embedding vector corresponding to the smart contract code statement, and the vector is used to replace the code statement in the original node, so that the feature of the node in the extracted graph is the word embedding vector. Finally, the word embedding vector is input into the graph convolutional neural network model to train the corresponding vulnerability detection model. In the vulnerability detection phase, the same static analysis is first performed on the unknown smart contract code to extract the program control flow graph, locate the program key path using the vulnerability rules, and extract the key path code statement vector. Then, the trained vulnerability detection model is used for prediction and the vulnerability detection result is output.

[0059] Specifically, the evm_cfg_builder library of Python is used to analyze the statement execution relationship in the smart contract code and generate a control flow graph corresponding to the source code. The nodes of the control flow graph represent each line of statement in the smart contract code, and the connecting edges represent the statement jump relationship. At the same time, the information of the parent node corresponding to each node is stored in each node, and the data dependency relationship between variables in the smart contract is extracted.

[0060] Step S1 specifically includes the following steps:

[0061] S1.1, Generate Control Flow Graph (CFG): In order to extract code slices related to vulnerabilities from smart contract codes, use Python's evm_cfg_builder library to analyze the statement execution relationship in the smart contract code and generate the control flow graph CFG corresponding to the smart contract code. In the control flow graph, the node represents each line of statement in the smart contract code, and the connecting edges between nodes represent the jump relationship between statements. In each node, a variable is defined to store the information of the parent node corresponding to the node. This detailed node and edge information helps the subsequent key path extraction module to locate the key path that triggers the vulnerability.

[0062] S1.2, by performing backward analysis on the key nodes in CFG, backtracking along the control flow path, extracting the variables in each statement and the data dependencies of the variables during the backtracking process, and gradually building the dependency chain of the variables on the key path related to the vulnerability, where the key nodes include: the statement nodes where the vulnerability exists. By analyzing the dependencies between variables, we can better understand the execution logic of the program and the flow of data. The extraction of data dependencies provides important basic information for subsequent vulnerability detection and analysis.

[0063] Specifically, according to the defined smart contract vulnerability detection rules, a depth-first traversal operation is performed on the control flow graph to locate statement nodes where smart contract vulnerabilities may exist. For timestamp dependency vulnerabilities, it is detected whether there is an if or while conditional judgment statement in the smart contract code and a variable is used in the condition, or a timestamp variable block.timestamp exists in the data dependency of a variable used for a transfer operation. For unchecked external call vulnerabilities, it is detected whether there is a call to the send or call function in the smart contract code. If so, it is further checked whether the return result of the function call is checked using a conditional statement (such as require). According to the node corresponding to the vulnerable statement, backward analysis is carried out in the program control flow graph to locate the path corresponding to the vulnerable statement node from the program input, and extract the relevant key path.

[0064] Step S2 specifically includes the following steps:

[0065] S2.1, Depth-first traversal of the control flow graph: Depth-first traversal is a graph traversal algorithm that uses the depth-first traversal algorithm to traverse the control flow graph in depth, starting from a starting node of the control flow graph and visiting nodes along a path until it is unable to move forward, then backtracking to the last node that was not fully explored and continuing to explore other paths to check the various execution paths of the smart contract code to ensure that no paths that may have vulnerabilities are missed.

[0066] S2.2, Detect timestamp dependency vulnerabilities.

[0067] S2.3, Unchecked external call vulnerability detection: In Ethereum, call, send and transfer functions can be used to perform external calls or transfer operations. The transfer function will throw an exception when the operation fails, causing the smart contract to terminate. However, if the call or send function is used, when the execution fails, the program (i.e., the smart contract code) will only return a false parameter. Even if the external call function execution process or transfer operation fails, the program code will continue to execute. Therefore, the developer needs to check whether the result of the function call is false. For the detection of unchecked external call vulnerabilities, first check whether there is a call to the send or call function in the smart contract code. If so, then continue to check whether the return result of the function call is checked using a conditional statement. If there is no conditional statement to check the return result, then the smart contract code has an unchecked external call vulnerability. This vulnerability may cause the smart contract to behave unpredictably when interacting with the outside world, thereby affecting the security of the contract.

[0068] S2.4, locate the vulnerability path: According to the node corresponding to the vulnerability statement, carry out backward analysis in the control flow graph of the smart contract code to locate the path corresponding to the vulnerability statement node from the smart contract code input. Through this backward analysis, the triggering path of the vulnerability in the smart contract code can be accurately determined, so as to better understand the cause and impact of the vulnerability. This method of locating the vulnerability path helps to deeply analyze the vulnerabilities of smart contracts and provide specific guidance for subsequent vulnerability repair and prevention.

[0069] Specifically, in step S2.2, for the timestamp dependency vulnerability, two situations are detected:

[0070] In the first case, if there is a conditional statement such as if or while in the smart contract code, and a variable is used in the corresponding condition of the conditional statement, then the conditional statement will be marked as a statement with a timestamp dependency vulnerability.

[0071] In the second case, if a variable is used for a transfer operation, and the variable's data dependency contains a timestamp variable, block.timestamp, then the statement containing the variable also has a vulnerability, because the transfer operation should be based on reliable conditions, and relying on a manipulable timestamp variable may lead to uncertainty in the transfer behavior and potential security risks.

[0072] Specifically, the comments in the smart contract code are removed, and the variables are renamed to "VARn" according to the order in which they appear in the code, and the functions are named "FUNCn", but the variables related to the on-chain status information are not renamed. Then, for each node in the control flow graph, the Doc2Vec technology is used to convert the standardized smart contract code statements into a word embedding vector.

[0073] Step S3 specifically includes the following steps:

[0074] S3.1, remove comments and unify naming: In the process of statement standardization, first remove the comments in the smart contract code, and then rename the variables to "VARn" in the order of appearance in the smart contract code, where n represents an integer number, and the functions are named "FUNCn" in order. This unified naming method helps to eliminate the differences in variable naming and code writing styles that may exist in different smart contract codes, making codes with similar structures and functions more unified in form.

[0075] S3.2, do not rename related variables: only rename state variables and function local variables, do not rename variables related to the on-chain state information; since the state variables and function local variables in the smart contract may have different names, and some variables related to the on-chain state and transfer operations have unified names, during the normalization operation, the invention only renames the state variables and function local variables, and does not rename variables related to the on-chain state information. The control flow graph after renaming only modifies the variable name, and does not affect the semantic information of the program, ensuring that the logic and function of the code are not affected by the normalization operation.

[0076] S3.3, word embedding vector conversion: Doc2Vec technology can be used to convert smart contract code statements into vector representations, so that code statements can be calculated and analyzed in the vector space. Doc2Vec is a powerful natural language processing (NLP) technology that can embed a piece of text into a high-dimensional vector space. Specifically, given a training sequence w1, w2, w3, … w consisting of word segments in the code T , the goal of Doc2Vec is to i The surrounding word segmentation w with a window size of 2k+1 i-k ,…,w i+k As the context, the word segmentation is predicted. In this way, the semantic relationship and context information between smart contract code statements can be captured. The Doc2Vec function formula is shown in formula (1):

[0077]

[0078] Among them, N is the normalization factor used to find the average value, w i For prediction tasks, p is the probability distribution of the current word segmentation, T is a specific value that determines the upper limit of the summation, and k is a specific value that determines the starting position of the summation;

[0079] Use multi-classifier softmax to complete the prediction task. The specific formula is shown in formula (2):

[0080]

[0081] Where exp is the natural exponential function, Represents the jth element in the output word segmentation vector;

[0082] In the Doc2Vec model, the softmax function is used to predict the probability distribution of the current word based on the context information, thereby achieving classification and prediction of the word. Represents the jth element in the output word segmentation vector, It is calculated from the unnormalized logarithmic probability distribution vector, and the calculation formula is:

[0083]

[0084] Among them, W is the word segmentation matrix, b and U are the parameters of the softmax classifier, and the h function represents the connection operation of the word vector. Through this formula, each element in the output word segmentation vector can be calculated, thereby realizing the prediction and classification of the word segmentation.

[0085] S3.4, use the stochastic gradient descent algorithm to automatically train and update the vector composed of smart contract code statements. The stochastic gradient descent algorithm is a commonly used optimization algorithm. It continuously adjusts the parameters of the model so that the output of the model gradually approaches the true value. In the training process of the Doc2Vec model, the stochastic gradient descent algorithm can be used to continuously adjust the parameters of the word segmentation matrix and the softmax classifier to maximize the average log-likelihood function. After the training is completed, the semantically similar code segmentations and sentence fragments in the output results will have a closer distance in the vector space.

[0086] Specifically, the word embedding vector is input into a neural network composed of a three-layer graph convolutional neural network and two random dropout layers and a linear layer for training. The information of different scales in the original data is captured by superposition of multi-layer graph convolutional neural network models. The random dropout layer is used to randomly discard the output of some nodes during the training process to prevent the model from overfitting. Finally, the features extracted from the graph convolutional network are mapped to the output space through the linear layer, and the final prediction results are output to obtain the vulnerability detection model.

[0087] Step S4 specifically includes the following steps:

[0088] S4.1, since there is an execution order relationship in the control flow graph of the smart contract code, and the previous code in the extracted critical path may affect the execution of the subsequent code, a multi-layer graph convolutional neural network is built as a neural network model for training and detecting vulnerabilities. The graph convolutional neural network has a message passing process, which allows the nodes in the graph to learn the characteristics of neighboring nodes from each other, thereby retaining the order relationship between the codes in the original control flow graph to a certain extent. The graph convolutional neural network is built, and the core formula in the graph convolutional neural network is as follows:

[0089]

[0090] Among them, H (l) represents the feature matrix of the lth layer, σ represents a nonlinear activation function, and the ReLU function is used in the present invention. Represents the degree matrix of the nodes in the graph, W (l) represents the trainable weight matrix of layer l, Represents the graph adjacency matrix after adding self-connection, that is:

[0091]

[0092] Where A represents the original adjacency matrix and I represents the identity matrix. Formula (5) describes the information transmission and feature update process between nodes in the graph convolutional neural network. Through continuous iterative calculation, the network can learn the features and patterns in the graph structure data.

[0093] S4.2, building a multi-layer graph convolutional neural network model includes: three layers of graph convolutional neural networks, two random dropout layers and linear layers connected in sequence. In addition, the graph convolutional network, the first random dropout layer, the first linear layer, the second random dropout layer and the second linear layer are connected in sequence. Figure 2 As shown, the present invention builds a neural network model consisting of a three-layer graph convolutional neural network and two random dropout layers and a linear layer, and inputs the word embedding vector into the graph convolutional network. Through the superposition of multiple layers of graph convolutional neural network models, the model can capture information of different scales in the original data, so that the network can better understand the complexity of graph structure data, and also enhance the generalization ability of the model. The random dropout layer can randomly discard the output of a part of the nodes during the training process, thereby preventing the model from overfitting. Finally, the features extracted from the graph convolutional network are mapped to the output space through the linear layer, and the final prediction result is output.

[0094] The superposition of multiple layers of graph convolutional neural network models can capture the complex patterns and features in the smart contract code. The role of the random inactivation layer is to increase the robustness of the model and prevent the model from over-relying on the information of certain nodes, thereby avoiding overfitting. The linear layer maps the features learned by the graph convolutional network to the output space and outputs the final vulnerability detection results. Through such a model structure design, the accuracy and reliability of smart contract vulnerability detection can be effectively improved.

[0095] Specifically, the same static analysis is performed on the unknown smart contract code to extract CFG, locate the critical path of the smart contract code, and extract the critical path code statement vector, so as to detect smart contract vulnerabilities.

[0096] 1) Extracting relevant information: For unknown smart contract codes, the invention first performs the same static analysis to extract the program control flow graph (CFG), generates the control flow graph corresponding to the code through the same method as the previous training stage, and then locates the critical path of the program. According to the vulnerability detection rules and the experience of the previous training stage, the critical path where the vulnerability may exist is determined, and the critical path code statement vector is extracted and input into the trained multi-layer graph convolutional neural network.

[0097] 2) The model determines whether a vulnerability exists: The multi-layer graph convolutional neural network analyzes and judges the input vector based on the vulnerability patterns and features learned during the training phase to determine whether the corresponding type of vulnerability exists in the new contract.

[0098] 3) Output test results: Based on the judgment of the model, output the test results on whether there are vulnerabilities in the new contract.

[0099] The present invention mainly adopts a method based on code slicing and neural networks to detect smart contract vulnerabilities, and designs a solution for critical path extraction, code normalization and vulnerability detection for smart contract scenarios. Different from the existing solution that chooses to model at the function call level, the present invention chooses to model at the code statement level, and takes the smart contract source code as input. First, a lightweight analysis module is used to perform statement-level analysis on the smart contract source code to obtain the program control flow graph of the smart contract code, and then according to the rules defined in the present invention, the corresponding critical paths are extracted for common smart contract vulnerabilities, and then the extracted critical path code is normalized, and the extracted key statements are encoded into word embedding vectors using Doc2Vec technology. Finally, a graph neural network is used to train the vector to obtain a model that can detect vulnerabilities.

[0100] Of course, the above description is not a limitation of the present invention, and the present invention is not limited to the above examples. Changes, modifications, additions or substitutions made by technicians in this technical field within the essential scope of the present invention should also fall within the protection scope of the present invention.

Claims

1. A smart contract vulnerability detection method based on code slicing and neural network, characterized in that: The specific steps include: S1, static analysis of smart contract code, including: using Python's evm_cfg_builder library to generate control flow graph CFG and extract data dependencies; S2, checks the program execution path by depth-first traversal of the control flow graph, detects timestamp dependency vulnerabilities and unchecked external call vulnerabilities, and locates the vulnerable path in the control flow graph according to the corresponding nodes of the vulnerable statements; S3, standardizes the smart contract code, removes smart contract code comments, unifies variable and function names, does not rename variables related to relevant state information, uses Doc2Vec technology to convert smart contract code statements into vector representations, and trains and updates vectors; S4, constructs a multi-layer graph convolutional neural network as a neural network model for training and detecting vulnerabilities; In S5, a multi-layer graph convolutional neural network determines whether the new contract has vulnerabilities based on the learned vulnerability patterns and features, and finally outputs the detection results.

2. According to claim 1, a smart contract vulnerability detection method based on code slicing and neural network is characterized in that: Step S1 specifically includes the following steps: S1.1, use Python's evm_cfg_builder library to analyze the statement execution relationship in the smart contract code and generate the control flow graph CFG corresponding to the smart contract code. In the control flow graph, the node represents each line of statement in the smart contract code, and the connection edge between the nodes represents the jump relationship between statements; In each node, define a variable to store the information of the parent node corresponding to the node; S1.2, by performing backward analysis on the key nodes in CFG and backtracing along the control flow path, during the backtracing process, the variables in each statement and the data dependencies of the variables are extracted, and the dependency chain of the variables on the key path related to the vulnerability is gradually constructed, where the key nodes include: the statement nodes where the vulnerability exists.

3. According to claim 1, a smart contract vulnerability detection method based on code slicing and neural network is characterized in that: Step S2 specifically includes the following steps: S2.1, using the depth-first traversal algorithm to traverse the control flow graph in depth, starting from a certain starting node of the control flow graph, visiting nodes along a path until it is impossible to move forward, then backtracking to the last node that was not fully explored, and continue to explore other paths to check the various execution paths of the smart contract code; S2.2, detect timestamp dependency vulnerabilities; S2.3, for the detection of unchecked external call vulnerabilities, first check whether there is a call to the send or call function in the smart contract code. If so, then continue to check whether the return result of the function call is checked using a conditional statement. If there is no conditional statement to check the return result, then the smart contract code has an unchecked external call vulnerability; S2.4, based on the node corresponding to the vulnerable statement, perform backward analysis in the control flow graph of the smart contract code to locate the path corresponding to the vulnerable statement node from the smart contract code input.

4. According to claim 3, a smart contract vulnerability detection method based on code slicing and neural network is characterized in that: In step S2.2, for the timestamp dependency vulnerability, two situations are detected: In the first case, if there is a conditional statement such as if or while in the smart contract code, and a variable is used in the corresponding condition of the conditional statement, then the conditional statement will be marked as a statement with a timestamp dependency vulnerability; In the second case, if a variable is used for a transfer operation, and the variable’s data dependency contains a timestamp variable called block.timestamp, then the statement containing the variable also has a vulnerability.

5. According to claim 1, a smart contract vulnerability detection method based on code slicing and neural network is characterized in that: Step S3 specifically includes the following steps: S3.1, in the process of statement normalization, first remove the comments in the smart contract code, then rename the variables to "VARn" in the order in which they appear in the smart contract code, where n represents an integer number, and the functions are named "FUNCn" in the order in which they appear; S3.2, only renames state variables and function local variables, and does not rename variables related to state information on the chain; S3.3, use Doc2Vec technology to convert smart contract code statements into vector representations. Given a training sequence w1,w2,w3,…w consisting of words in the smart contract code, T , the Doc2Vec function formula is shown in formula (1): Among them, N is the normalization factor used to find the average value, w i For prediction tasks, p is the probability distribution of the current word segmentation, T is a specific value that determines the upper limit of the summation, and k is a specific value that determines the starting position of the summation; Use multi-classifier softmax to complete the prediction task. The specific formula is shown in formula (2): Where exp is the natural exponential function, Represents the jth element in the output word segmentation vector; In formula (2) Represents the jth element in the output word segmentation vector, It is calculated from the unnormalized logarithmic probability distribution vector, and the calculation formula is: Among them, W is the word segmentation matrix, b and U are the parameters of the softmax classifier, and the h function represents the connection operation of the word vector; S3.4, use the stochastic gradient descent algorithm to automatically train and update the vector composed of smart contract code statements.

6. According to claim 1, a smart contract vulnerability detection method based on code slicing and neural network is characterized in that: Step S4 specifically includes the following steps: S4.1, build a graph convolutional neural network. The core formula in the graph convolutional neural network is as follows: Among them, H (l) represents the feature matrix of the lth layer, σ represents the nonlinear activation function, Represents the degree matrix of the nodes in the graph, W (l) represents the trainable weight matrix of layer l, Represents the graph adjacency matrix after adding self-connection, that is: Where A represents the original adjacency matrix and I represents the identity matrix; S4.2, building a multi-layer graph convolutional neural network model includes: three layers of graph convolutional neural network, two random inactivation layers and a linear layer connected in sequence.

Citation Information

Patent Citations

  • Intelligent contract multi-vulnerability detection method and system based on source code graph representation learning

    CN113360915A

  • Intelligent contract vulnerability detection method based on abstract syntax tree and application

    CN115017514A

  • Intelligent contract vulnerability detection method and device based on syntax and semantic feature fusion

    CN116089957A

  • Method, device and equipment for detecting contract vulnerability of block chain

    CN116150770A

  • Intelligent contract vulnerability detection method based on graph neural network

    CN116383832A

Cited By

  • Vulnerability hidden danger intelligent detection method based on large model

    CN121389128A

  • Intelligent contract vulnerability detection and repair system based on heterogeneous graph neural network

    CN121543093A

  • Smart Contract Vulnerability Detection and Repair System Based on Heterogeneous Graph Neural Network

    CN121543093B