Intelligent contract vulnerability detection method based on machine learning and dynamic-static combined analysis
This smart contract vulnerability detection method, which combines machine learning and dynamic/static analysis, accurately identifies the probability and complexity of smart contract vulnerabilities using a detection model and selects appropriate detection methods. This solves the problem of low vulnerability detection efficiency in existing technologies and achieves efficient and accurate vulnerability detection.
Patent Information
- Application Number
- CN202511885416.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-15
- Publication Date
- 2026-06-09
- Estimated Expiration
- 2045-12-15
Smart Images

Figure CN121834827B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of smart contract vulnerability detection technology, and in particular to a smart contract vulnerability detection method based on machine learning and dynamic-static combined analysis. Background Technology
[0002] In blockchain-related applications, smart contracts are an indispensable technology. Combined with blockchain, smart contracts can quickly implement corresponding contracts based on agreed-upon terms between business parties. At the same time, the security issues of smart contracts are becoming increasingly prominent, and vulnerability detection has attracted widespread attention.
[0003] In existing technologies, static analysis tools (such as Slither) can be used for static vulnerability detection of smart contracts, while dynamic analysis tools (such as Mythril) can be used for dynamic vulnerability detection. The former method is fast, but has poor vulnerability detection effectiveness (high false negative rate). The latter method has better vulnerability detection effectiveness, but is slower and consumes more computational resources. Excessive detection time and high resource consumption not only affect the efficiency of practical applications but also lead to a significant increase in deployment costs. Good efficiency is key to improving the practicality and scalability of vulnerability detection systems. Therefore, existing technologies suffer from either low vulnerability detection efficiency or poor vulnerability detection effectiveness.
[0004] There is currently no effective solution to the technical problems of low vulnerability detection efficiency or poor vulnerability detection effect in the existing technologies mentioned above. Summary of the Invention
[0005] The embodiments of this disclosure provide a smart contract vulnerability detection method, apparatus, and storage medium based on machine learning and dynamic-static combined analysis, so as to at least solve the technical problems of low vulnerability detection efficiency or poor vulnerability detection effect in the prior art.
[0006] According to one aspect of the present disclosure, a smart contract vulnerability detection method based on machine learning and dynamic / static combined analysis is provided, comprising: converting the smart contract to be detected into vector form to obtain corresponding input data; inputting the input data into a detection model to determine the vulnerability probability corresponding to the smart contract to be detected, wherein the vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability; if the detection model determines that the smart contract to be detected has a reentrancy attack vulnerability, determining the smart contract complexity of the smart contract to be detected; and determining the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity, and performing vulnerability detection on the smart contract to be detected according to the vulnerability detection method; wherein the detection model includes... The system comprises a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. The output layer includes a linear output head and a non-linear output head arranged in parallel. The operation of determining the vulnerability probability corresponding to the smart contract to be detected through the detection model includes: determining a first feature corresponding to the smart contract to be detected based on the sequence mixing layer; determining a corresponding second feature based on the first feature and the multi-head self-attention layer; determining a corresponding third feature based on the second feature and the feature mixing layer; inputting the third feature into the linear output head and the non-linear output head respectively to obtain the linear feature output by the linear output head and the non-linear feature output by the non-linear output head; fusing the linear feature and the non-linear feature to obtain a fused feature; and determining the vulnerability probability based on the fused feature.
[0007] According to another aspect of the present disclosure, a storage medium is also provided, the storage medium including a stored program, wherein, when the program is executed, a processor performs any of the methods described above.
[0008] According to another aspect of the embodiments of this disclosure, a smart contract vulnerability detection device based on machine learning and dynamic-static combined analysis is also provided, comprising: an input data determination module, used to convert the smart contract to be detected into vector form to obtain corresponding input data; a probability determination module, used to input the input data into a detection model, and determine the vulnerability probability corresponding to the smart contract to be detected through the detection model, wherein the vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability; a complexity determination module, used to determine the smart contract complexity of the smart contract to be detected if the detection model determines that the smart contract to be detected has a reentrancy attack vulnerability; and a detection method determination module, used to determine the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity. The system performs vulnerability detection on the smart contract to be tested according to the vulnerability detection method. The detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. The output layer includes parallel linear and non-linear output heads. A probability determination module is used to determine a first feature corresponding to the smart contract to be tested based on the sequence mixing layer; determine a corresponding second feature based on the first feature and the multi-head self-attention layer; determine a corresponding third feature based on the second feature and the feature mixing layer; input the third feature into the linear and non-linear output heads respectively to obtain the linear feature output by the linear output head and the non-linear feature output by the non-linear output head; fuse the linear and non-linear features to obtain a fused feature; and determine the vulnerability probability based on the fused feature.
[0009] According to another aspect of the present disclosure, a smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis is also provided, comprising: a processor; and a memory connected to the processor, configured to provide the processor with instructions for processing the following steps: converting the smart contract to be detected into vector form to obtain corresponding input data; inputting the input data into a detection model, determining the vulnerability probability corresponding to the smart contract to be detected through the detection model, the vulnerability probability representing the probability that the smart contract to be detected has a reentrancy attack vulnerability; determining the smart contract complexity of the smart contract to be detected if the detection model determines that the smart contract to be detected has a reentrancy attack vulnerability; and determining the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity, and performing vulnerability detection on the smart contract to be detected according to the vulnerability detection method; and The detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. The output layer includes a linear output head and a non-linear output head arranged in parallel. The operation of determining the vulnerability probability corresponding to the smart contract to be detected through the detection model includes: determining a first feature corresponding to the smart contract to be detected based on the sequence mixing layer; determining a corresponding second feature based on the first feature and the multi-head self-attention layer; determining a corresponding third feature based on the second feature and the feature mixing layer; inputting the third feature into the linear output head and the non-linear output head respectively to obtain a linear feature output by the linear output head and a non-linear feature output by the non-linear output head; fusing the linear feature and the non-linear feature to obtain a fused feature; and determining the vulnerability probability based on the fused feature.
[0010] In this embodiment, according to the technical solution, the probability of a smart contract being tested having a reentrancy vulnerability can be accurately determined using a detection model. Consequently, the existence of such a vulnerability can be accurately determined. Then, if a reentrancy vulnerability is confirmed, a vulnerability detection method can be determined based on the vulnerability probability and the smart contract's complexity. The smart contract is then subjected to vulnerability detection according to this method. Conversely, if the detection model determines that the smart contract does not have a reentrancy vulnerability, it is unnecessary to determine the smart contract's complexity or the vulnerability detection method (i.e., no further vulnerability detection is required). Therefore, this method can accurately exclude smart contracts that do not require vulnerability detection, thereby improving the efficiency of smart contract vulnerability detection. Furthermore, by determining the vulnerability probability and smart contract complexity, a suitable vulnerability detection method can be identified for the smart contract being tested, further improving both the efficiency and effectiveness of vulnerability detection.
[0011] Furthermore, the detection model first identifies the first feature corresponding to the smart contract under test at the sequence level through a sequence mixing layer. Then, it further extracts features from the first feature through a multi-head self-attention layer to obtain the second feature, thereby further extracting long-distance correlations in the feature sequence of the first feature of the smart contract under test. Next, a feature mixing layer mixes features at the feature channel level to determine the third feature. Finally, the third feature is simultaneously input into both a linear and a non-linear output head to obtain linear and non-linear features. The vulnerability probability is then determined by fusing the linear and non-linear features. This detection model addresses the problem of sequence mixing layers failing to capture long-term dependencies through a multi-head self-attention mechanism. Furthermore, it sets up two output heads in parallel at the output layer: one captures clear, simple patterns through a linear path, while the other learns complex, deep features through non-linear transformations. This effectively extracts various simple or complex information from the smart contract code, thereby improving the accuracy of determining the vulnerability probability of the smart contract. Attached Figure Description
[0012] The accompanying drawings, which are included to provide a further understanding of this disclosure and form part of this application, illustrate exemplary embodiments of this disclosure and are used to explain this disclosure, but do not constitute an undue limitation of this disclosure. In the drawings:
[0013] Figure 1 This is a hardware structure block diagram of a computing device for implementing the method according to Embodiment 1 of this disclosure;
[0014] Figure 2 This is a flowchart illustrating the smart contract vulnerability detection method based on machine learning and dynamic-static combined analysis according to the first aspect of Embodiment 1 of this disclosure;
[0015] Figure 3A This is a flowchart illustrating a method for determining vulnerability probability using a detection model, according to Embodiment 1 of this disclosure.
[0016] Figure 3B This is a flowchart illustrating a method for determining vulnerability probability using a detection model, according to Embodiment 1 of this disclosure.
[0017] Figure 4 This is a schematic diagram of a smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis according to the first aspect of Embodiment 2 of this disclosure; and
[0018] Figure 5 This is a schematic diagram of a smart contract vulnerability detection device based on machine learning and dynamic-static combined analysis, according to the first aspect of Embodiment 3 of this disclosure. Detailed Implementation
[0019] To enable those skilled in the art to better understand the technical solutions of this disclosure, the technical solutions of the embodiments of this disclosure will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are merely some embodiments of this disclosure, and not all embodiments. Based on the embodiments of this disclosure, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this disclosure.
[0020] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this disclosure are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of this disclosure described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0021] Example 1
[0022] According to this embodiment, a method for detecting smart contract vulnerabilities based on machine learning and dynamic-static combined analysis is provided. It should be noted that the steps shown in the flowchart in the accompanying drawings can be executed in a computer system such as a set of computer-executable instructions. Although a logical order is shown in the flowchart, in some cases, the steps shown or described may be executed in a different order than that shown here.
[0023] The method embodiments provided in this example can be executed on mobile terminals, computer terminals, servers, or similar computing devices. Figure 1 A hardware structure block diagram of a computing device for implementing a smart contract vulnerability detection method based on machine learning and static / dynamic analysis is shown. Figure 1 As shown, a computing device may include one or more processors (processors may include, but are not limited to, microprocessors such as MCUs or programmable logic devices such as FPGAs), a memory for storing data, a transmission device for communication functions, and an input / output interface. The memory, transmission device, and input / output interface are connected to the processor via a bus. In addition, it may also include a display, keyboard, and cursor control device connected to the input / output interface. Those skilled in the art will understand that... Figure 1 The structure shown is for illustrative purposes only and does not limit the structure of the aforementioned electronic device. For example, a computing device may also include... Figure 1 The more or fewer components shown, or having the same Figure 1 The different configurations shown.
[0024] It should be noted that the aforementioned one or more processors and / or other data processing circuits are generally referred to herein as "data processing circuits". These data processing circuits may be embodied, in whole or in part, in software, hardware, firmware, or any other combination thereof. Furthermore, the data processing circuits may be a single, independent processing module, or may be integrated, in whole or in part, into any other element in a computing device. As involved in the embodiments of this disclosure, the data processing circuits serve as processor control (e.g., selection of a variable resistor termination path connected to an interface).
[0025] The memory can be used to store software programs and modules of application software, such as the program instructions / data storage device corresponding to the smart contract vulnerability detection method based on machine learning and dynamic-static analysis in this embodiment of the present disclosure. The processor executes various functional applications and data processing by running the software programs and modules stored in the memory, thereby realizing the aforementioned smart contract vulnerability detection method based on machine learning and dynamic-static analysis of the application. The memory may include high-speed random access memory, and may also include non-volatile memory, such as one or more magnetic storage devices, flash memory, or other non-volatile solid-state memory. In some instances, the memory may further include memory remotely located relative to the processor, and these remote memories can be connected to the computing device via a network. Examples of the aforementioned networks include, but are not limited to, the Internet, corporate intranets, local area networks, mobile communication networks, and combinations thereof.
[0026] The transmission device is used to receive or send data via a network. Specific examples of the network described above may include a wireless network provided by the computing device's communication provider. In one example, the transmission device includes a Network Interface Controller (NIC), which can connect to other network devices via a base station to communicate with the Internet. In another example, the transmission device may be a Radio Frequency (RF) module used for wireless communication with the Internet.
[0027] The display can be, for example, a touchscreen liquid crystal display (LCD), which allows users to interact with the user interface of the computing device.
[0028] It should be noted here that, in some optional embodiments, the above... Figure 1The computing device shown may include hardware elements (including circuitry), software elements (including computer code stored on a computer-readable medium), or a combination of both hardware and software elements. It should be noted that... Figure 1 This is only one instance of a specific particular instance, and is intended to illustrate the types of components that may exist in the aforementioned computing devices.
[0029] Under the aforementioned operating environment, according to the first aspect of this embodiment, a smart contract vulnerability detection method based on machine learning and dynamic / static combined analysis is provided. This method can be... Figure 1 The computing device implementation is shown. Figure 2 A flowchart illustrating the method is shown below. (Refer to...) Figure 2 As shown, the method includes:
[0030] S202: Convert the smart contract to be tested into vector form to obtain the corresponding input data;
[0031] S204: Input the input data into the detection model to determine the vulnerability probability corresponding to the smart contract to be detected. The vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability.
[0032] S206: If the detection model determines that the smart contract to be detected has a reentrancy attack vulnerability, determine the smart contract complexity of the smart contract to be detected.
[0033] S208: Based on the vulnerability probability and the complexity of the smart contract, determine the vulnerability detection method for the smart contract to be tested, and perform vulnerability detection on the smart contract to be tested according to the vulnerability detection method.
[0034] refer to Figure 3A As shown, before determining whether a smart contract to be tested has vulnerabilities and the corresponding vulnerability probabilities through the detection model, the computing device can convert the smart contract to be tested into vector form to obtain the corresponding input data.
[0035] The computing device can preprocess the smart contract to be tested. To remove noise irrelevant to the task objective (i.e., vulnerability detection), retain relevant semantics, and ensure that code from different sources is as comparable, mergeable, and generalizable as possible in form, the corresponding data can be cleaned and standardized. Specifically, the computing device can remove numerous blank lines, multi-line comments starting with "*", and single-line comments starting with "\\" from the smart contract to be tested, and replace functions and variables with placeholders FUN# and VAR#. Different variables and functions within a smart contract are distinguished by ordinal numbers, such as variable names represented by VAR1, VAR2, etc., and function names represented by FUN1, FUN2, etc. (For function and variable names, different coding styles and different smart contracts have their own characteristics; using placeholders can standardize the contract code, unifying the naming of the same logic in different smart contracts, allowing the subsequent vulnerability detection model to focus on code logic rather than naming).
[0036] During the preprocessing stage, the computing device can pre-segment the source code using preset segmentation rules to obtain a source code sequence containing several tokens. For example, the code "require(VAR1>= VAR2&&VAR1>0); " can be segmented into "['require', '(', 'VAR1', '>=', 'VAR2', '&&', 'VAR1', '>', '0', ')', ';']", where each element within a single quote (') represents a token. Specifically, operators (such as >=, &&, etc.) can be pre-defined, and operators in the code can be segmented into tokens, while tokens other than operators (such as "require", "VAR1", "VAR2", and "0") can be extracted.
[0037] To ensure a consistent data format when inputting data into the detection model, the smart contracts to be detected are processed into a fixed-length source code sequence. The maximum length L of the source code sequence is... max Based on statistical principles, the maximum length is set as follows:
[0038] L max = μ+2σ(1)
[0039] Formula (1) is derived based on the 3σ principle of normal distribution. μ represents the average length of the smart contract source code sequence, and σ represents the standard deviation of the smart contract source code sequence length. Choosing μ+2σ as the maximum sequence length can cover approximately 95% of normal samples, avoiding excessive truncation. For lengths exceeding L... max The smart contract uses a truncation method to retain the first L. maxOne token; for tokens shorter than L max The smart contracts are padded with special padding characters (such as PAD) to ensure that the sequences of all smart contract input detection models are of uniform length L. max The unified sequence can be represented as:
[0040] (2)
[0041] Formula (2) represents the form of a truncated or padded sequence of source code, where i represents the i-th smart contract. This represents the length of the original source code sequence of the smart contract. After processing, all smart contracts are reduced to a length of L. max The source code sequence is then used. The computing device can then use a word2vec word embedding model to convert the source code sequence of the smart contract to be detected into a vector form, obtaining input data that can be fed into the subsequent detection model while preserving the hidden context / semantic relationships within the smart contract code.
[0042] Then, the computing device can input the corresponding input data into the detection model, and the detection model can determine the vulnerability probability corresponding to the smart contract to be detected. This vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability.
[0043] Among them, continue to refer to Figure 3A As shown, the detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. Figure 3AAs can be seen, the output layer contains parallel linear and nonlinear output heads. First, the computing device inputs the input data into the detection model, outputting a first feature corresponding to the smart contract to be detected through a sequence mixing layer. This sequence mixing layer is composed of a Multilayer Perceptron (MLP), focusing on the mixing of information at the sequence level of the input data. Then, based on the first feature, a second feature is determined through a multi-head self-attention layer. The second feature is obtained by further feature extraction from the first feature using a multi-head self-attention mechanism, thus solving the problem of MLP's difficulty in uncovering long-term dependencies at the sequence level of the input data. Next, the computing device can determine the corresponding third feature based on the second feature through a feature mixing layer. The feature mixing layer differs from the sequence mixing layer in that it learns the mixed information between different feature channels in the input data. Then, the computing device inputs the third feature into both the linear and nonlinear output heads. The linear output head outputs a linear feature through a linear transformation, and the nonlinear output head outputs a nonlinear feature through a nonlinear transformation. Both linear and nonlinear features are two-dimensional features, which are ultimately used for classification. Finally, the linear and nonlinear features are fused (weighted summation) to obtain the fused feature. By inputting the fused features into the Softmax layer, we can obtain the vulnerability probability P1 corresponding to the smart contract to be detected and the probability P2 that the smart contract to be detected does not have any vulnerabilities.
[0044] Furthermore, the computing device determines the smart contract complexity of the smart contract to be tested, the method for determining this complexity will be explained later. Then, based on the vulnerability probability and the smart contract complexity, the computing device determines the vulnerability detection method for the smart contract to be tested, and performs vulnerability detection on the smart contract according to the determined vulnerability detection method. The vulnerability detection method may include: static vulnerability detection using only static analysis tools, dynamic vulnerability detection using only dynamic analysis tools, and simultaneous static and dynamic vulnerability detection using both static and dynamic analysis tools.
[0045] As described in the background section, smart contracts are an essential technology in blockchain-related applications. Combined with blockchain, smart contracts can quickly implement corresponding contracts based on agreed-upon terms between business parties. However, current technologies struggle to efficiently and effectively detect vulnerabilities in smart contracts.
[0046] In view of this, according to the technical solution of this embodiment, the probability of a smart contract to be tested having a reentrancy attack vulnerability can be accurately determined through the detection model. Correspondingly, the result of whether the smart contract to be tested has a reentrancy attack vulnerability can be accurately obtained. Then, if it is determined that the smart contract to be tested has a reentrancy attack vulnerability, the vulnerability detection method for the smart contract to be tested can be determined based on the vulnerability probability and the complexity of the smart contract, and vulnerability detection can be performed on the smart contract to be tested according to the corresponding vulnerability detection method. If the detection model determines that the smart contract to be tested does not have a reentrancy attack vulnerability, then it is not necessary to determine the corresponding smart contract complexity or the vulnerability detection method; that is, it is not necessary to continue vulnerability detection on the smart contract to be tested. Therefore, this method can accurately exclude smart contracts that do not require vulnerability detection, thereby improving the efficiency of smart contract vulnerability detection. Furthermore, by determining the vulnerability probability and the complexity of the smart contract, a suitable vulnerability detection method can be determined for the smart contract to be tested, thereby further improving the vulnerability detection efficiency and effectiveness.
[0047] Furthermore, the aforementioned detection model first identifies the first feature corresponding to the smart contract under test at the sequence level through a sequence mixing layer. Then, it further extracts features from the first feature through a multi-head self-attention layer to obtain the second feature, thereby further extracting long-distance correlations in the feature sequence of the first feature of the smart contract under test. Next, a feature mixing layer mixes features at the feature channel level to determine the third feature. Finally, the third feature is simultaneously input into both a linear output head and a non-linear output head to obtain linear and non-linear features. The vulnerability probability is then determined by fusing the linear and non-linear features. This detection model addresses the problem of sequence mixing layers failing to capture long-term dependencies through a multi-head self-attention mechanism. Furthermore, it sets up two output heads in parallel at the output layer: one captures clear, simple patterns through a linear path, while the other learns complex, deep features through non-linear transformations. This effectively extracts various simple or complex information from the smart contract code, thereby improving the accuracy of determining the vulnerability probability of the smart contract.
[0048] Continue to refer to Figure 3AAs shown. To overcome the difficulty of traditional Multilayer Perceptron (MLP) models in capturing long-term dependencies in smart contract code sequences and to fully learn the semantic features of smart contract sequences for better detection of complex smart contracts, this embodiment presents an improved sequence mixing model—a dual-head TSMixer with embedded self-attention mechanism. Specifically, a multi-head self-attention mechanism is introduced into the sequence mixing layer, enabling the model to globally perceive code sequences and accurately capture semantic dependencies across long distances. It is particularly adept at identifying key code segments scattered throughout the code that collectively constitute vulnerability patterns. Furthermore, a unique dual-head output structure is designed: one output head (linear output head) captures clear and simple patterns through linear paths, while the other output head (non-linear output head) learns complex deep features through non-linear transformations. Finally, a learnable weight parameter adaptively fuses the two.
[0049] The following section uses a batch of smart contracts from the training phase to illustrate in detail the process of determining the probability of vulnerabilities in smart contracts through a detection model.
[0050] refer to Figure 3A and Figure 3B As shown. The input to the detection model comes directly from the standardized source code sequence generated during the data preprocessing stage: padded or truncated. Each token in the source code sequence has been mapped to a d (d=100)-dimensional vector using word2vec technology. Therefore, for a batch of smart contracts, the corresponding input tensor has dimensions [batch_size, length_max, d], abbreviated as [B, L, D]. B represents the number of smart contracts in a batch. L is the maximum length of the standardized sequence, L = L max D represents the dimension of the vector, which can be 100. Before entering the detection model, the input tensor is transformed in dimension, changing the input from [B, L, D] to [B, D, L], in order to adapt to subsequent sequence mixing and feature mixing operations.
[0051] The Sequence Mixing Layer focuses on processing relationships along the sequence dimension, capturing the contextual dependencies and structural patterns between tokens in the smart contract source code. The Sequence Mixing Layer receives data input in [B, D, L] dimensions, i.e., B samples, each with D feature channels, and a sequence length of L. First, the time dimension is batch-normalized using the TimeBatchNorm2d function to stabilize the training process. Second, maintaining the tensor dimension at [B, D, L], a fully connected layer is applied to mix information along the sequence dimension, capturing short-term dependencies between tokens to obtain the corresponding first feature.
[0052] Then, to address the issue of MLPs' difficulty in capturing long-term dependencies, a multi-head self-attention mechanism (i.e., a multi-head self-attention layer) is introduced after the sequence mixing layer. The dimensions of the Q, K, and V matrices are set to [B, D, L], and the number of attention heads is 4, with each attention head having a dimension equal to the feature dimension / 4 (d / 4). This allows the detection model to learn information from different representation subspaces. Attention calculation uses scaled dot product attention, with the following formula:
[0053] (3)
[0054] Where Q represents the query matrix, K represents the key matrix, V represents the value matrix, and d k =d / 4. Multi-head information is fused through a linear projection layer to generate an enhanced sequence representation.
[0055] Finally, after residual connection, the result of sequence mixing is obtained, and the output dimension is maintained as [B, D, L]. That is, the second feature is obtained by adding the original input of the detection model to the output of the multi-head self-attention layer.
[0056] The feature mixing layer focuses on processing the relationships between feature dimensions, learning the interactions and combinations between semantic features. First, the dimensions of the received data are transformed from [B, D, L] to [B, L, D], allowing subsequent operations to be performed along the feature dimensions. Second, two fully connected layers are applied along the feature dimensions to learn the interactions and combination patterns between different feature channels. A dropout layer is added after each layer to effectively suppress overfitting and improve the model's generalization and robustness. Finally, the residual connections are added to the original input, and the tensor dimensions are transformed back to [B, D, L] to obtain the aforementioned third feature. In other words, the third feature is obtained by adding the second feature and the output of the feature mixing layer.
[0057] Since simple linear mappings may struggle to capture the complex semantics of smart contracts, a unique dual-head hybrid mechanism—a linear output head and a nonlinear output head—is designed at the output layer. The linear output head directly maps D-dimensional features to a 2-dimensional output through a linear transformation, capturing simple linear relationships between features. The nonlinear output head performs a nonlinear transformation using the ReLU activation function before mapping to the 2-dimensional output, capturing complex nonlinear patterns between features. In this layer, the feature mixture is processed through the parallel linear and nonlinear heads, and the outputs of both heads are weighted and summed using a learnable weight parameter α, as shown in the formula:
[0058] output=α×linear_output+(1-α)×nonlinear_output (4)
[0059] Here, `linear_output` represents linear output features, and `nonlinear_output` represents nonlinear output features. The value range of α is [0, 1]. In order to output the probability of a specific category along with the category output, a binary classification probability is finally generated through the Softmax function, with an output dimension of [batch_size, 2], where the two feature dimensions correspond to the probabilities of "no vulnerabilities" and "vulnerabilities" respectively.
[0060] Throughout the training process, the Adam optimizer can be used to optimize the cross-entropy loss of the detection model, balancing training stability and convergence speed. Before model training, existing smart contracts are labeled. The labeling rule is to locate reentrancy attack risk points in the smart contracts. When a risk point appears, the smart contract is marked as having a reentrancy attack vulnerability; the rest are marked as not having a reentrancy attack vulnerability. Subsequently, to ensure the balance of model training and prevent imbalanced samples from causing poor training results and poor generalization ability, an equal number of "vulnerable" and "vulnerable" smart contract samples are randomly drawn from the dataset in a 1:1 ratio to form a balanced training dataset, outputting a set of smart contracts with accurate binary classification labels.
[0061] By using a trained machine learning model (detection model) to predict whether a smart contract has vulnerabilities and output the probability of such vulnerabilities, the vulnerability risk of a contract can be efficiently assessed. The vulnerability probability output by the detection model determines the subsequent detection strategy, allowing different detection resources to be allocated according to actual needs. This process not only improves the efficiency of vulnerability detection but also optimizes resource consumption and avoids over-reliance on inefficient deep analysis tools.
[0062] Optionally, the operation of determining the smart contract complexity of the smart contract to be tested includes: determining the number of lines of code, the number of functions, and the number of variables in the smart contract to be tested; normalizing the number of lines of code, the number of functions, and the number of variables respectively to obtain the corresponding normalized values; and determining the smart contract complexity based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables respectively.
[0063] Before determining the complexity of a smart contract based on the number of lines of code, functions, and variables, the computing device can first normalize the number of lines of code, functions, and variables to eliminate differences in feature dimensions and maintain consistency in dimensions, while also solving the problem of large ranges.
[0064] It should be noted that the statistics involved in the formulas below, such as the maximum and minimum number of lines of code in a smart contract, can be determined by collecting a batch of smart contracts at regular intervals. Of course, in the training phase, they can be directly determined from each batch of training samples (which contain smart contracts).
[0065] Specifically, a smooth logarithmic normalization method can be used to map the number of lines of code, the number of functions, and the number of variables to the interval [0,1]. The logarithmic normalization formula is as follows:
[0066] (5)
[0067] in, The normalized value is represented by the number of lines of code, functions, and variables of the smart contract to be tested, which are then substituted into the above formula (5) to obtain the corresponding normalized value. This indicates the number of lines of code, functions, or variables in the smart contract to be tested. This indicates the minimum number of lines of code, minimum number of functions, or minimum number of variables required for a smart contract. This indicates the maximum number of lines of code, the maximum number of functions, or the maximum number of variables in a smart contract.
[0068] After normalizing the number of lines of code, functions, and variables in a smart contract, any smart contract can be represented as a feature point in a corresponding three-dimensional normalized feature space, with coordinates as (…). , , ). Among them, the assumption is ( , , () are the coordinates of the smart contract to be tested. This represents the normalized value of the number of lines of code in the smart contract to be tested. The normalized value representing the number of functions in the smart contract to be tested. This represents the normalized value of the number of variables in the smart contract to be tested. The origin O(0, 0, 0) represents the smart contract with the simplest code in theory, and the extreme point M(1, 1, 1) represents the smart contract with the most complex code in theory.
[0069] Optionally, the operation of determining the complexity of a smart contract based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables includes: determining the origin, poles, and feature points corresponding to the smart contract to be tested in the three-dimensional normalized feature space based on the normalization operation; determining the first distance between the feature points and the origin and the second distance between the feature points and the poles based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables; and determining the complexity of the smart contract based on the first distance and the second distance.
[0070] After determining the normalized values corresponding to the number of lines of code, functions, and variables, the complexity of the smart contract can be determined. The normalized numbers of lines of code, functions, and variables in a smart contract can be considered as feature points of each smart contract within a three-dimensional normalized feature space. The three dimensions of this three-dimensional normalized feature space correspond to the normalized values of the number of lines of code, functions, and variables, respectively. The aforementioned extreme points and origin are special points in this three-dimensional normalized feature space. The complexity of the smart contract under test can then be determined based on these extreme points and origin.
[0071] Specifically, the Minkowski distance can be used to calculate the first distance from the feature points of the smart contract to be detected to the origin. And the second distance to the pole The specific formula is as follows:
[0072] (6)
[0073] (7)
[0074] In this embodiment, it is considered that the closer a normalized value of a certain dimension (such as the normalized value of the number of lines of code, the normalized value of the number of functions, or the normalized value of the number of variables) is to the extreme value 1, the greater its impact on the complexity of the smart contract. In this embodiment, the parameter p should not be set too large or too small, because the parameter p is related to the first distance corresponding to the feature points of the smart contract. Second distance The value of p affects the value of the smart contract complexity C. In this embodiment, it is desirable that if the normalized value of any one of the three dimensions is high (e.g., a large number of lines of code, a large number of functions, or a large number of variables), even if the normalized values of the other two dimensions are low, the final determined smart contract complexity can still be relatively large. This requires that the parameter p be set neither too large nor too small. Based on this, the parameter p is preferably set to: p=3.
[0075] Finally, based on the first distance Second distance The complexity C of a smart contract is determined by the following formula:
[0076] (8)
[0077] This formula limits the complexity of smart contracts to the range [0,1].
[0078] In summary, the formula for determining the complexity C of a smart contract is:
[0079] (9)
[0080] For ease of explanation, the probability of a vulnerability will be written as P in the following text.
[0081] After determining the complexity of the smart contract to be tested, the computing device can determine which vulnerability detection method to use based on the smart contract complexity C and the vulnerability probability P.
[0082] Optionally, the operation of determining the vulnerability detection method for the smart contract to be tested based on the vulnerability probability and the smart contract complexity includes: determining the weights corresponding to the vulnerability probability and the smart contract complexity based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, wherein the correlation coefficients are used to represent the correlation between the corresponding variables and whether the smart contract to be tested has a reentrancy attack vulnerability; performing a weighted summation of the vulnerability probability and the smart contract complexity based on the weights corresponding to the vulnerability probability and the smart contract complexity to obtain a comprehensive score for the smart contract to be tested; and determining the vulnerability detection method for the smart contract to be tested based on the comprehensive score.
[0083] Specifically, the smart contract's complexity C and vulnerability probability P can be weighted and summed to obtain a comprehensive score for the smart contract under test, as shown in the following formula:
[0084] Score = w1·P + w2·C (10)
[0085] Where w1 represents the weight corresponding to the vulnerability probability, and w2 represents the weight corresponding to the smart contract complexity. In this embodiment, the weight w1 corresponding to the vulnerability probability and the weight w2 corresponding to the smart contract complexity are determined with reference to the theory of point-bivariate correlation. That is, based on the correlation coefficient r corresponding to the vulnerability probability... p And the correlation coefficient r with the complexity of smart contracts c The weights corresponding to vulnerability probabilities and smart contract complexity are determined. The correlation coefficient corresponding to vulnerability probability represents the correlation between the vulnerability probability of a smart contract and the existence of reentrancy attack vulnerabilities, while the correlation coefficient corresponding to smart contract complexity represents the correlation between smart contract complexity and the existence of reentrancy attack vulnerabilities in the smart contract under test.
[0086] The following gives the correlation coefficient r corresponding to the vulnerability probability. p And the correlation coefficient r with the complexity of smart contracts c In this way.
[0087] Optionally, the operation of determining the correlation coefficient corresponding to the vulnerability probability includes: determining the correlation coefficient corresponding to the vulnerability probability using the following formula.
[0088] (11)
[0089] in, This represents the correlation coefficient corresponding to the probability of a vulnerability. This represents the average vulnerability probability of a smart contract that is susceptible to reentrancy attacks. This represents the average vulnerability probability of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the probability of vulnerabilities in smart contracts. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This represents the number of smart contracts that do not have reentrancy vulnerabilities; and the operations for determining the correlation coefficient corresponding to the complexity of smart contracts include:
[0090] (12)
[0091] This represents the correlation coefficient between smart contract complexity and... This represents the average smart contract complexity of a smart contract vulnerable to reentrancy attacks. This represents the average smart contract complexity of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the smart contract complexity represents the complexity of a smart contract. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This indicates the number of smart contracts that do not have reentrancy vulnerability.
[0092] As can be seen from the above, formulas (11) and (12) have the same form. Formula (11) is used to determine the correlation coefficient corresponding to the vulnerability probability. Formula (12) is used to determine the correlation coefficient corresponding to the complexity of smart contracts. Formulas (11) and (12) are derived from formula (13), and the derivation of formula (13) will be given below.
[0093] (13)
[0094] First, the basic formula for the Pearson correlation coefficient is shown in formula (14):
[0095] (14)
[0096] In formula (14), r represents the correlation coefficient between variables X and Y. In formula (14), variable X is the vulnerability probability or smart contract complexity, and variable Y is a binary variable representing whether a smart contract has a reentrancy attack vulnerability. n is the number of smart contracts used to determine the correlation coefficient r. Let X represent the variable corresponding to the i-th smart contract. Let Y represent the variable corresponding to the i-th smart contract.
[0097] The mean of variable Y can be expressed as:
[0098] (15)
[0099] The numerator in formula (14) can be represented as:
[0100] (16)
[0101] The denominator in formula (14) can be expressed as:
[0102] (17)
[0103] (18)
[0104] Formula (16) is derived from: , , Substitute the aforementioned terms into the left half of formula (16): Formula (17) is derived from the variance formula. Formula (18) is simplified to obtain: .
[0105] By substituting formulas (14) to (18) into formula (10) and simplifying them, we can obtain formula (13), which is the formula related to the two columns. The process is shown in the following formula (19).
[0106] (19)
[0107] in, This indicates the number of smart contracts vulnerable to reentrancy attacks. This indicates the number of smart contracts that do not have reentrancy vulnerabilities. The mean of variable X represents the value of a smart contract vulnerable to reentrancy attacks. The mean value of variable X of the smart contract indicating the absence of re - entry attack vulnerability. s represents the standard deviation of variable X. Among them, the finally determined correlation coefficient ranges from 0 to 1. The larger the value of the correlation coefficient, the stronger the correlation between the corresponding variable and the existence of the vulnerability (re - entry attack vulnerability), and it has a better discriminant contribution in identifying re - entry attack vulnerabilities.
[0108] The computing device determines the correlation coefficient corresponding to the vulnerability probability and the correlation coefficient After that, the weight w1 corresponding to the vulnerability probability can be determined through the following formula (20), and the weight w2 corresponding to the determined smart contract complexity can be determined through formula (21).
[0109] (20)
[0110] (21)
[0111] Then, the computing device can determine the comprehensive score Score corresponding to the to - be - detected smart contract based on formula (10) according to the determined weight w1 corresponding to the vulnerability probability and the weight w2 corresponding to the smart contract complexity.
[0112] Optionally, the operation of determining the vulnerability detection method of the to - be - detected smart contract according to the comprehensive score includes: when the comprehensive score is not higher than the first threshold, detecting the vulnerability of the to - be - detected smart contract through a static analysis tool; when the comprehensive score is higher than the first threshold and lower than the second threshold, detecting the vulnerability of the to - be - detected smart contract through a dynamic analysis tool; when the comprehensive score is higher than the second threshold, combining the static analysis tool and the dynamic analysis tool to detect the vulnerability of the to - be - detected smart contract.
[0113] After the computing device determines the comprehensive score of the to - be - detected smart contract, it can determine the corresponding vulnerability detection method for the to - be - detected smart contract. First, determine the first threshold α and the second threshold β, where α < β. α and β can be preset.
[0114] Then, the risks can be divided into three levels according to the first threshold α and the second threshold β: low - risk level (the comprehensive score Score is not higher than the first threshold, that is, Score ≤ α); medium - risk level (the comprehensive score Score is higher than the first threshold and not higher than the second threshold, that is, α < Score ≤ β) and high - risk level (the comprehensive score Score is higher than the second threshold, that is, Score > β).
[0115] Among them, when the smart contract to be detected is at a low-risk level, that is, the comprehensive score Score of the smart contract to be detected ≤ α, the computing device can detect vulnerabilities in the smart contract to be detected through a static analysis tool. That is, when the smart contract is at a low-risk level, it indicates that the possibility of vulnerabilities in the corresponding smart contract is low and the structure of the corresponding smart contract is simple. Then, fast pattern matching and syntax checking can be performed through the static analysis tool Slither, mainly for a preliminary screening of function visibility errors. The input data (that is, the data input into the static analysis tool Slither) is the Solidity source code after standardized preprocessing. The computing device can automatically generate temporary compilation products (AST and bytecode) for the abstract syntax analysis module of Slither to call. The detection result is a JSON-format file, which contains the name of the vulnerability, the risk level, the file path, and the corresponding lines (code lines) field, clearly marking the specific line number range of the vulnerability. This detection result is then parsed and written into the database as the input for subsequent risk assessment and visualization. In this way, while ensuring the detection speed, resource consumption is minimized to provide a basis for the preliminary screening in the subsequent stage.
[0116] When the smart contract to be detected is at a medium-risk level, that is, the comprehensive score of the smart contract to be detected is higher than the first threshold and not higher than the second threshold (α < Score ≤ β), the computing device can detect vulnerabilities in the smart contract to be detected through a dynamic analysis tool. When the smart contract is at a medium-risk level, it indicates that there are certain risks or the structure is complex in the corresponding smart contract. The dynamic analysis tool Mythril is started for in-depth symbolic execution and taint tracking. The computing device first constructs a control flow graph (CFG) based on the intermediate representation and EVM bytecode generated by compiling the source code. Subsequently, Mythril simulates the running process of the corresponding smart contract under multi-path execution, tracking variables and paths that may lead to abnormal states, such as external calls or re-entrancy points. Key path information and variable constraint conditions are recorded during the execution process, and finally, the detection result is output to achieve a deep capture of potential logical vulnerabilities.
[0117] When a smart contract under test is classified as high-risk (i.e., its overall score exceeds the second threshold (Score > β), the computing device can combine static and dynamic analysis tools to perform vulnerability detection. A high-risk level indicates a high risk of vulnerabilities and complex structure. Simultaneously, the static analysis tool Slither and the dynamic analysis tool Mythril are activated for combined static and dynamic verification. The results of the two analyses are cross-checked and their consistency is verified. First, Slither performs static analysis on the smart contract code, extracting potentially high-risk functions and call relationship graphs, and generating preliminary vulnerability location information. Then, Mythril simulates the smart contract's execution under multi-path execution for in-depth verification. After analysis, the two detection results are uniformly analyzed and merged. Vulnerabilities in the same location or type are cross-checked and their consistency is verified. If the results are consistent, the vulnerability confidence is increased; if discrepancies occur, manual review or re-analysis is triggered.
[0118] The final detection results (detection report) output by the computing device can include vulnerability type, vulnerability location, tool source, and analysis time, providing smart contract developers with a highly credible and traceable security assessment result.
[0119] The detection report provided to developers may include the following important outputs: (1) Vulnerability type, i.e., the specific category of the detected security vulnerability; (2) Vulnerability location, including the precise line number of the vulnerability code, so that developers can locate and fix the problem. The precise location of the vulnerability depends on the source code location information returned by Slither and Mythril in the detection results. The output of both tools includes fields pointing to the contract source file and line number, which developers can use to jump directly to and fix the problem in the source code editor. When exported as a JSON report, the result indicating the vulnerability location is generally stored under the lines field; (3) Execution time of the vulnerability detection process, i.e., the time required for vulnerability analysis in each detection stage, reflecting the efficiency of the tool. Using Python's time library, timestamps are recorded at the beginning and end of each detection stage, and the execution time is the difference between "end time - start time" (in seconds). (4) Resource consumption, used to evaluate the differences in resource consumption of different analysis tools, to ensure the optimal choice in performance and resource management. The psutil library based on Python records the memory usage, CPU usage, and number of active threads of different vulnerability detection methods at regular intervals.
[0120] The joint decision-making mechanism in this embodiment achieves the matching of vulnerability detection resources with smart contract risks by quantitatively evaluating the risk (represented by the vulnerability probability P) and complexity (represented by the smart contract complexity C) of each smart contract. This ensures that high-threat smart contracts are fully verified while significantly improving the overall efficiency of large-scale smart contract vulnerability detection.
[0121] In addition, refer to Figure 1 As shown, according to a second aspect of this embodiment, a storage medium is provided. The storage medium includes a stored program, wherein, when the program is executed, a processor performs any of the methods described above.
[0122] Therefore, according to this embodiment, not only is the accuracy of the determined vulnerability probability of smart contracts improved by introducing a multi-head self-attention mechanism and parallel linear and nonlinear output heads into the detection model, but also the appropriate vulnerability detection method (or vulnerability detection strategy) is evaluated by comprehensively considering the complexity and vulnerability probability of the smart contract. Low-risk smart contracts undergo static vulnerability detection, medium-risk smart contracts undergo dynamic vulnerability detection, and high-risk smart contracts undergo both static and dynamic vulnerability detection. This improves vulnerability detection efficiency and effectively detects vulnerabilities in various smart contracts.
[0123] It should be noted that, for the sake of simplicity, the foregoing method embodiments are all described as a series of actions. However, those skilled in the art should understand that the present invention is not limited to the described order of actions, because according to the present invention, some steps can be performed in other orders or simultaneously. Furthermore, those skilled in the art should also understand that the embodiments described in the specification are preferred embodiments, and the actions and modules involved are not necessarily essential to the present invention.
[0124] Through the above description of the embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus necessary general-purpose hardware platforms. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a storage medium (such as ROM / RAM, magnetic disk, optical disk) and includes several instructions to cause a terminal device (which may be a mobile phone, computer, server, or network device, etc.) to execute the methods described in the various embodiments of the present invention.
[0125] Example 2
[0126] Figure 4A smart contract vulnerability detection apparatus based on machine learning and static / dynamic analysis according to the first aspect of this embodiment is shown, which corresponds to the method described according to the first aspect of Embodiment 1. (Reference) Figure 4 As shown, the smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis includes: an input data determination module 410, used to convert the smart contract to be detected into vector form to obtain corresponding input data; a probability determination module 420, used to input the input data into the detection model, and determine the vulnerability probability corresponding to the smart contract to be detected through the detection model, where the vulnerability probability represents the probability that the smart contract to be detected has a reentrancy attack vulnerability; a complexity determination module 430, used to determine the smart contract complexity of the smart contract to be detected; and a detection method determination module 440, used to determine the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity, and to perform vulnerability detection on the smart contract to be detected according to the vulnerability detection method. The system performs vulnerability detection; the detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. The output layer includes a linear output head and a non-linear output head arranged in parallel. A probability determination module 420 is used to determine a first feature corresponding to the smart contract to be detected based on the sequence mixing layer; determine a corresponding second feature based on the first feature and the multi-head self-attention layer; determine a corresponding third feature based on the second feature and the feature mixing layer; input the third feature into the linear output head and the non-linear output head respectively to obtain the linear feature output by the linear output head and the non-linear feature output by the non-linear output head; fuse the linear feature and the non-linear feature to obtain the fused feature; and determine the vulnerability probability based on the fused feature.
[0127] Optionally, the complexity determination module 430 is used to determine the number of lines of code, the number of functions, and the number of variables of the smart contract to be tested; normalize the number of lines of code, the number of functions, and the number of variables respectively to obtain the corresponding normalized values; and determine the complexity of the smart contract based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables respectively.
[0128] Optionally, the complexity determination module 430 is used to determine the origin, poles, and feature points corresponding to the smart contract to be detected in the three-dimensional normalized feature space based on normalized operations; determine the first distance between the feature points and the origin and the second distance between the feature points and the poles based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables; and determine the complexity of the smart contract based on the first distance and the second distance.
[0129] Optionally, the detection method determination module 440 is used to determine the weights corresponding to the vulnerability probability and the smart contract complexity based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, wherein the correlation coefficients are used to represent the correlation between the corresponding variables and whether the smart contract to be detected has a reentrancy attack vulnerability; based on the weights corresponding to the vulnerability probability and the smart contract complexity, the vulnerability probability and the smart contract complexity are weighted and summed to obtain a comprehensive score for the smart contract to be detected; based on the comprehensive score, the vulnerability detection method for the smart contract to be detected is determined.
[0130] Optionally, the detection method determination module 440 is used to determine the correlation coefficient corresponding to the vulnerability probability using the following formula. ,in, This represents the correlation coefficient corresponding to the probability of a vulnerability. This represents the average vulnerability probability of a smart contract that is susceptible to reentrancy attacks. This represents the average vulnerability probability of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the probability of vulnerabilities in smart contracts. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This represents the number of smart contracts that do not have reentrancy vulnerabilities; and the operations for determining the correlation coefficient corresponding to the complexity of smart contracts include: , This represents the correlation coefficient between smart contract complexity and... This represents the average smart contract complexity of a smart contract vulnerable to reentrancy attacks. This represents the average smart contract complexity of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the smart contract complexity represents the complexity of a smart contract. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This indicates the number of smart contracts that do not have reentrancy vulnerability.
[0131] Optionally, the detection method determination module 440 is used to perform vulnerability detection on the smart contract to be tested using a static analysis tool when the comprehensive score is not higher than a first threshold; to perform vulnerability detection on the smart contract to be tested using a dynamic analysis tool when the comprehensive score is higher than the first threshold but not higher than a second threshold, wherein the first threshold is lower than the second threshold; and to perform vulnerability detection on the smart contract to be tested by combining the static analysis tool and the dynamic analysis tool when the comprehensive score is higher than the second threshold.
[0132] Therefore, according to this embodiment, not only is the accuracy of the determined vulnerability probability of smart contracts improved by introducing a multi-head self-attention mechanism and parallel linear and nonlinear output heads into the detection model, but also the appropriate vulnerability detection method (or vulnerability detection strategy) is evaluated by comprehensively considering the complexity and vulnerability probability of the smart contract. Low-risk smart contracts undergo static vulnerability detection, medium-risk smart contracts undergo dynamic vulnerability detection, and high-risk smart contracts undergo both static and dynamic vulnerability detection. This improves vulnerability detection efficiency and effectively detects vulnerabilities in various smart contracts.
[0133] Example 3
[0134] Figure 5 A smart contract vulnerability detection apparatus based on machine learning and static / dynamic analysis according to the first aspect of this embodiment is shown, which corresponds to the method described according to the first aspect of Embodiment 1. (Reference) Figure 5 As shown, the smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis includes: a processor 510; and a memory 520 connected to the processor 510, used to provide the processor 510 with instructions to process the following steps: converting the smart contract to be detected into vector form to obtain corresponding input data; inputting the input data into a detection model, determining the vulnerability probability corresponding to the smart contract to be detected through the detection model, the vulnerability probability being used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability; determining the smart contract complexity of the smart contract to be detected; and determining the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity, and performing vulnerability detection on the smart contract to be detected according to the vulnerability detection method; and wherein, the detection... The detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer. The output layer includes a linear output head and a non-linear output head set in parallel. The operation of determining the vulnerability probability corresponding to the smart contract to be detected through the detection model includes: determining a first feature corresponding to the smart contract to be detected based on the sequence mixing layer; determining a corresponding second feature based on the first feature and the multi-head self-attention layer; determining a corresponding third feature based on the second feature and the feature mixing layer; inputting the third feature into the linear output head and the non-linear output head respectively to obtain the linear feature output by the linear output head and the non-linear feature output by the non-linear output head; fusing the linear feature and the non-linear feature to obtain the fused feature; and determining the vulnerability probability based on the fused feature.
[0135] Optionally, the operation of determining the smart contract complexity of the smart contract to be tested includes: determining the number of lines of code, the number of functions, and the number of variables in the smart contract to be tested; normalizing the number of lines of code, the number of functions, and the number of variables respectively to obtain the corresponding normalized values; and determining the smart contract complexity based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables respectively.
[0136] Optionally, the operation of determining the complexity of a smart contract based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables includes: determining the origin, poles, and feature points corresponding to the smart contract to be tested in the three-dimensional normalized feature space based on the normalization operation; determining the first distance between the feature points and the origin and the second distance between the feature points and the poles based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables; and determining the complexity of the smart contract based on the first distance and the second distance.
[0137] Optionally, the operation of determining the vulnerability detection method for the smart contract to be tested based on the vulnerability probability and the smart contract complexity includes: determining the weights corresponding to the vulnerability probability and the smart contract complexity based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, wherein the correlation coefficients are used to represent the correlation between the corresponding variables and whether the smart contract to be tested has a reentrancy attack vulnerability; performing a weighted summation of the vulnerability probability and the smart contract complexity based on the weights corresponding to the vulnerability probability and the smart contract complexity to obtain a comprehensive score for the smart contract to be tested; and determining the vulnerability detection method for the smart contract to be tested based on the comprehensive score.
[0138] Optionally, the operation of determining the correlation coefficient corresponding to the vulnerability probability includes: determining the correlation coefficient corresponding to the vulnerability probability using the following formula. ,in, This represents the correlation coefficient corresponding to the probability of a vulnerability. This represents the average vulnerability probability of a smart contract that is susceptible to reentrancy attacks. This represents the average vulnerability probability of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the probability of vulnerabilities in smart contracts. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This represents the number of smart contracts that do not have reentrancy vulnerabilities; and the operations for determining the correlation coefficient corresponding to the complexity of smart contracts include: , This represents the correlation coefficient between smart contract complexity and... This represents the average smart contract complexity of a smart contract vulnerable to reentrancy attacks. This represents the average smart contract complexity of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the smart contract complexity represents the complexity of a smart contract. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This indicates the number of smart contracts that do not have reentrancy vulnerability.
[0139] Optionally, the operation of determining the vulnerability detection method for the smart contract to be tested based on the comprehensive score includes: if the comprehensive score is not higher than a first threshold, performing vulnerability detection on the smart contract to be tested using a static analysis tool; if the comprehensive score is higher than the first threshold but not higher than a second threshold, performing vulnerability detection on the smart contract to be tested using a dynamic analysis tool, where the first threshold is lower than the second threshold; and if the comprehensive score is higher than the second threshold, performing vulnerability detection on the smart contract to be tested by combining static and dynamic analysis tools.
[0140] Therefore, according to this embodiment, not only is the accuracy of the determined vulnerability probability of smart contracts improved by introducing a multi-head self-attention mechanism and parallel linear and nonlinear output heads into the detection model, but also the appropriate vulnerability detection method (or vulnerability detection strategy) is evaluated by comprehensively considering the complexity and vulnerability probability of the smart contract. Low-risk smart contracts undergo static vulnerability detection, medium-risk smart contracts undergo dynamic vulnerability detection, and high-risk smart contracts undergo both static and dynamic vulnerability detection. This improves vulnerability detection efficiency and effectively detects vulnerabilities in various smart contracts.
[0141] The sequence numbers of the above embodiments of the present invention are for descriptive purposes only and do not represent the superiority or inferiority of the embodiments.
[0142] In the above embodiments of the present invention, the descriptions of each embodiment have different focuses. For parts not described in detail in a certain embodiment, please refer to the relevant descriptions of other embodiments.
[0143] In the several embodiments provided in this application, it should be understood that the disclosed technical content can be implemented in other ways. The device embodiments described above are merely illustrative; for example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the displayed or discussed mutual coupling, direct coupling, or communication connection may be through some interfaces; the indirect coupling or communication connection between units or modules may be electrical or other forms.
[0144] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0145] Furthermore, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0146] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, read-only memory (ROM), random access memory (RAM), portable hard drives, magnetic disks, or optical disks.
[0147] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A smart contract vulnerability detection method based on machine learning and dynamic / static combined analysis, characterized in that, include: The smart contract to be tested is converted into vector form to obtain the corresponding input data; The input data is fed into the detection model to determine the vulnerability probability corresponding to the smart contract to be detected. The vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability. If the detection model determines that the smart contract to be detected has a reentrancy attack vulnerability, the smart contract complexity of the smart contract to be detected is determined. as well as Based on the vulnerability probability and the smart contract complexity, determine the vulnerability detection method for the smart contract to be tested, and perform vulnerability detection on the smart contract to be tested according to the vulnerability detection method; Furthermore, the detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer, wherein the output layer includes a linear output head and a non-linear output head arranged in parallel. The operation of determining the vulnerability probability corresponding to the smart contract to be detected through the detection model includes: Based on the sequence mixing layer, a first feature corresponding to the smart contract to be detected is determined; based on the first feature, a corresponding second feature is determined based on the multi-head self-attention layer; based on the second feature, a corresponding third feature is determined based on the feature mixing layer; the third feature is input into the linear output head and the nonlinear output head respectively to obtain the linear feature output by the linear output head and the nonlinear feature output by the nonlinear output head; the linear feature and the nonlinear feature are fused to obtain a fused feature; and based on the fused feature, the vulnerability probability is determined. The operation of determining the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity includes: Based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, the weights corresponding to the vulnerability probability and the smart contract complexity are determined, wherein the correlation coefficients are used to represent the correlation between the corresponding variables and whether the smart contract to be detected has a reentrancy attack vulnerability. Based on the weights corresponding to the vulnerability probability and the smart contract complexity, a weighted sum is performed on the vulnerability probability and the smart contract complexity to obtain a comprehensive score for the smart contract to be tested. Based on the comprehensive score, the vulnerability detection method for the smart contract to be tested is determined.
2. The method according to claim 1, characterized in that, The operation of determining the smart contract complexity of the smart contract to be tested includes: Determine the number of lines of code, the number of functions, and the number of variables of the smart contract to be tested; The number of lines of code, the number of functions, and the number of variables are normalized respectively to obtain their corresponding normalized values; The complexity of the smart contract is determined based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables.
3. The method according to claim 2, characterized in that, The operation of determining the complexity of the smart contract based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables includes: Based on the normalization operation, the origin, poles, and feature points corresponding to the smart contract to be detected in the three-dimensional normalized feature space are determined. Based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables, the first distance between the feature point and the origin and the second distance between the feature point and the pole are determined. The complexity of the smart contract is determined based on the first distance and the second distance.
4. The method according to claim 1, characterized in that, The operation of determining the correlation coefficient corresponding to the vulnerability probability includes: The correlation coefficient corresponding to the probability of the vulnerability is determined using the following formula. in, This represents the correlation coefficient corresponding to the probability of the vulnerability. This represents the average vulnerability probability of a smart contract that is susceptible to reentrancy attacks. This represents the average vulnerability probability of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the probability of vulnerabilities in smart contracts. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This represents the number of smart contracts that do not have reentrancy vulnerabilities; and among them, The operation of determining the correlation coefficient corresponding to the complexity of the smart contract includes: This represents the correlation coefficient corresponding to the complexity of the smart contract. This represents the average smart contract complexity of a smart contract vulnerable to reentrancy attacks. This represents the average smart contract complexity of a smart contract that does not have a reentrancy vulnerability. The standard deviation of the smart contract complexity represents the complexity of a smart contract. This represents the total number of smart contracts. This indicates the number of smart contracts vulnerable to reentrancy attacks. This indicates the number of smart contracts that do not have reentrancy vulnerability.
5. The method according to claim 1, characterized in that, The operation of determining the vulnerability detection method for the smart contract to be tested based on the comprehensive score includes: If the comprehensive score is not higher than the first threshold, the smart contract to be tested is subjected to vulnerability detection using a static analysis tool. If the comprehensive score is higher than the first threshold but not higher than the second threshold, the smart contract to be tested is subjected to vulnerability detection using a dynamic analysis tool, where the first threshold is lower than the second threshold. If the comprehensive score is higher than the second threshold, the smart contract to be tested is subjected to vulnerability detection by combining the static analysis tool and the dynamic analysis tool.
6. A storage medium, characterized in that, The storage medium includes a stored program, wherein the method described in any one of claims 1 to 5 is generated and executed by a processor when the program is run.
7. A smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis, characterized in that, include: The input data determination module is used to convert the smart contract to be tested into vector form to obtain the corresponding input data. The probability determination module is used to input the input data into the detection model and determine the vulnerability probability corresponding to the smart contract to be detected through the detection model. The vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability. The complexity determination module is used to determine the smart contract complexity of the smart contract to be detected. as well as A detection method determination module is used to determine the vulnerability detection method for the smart contract to be tested based on the vulnerability probability and the smart contract complexity, and to perform vulnerability detection on the smart contract to be tested according to the vulnerability detection method. The module is further configured to determine the weights corresponding to the vulnerability probability and the smart contract complexity based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, where the correlation coefficients represent the correlation between the corresponding variables and whether the smart contract to be tested has a reentrancy attack vulnerability; to perform a weighted summation of the vulnerability probability and the smart contract complexity based on the weights corresponding to the vulnerability probability and the smart contract complexity to obtain a comprehensive score for the smart contract to be tested; and to determine the vulnerability detection method for the smart contract to be tested based on the comprehensive score. Furthermore, the detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer, wherein the output layer includes a linear output head and a non-linear output head arranged in parallel. The probability determination module is used to determine a first feature corresponding to the smart contract to be detected based on the sequence mixing layer; determine a corresponding second feature based on the multi-head self-attention layer based on the first feature; determine a corresponding third feature based on the feature mixing layer based on the second feature; input the third feature into the linear output head and the nonlinear output head respectively to obtain the linear feature output by the linear output head and the nonlinear feature output by the nonlinear output head; fuse the linear feature and the nonlinear feature to obtain the fused feature; and determine the probability of the vulnerability based on the fused feature.
8. The apparatus according to claim 7, characterized in that, The operation of determining the smart contract complexity of the smart contract to be tested includes: determining the number of lines of code, the number of functions, and the number of variables of the smart contract to be tested; normalizing the number of lines of code, the number of functions, and the number of variables respectively to obtain corresponding normalized values; and determining the smart contract complexity based on the normalized values corresponding to the number of lines of code, the number of functions, and the number of variables respectively.
9. A smart contract vulnerability detection device based on machine learning and dynamic / static combined analysis, characterized in that, include: processor; as well as A memory, connected to the processor, for providing the processor with instructions to perform the following processing steps: The smart contract to be tested is converted into vector form to obtain the corresponding input data; The input data is fed into the detection model, and the detection model determines the vulnerability probability corresponding to the smart contract to be detected. The vulnerability probability is used to represent the probability that the smart contract to be detected has a reentrancy attack vulnerability. Determine the smart contract complexity of the smart contract to be tested; as well as Based on the vulnerability probability and the smart contract complexity, determine the vulnerability detection method for the smart contract to be tested, and perform vulnerability detection on the smart contract to be tested according to the vulnerability detection method; Furthermore, the detection model includes a sequence mixing layer, a multi-head self-attention layer, a feature mixing layer, and an output layer, wherein the output layer includes a linear output head and a non-linear output head arranged in parallel. The operation of determining the vulnerability probability corresponding to the smart contract to be detected through the detection model includes: Based on the sequence mixing layer, a first feature corresponding to the smart contract to be detected is determined; based on the first feature, a corresponding second feature is determined based on the multi-head self-attention layer; based on the second feature, a corresponding third feature is determined based on the feature mixing layer; the third feature is input into the linear output head and the nonlinear output head respectively to obtain the linear feature output by the linear output head and the nonlinear feature output by the nonlinear output head; the linear feature and the nonlinear feature are fused to obtain a fused feature; and based on the fused feature, the vulnerability probability is determined; wherein, the operation of determining the vulnerability detection method of the smart contract to be detected based on the vulnerability probability and the smart contract complexity includes: Based on the correlation coefficients corresponding to the vulnerability probability and the smart contract complexity, the weights corresponding to the vulnerability probability and the smart contract complexity are determined, wherein the correlation coefficients are used to represent the correlation between the corresponding variables and whether the smart contract to be detected has a reentrancy attack vulnerability. Based on the weights corresponding to the vulnerability probability and the smart contract complexity, a weighted sum is performed on the vulnerability probability and the smart contract complexity to obtain a comprehensive score for the smart contract to be tested. Based on the comprehensive score, the vulnerability detection method for the smart contract to be tested is determined.
Citation Information
Patent Citations
Smart contract reentrant vulnerability detection method and system based on sequence model
CN114707154A
Cross-contract vulnerability detection method, system and equipment
CN116663012A