Block chain intelligent contract vulnerability detection method based on multi-modal deep learning

Through multimodal deep learning method, combined with computer vision, code semantics and graph features, the problems of high false negative rates and poor detection performance in smart contract vulnerability detection are solved, achieving higher accuracy and recall rates, significantly improving Detection accuracy.

CN118886019APending Publication Date: 2024-11-01KUNMING UNIV OF SCI & TECH
View PDF 0 Cites 2 Cited by

Patent Information

Application Number
CN202411007384.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-07-25
Publication Date
2024-11-01

AI Technical Summary

Technical Problem

The existing smart contract vulnerability detection methods have problems such as high false negative rates, incomplete feature extraction and loss of semantic information, and the detection performance of the graph neural network is poor.

Method used

Using multimodal deep learning method, combining computer vision features, code semantic features and graph features, visual features are extracted through SwinV2 model, semantic features are extracted by UniXcoder model, graph neural network extracts graph features, and fuses them to build a classification model for smart contracts Vulnerability detection.

Benefits of technology

It significantly improves the accuracy and recall rate of vulnerability detection, avoids the risks of insufficient extraction of single modal feature and loss of semantic information, and realizes more comprehensive and accurate smart contract representation, improving detection accuracy.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118886019A_ABST
    Figure CN118886019A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of blockchain smart contract security, in particular to a blockchain smart contract vulnerability detection method based on multi-modal deep learning, and the method comprises the following steps: S1, extracting a code attribute graph (CPG) of a smart contract; s2, a large-scale pre-training visual model of SwinTransformV2 is adopted to extract computer visual features; s3, a large-scale pre-training model of UniXcoder is adopted to extract code semantic features; s4, forming a graph feature extractor by a plurality of staggered graph convolution / pooling layer blocks (Conv-Pool blocks) to extract graph features; and S5, fusing the three features obtained by the feature extractors in the steps S2, S3 and S4 together to obtain a multi-modal feature to realize reentry vulnerability detection of the block chain smart contract. According to the detection method based on multi-modal deep learning disclosed by the invention, the detection precision of the block chain smart contract re-entry vulnerability can be effectively improved, and the security risk prevention work of the block chain smart contract is promoted.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of blockchain smart contract security technology, and in particular to a blockchain smart contract vulnerability detection method based on multimodal deep learning. Background Art

[0002] Smart contracts occupy a vital position in the blockchain ecosystem and are one of the most widely used applications of blockchain technology. In blockchain systems, smart contracts involve millions of dollars worth of cryptocurrencies, which makes it possible for vulnerabilities in smart contracts to cause serious economic losses. Therefore, it is particularly important to improve the quality of smart contracts before they are deployed. However, due to the complex semantic characteristics of domain-specific languages ​​and the potential destructive changes that may occur during their evolution, there are certain technical challenges in developing reliable and secure smart contracts. Due to the immutability of blockchain technology, smart contracts cannot be updated once they are deployed. Therefore, before deploying smart contracts, they must be tested for vulnerabilities.

[0003] Traditional smart contract vulnerability detection methods, such as formal verification, symbolic execution, and fuzz testing, can no longer meet the needs of the growing number of smart contracts through expert knowledge and path coverage traversal. Compared with traditional vulnerability detection technology, vulnerability detection technology based on machine learning can effectively use past data to train models, greatly improving the efficiency of smart contract vulnerability detection. In many tasks, these methods have been proven to be superior to traditional vulnerability detection methods. Machine learning-based methods can be divided into traditional machine learning detection methods and deep learning detection methods. Traditional machine learning detection methods include support vector machines, decision trees, random forests, etc. Compared with traditional machine learning methods, deep learning methods have stronger expression and adaptability, and can better mine complex patterns and rules in smart contracts. Commonly used deep learning detection methods include long short-term memory models and graph neural networks.

[0004] The existing Chinese patent document CN202110170847.4 discloses an automated detection method for smart contract vulnerabilities based on graph neural networks, including the following: (1) The smart contract virtual machine compiles the smart contract vulnerability source code (2) Constructs the smart contract code property graph (CPG) (3) Pre-trains the CPG code property graph using the BERT pre-training method (4) Creates a graph embedding model to extract vulnerability features (5) Trains the graph neural network vulnerability detection model (6) Uses the model to detect vulnerabilities. The present invention is an automated analysis method for smart contract vulnerabilities based on a graph neural network, which can automatically learn potential smart contract vulnerability features or representations to achieve automated analysis of smart contract vulnerabilities. It is found from the above-mentioned prior art that the current smart contract vulnerability detection method has the following problems:

[0005] The vulnerability patterns defined by traditional manual methods are relatively simple and cannot cover some complex vulnerabilities, which will lead to a high false negative rate;

[0006] Existing machine learning detection methods generally focus on a single modality of smart contracts, extracting one form of features from the smart contract source code, operation code or bytecode, which carries the risk of incomplete feature extraction and loss of semantic information.

[0007] The graph structure used by existing graph neural network-based methods is too complex and performs poorly in detection performance.

[0008] The solution of the present invention comprehensively utilizes multiple characteristic representations of smart contracts, including computer vision features, code semantic features, and graph features, so as to more deeply understand and analyze smart contracts. With the help of computer vision features, the structure and function of smart contracts can be understood. Code semantic features are achieved by in-depth analysis of the source code of smart contracts, so as to more accurately understand the logic and behavior of smart contracts. Graph features are achieved by analyzing the code attribute graph structure of smart contracts, so as to more accurately understand the structure and relationship of smart contracts. These different features express the characteristics of smart contracts from different dimensions. Combining these features can obtain a more comprehensive and accurate representation of smart contracts. This combination is not a linear performance improvement, but a power-like improvement. Summary of the invention

[0009] The purpose of the present invention is to provide a blockchain smart contract vulnerability detection method based on multimodal deep learning. In order to fully explore and utilize the multiple feature representations of smart contract codes; the present invention comprehensively utilizes multiple modal features such as smart contract computer vision features, code semantic features, and graph features. Specifically, the code property graph (CPG) of the smart contract is first extracted. In terms of computer vision features, the technology of converting CPG into pictures is adopted, and the Transformer-based computer vision pre-trained model SwinV2 is used for feature extraction to obtain the required computer vision features. The semantic features of the contract code are extracted with the help of the BERT-based pre-trained model UniXcoder. For graph-based representation, a graph-based neural network is selected as a feature extraction tool. Finally, the features of these three different dimensions are fused to construct the multimodal features of the smart contract, and they are used to construct the final classification model.

[0010] In order to achieve the above technical objectives and the above technical effects, the present invention is implemented through the following technical solutions:

[0011] A blockchain smart contract vulnerability detection method based on multimodal deep learning includes the following steps:

[0012] S1: Extracted the code property graph (CPG) of the smart contract;

[0013] S2: The large-scale pre-trained visual model of Swin TransformerV2 is used to extract computer vision features. For a given CPG image I, SwinV2 takes it as input and outputs a vectorized feature representation. The dimension of the output feature vector is 1536, which means that it can represent very complex image information. However, in order to reduce the computational complexity and improve the generalization ability of the model, this feature vector is usually further processed. Specifically, the feature vector is projected into a smaller space of 512 dimensions through a fully connected layer. In this way, a more concise and representative image feature can be obtained, which can be expressed as I c ∈R 1×D .

[0014] Among them I c represents the computer vision feature vector, R represents the computer vision model feature matrix, and D is equal to 512.

[0015] S3: Use UniXcoder's large-scale pre-trained model to extract code semantic features. Split the code of a given contract into separate statements. First, split the code of a given contract into separate statements. Then, the entire contract and individual statements (code lines) are labeled by UniXcoder's pre-trained Byte Pair Encoding (BPE) tagger. Next, UniXcoder converts the input smart contract and statement into 768-dimensional vectors respectively at the contract level and statement level. This means that a total of n+1 code features are generated, that is, 1 feature for the entire contract, and n features for all code lines. Similar to obtaining computer vision features for smart contracts, the acquired smart contract code semantic features are further projected through a fully connected layer. The final smart contract code semantic features can be expressed as T c ∈R 1×D , while the statement-level code feature T node ={t1,t2,...,t n} will be used as the initial node embeddings for the graph.

[0016] Where T c represents the code semantic feature vector, R represents the code semantic model feature matrix, t i The feature vector representing the code line, T node The set of feature vectors representing code lines, D is equal to 512.

[0017] S4: Multiple interlaced graph convolution / pooling layer blocks (Conv-Pool blocks) form a graph feature extractor to extract graph features. The graph output layer integrates features of different graph scales and projects them through a fully connected layer (FC) to map the features to the final output result. In order to ensure the weight balance of the three modal features, the fully connected layer is further used to project the normalized vector of the obtained graph. The final graph feature can be expressed as V c ∈R 1×D .

[0018] Where V c represents the graph feature vector, R represents the graph feature matrix, and the value of D is equal to 512.

[0019] S5: The three features I obtained by the feature extractors in steps S2, S3, and S4 are c 、V c and T c Fusion together to obtain the multimodal feature F = [I c ,V c ,T c ], where F∈R 1×D The overall goal is to evaluate whether a contract is vulnerable, which is a typical binary classification problem. By passing the final representation F to the fully connected layer (i.e., the final classification layer) and the Softmax layer, the probability distribution of the class label of a given input contract can be obtained. During the training phase, the cross entropy loss function is used to minimize the cross entropy loss, so that the predicted probability of the model is as close as possible to the probability distribution of the true label.

[0020] Among them I c represents the computer vision feature vector, V c represents the graph feature vector, T c represents the code semantic feature vector, F represents the multimodal fusion feature vector, R represents the multimodal fusion feature matrix, and the value of D is equal to 1536.

[0021] Furthermore, the CPG diagram in step S1 is represented as follows:

[0022] Given a smart contract code S = (s1, s2, ..., s n ), the CPG node can be represented as V = (v1, v2, ..., v n ). Each node relationship (direct edge) ε= <v i ,v j >From v i to v j Indicates th Node and j th The nodes are associated. The edges of CPG are composed of edges of multiple types of graphs λ = λ A ∪λ C ∪λP The nodes and the relationships between them that appear in the smart contract code are represented by a graph G = (V, E, λ).

[0023] where s i Indicates the smart contract code line, v i represents the node of the CPG graph, λ A Represents AST type edge, λ C represents the CFG type edge, λ P represents a PDG type edge, and E represents the set of edges ε.

[0024] Furthermore, the calculation process of SwinTransform Block, the core component of the SwinV2 model in step S2, can be described as follows:

[0025]

[0026] SwinV2 uses W_MSA and SW_MSA to replace MSA (Multi-head Self Attention). Assuming the image size is h×w and the SwinV2 window size is M×M, the image will be split into windows, and then perform Self-Attention operation on each window, and finally pass it through a multi-layer perceptron (MLP). This greatly reduces the amount of calculation, but isolates the information transmission between different windows, so it is necessary to slide each window down and left through a sliding window multi-head self-attention operation (SW_MSA). pixels, and perform another window Self-Attention operation in the sliding window, so that information can be transferred between adjacent windows. LN stands for LayerNormalization regularization. and z l Represents the output of the (S)W_MSA module and the MLP module of block l.

[0027] Furthermore, in step S3, UniXcoder first converts the source code into Tokens and retains the Position information of the code during the conversion process. After that, UniXcoder applies N Transformer layers on Tokens and Positions to generate hidden states. Each Transformer consists of a series of MSA (Multi-head Self Attention) operations. The formula for calculating MSA at layer l is as follows:

[0028] Q=H l-1 W Q

[0029] K=H l-1 W K

[0030] V=H l-1 W V

[0031]

[0032] in They are linearly mapped to the triples Q, K, and V, where Q, K, and V represent the query vector, key vector, and value vector, respectively. Q , W K , W V is the weight matrix of the linear transformation. k is the size of the head, It is a mask matrix, whose main function is to limit the focus range of the token during the context calculation process. Softmax represents the normalized exponential activation function, and T represents transpose.

[0033] Furthermore, the Conv-Pool block in step S4 includes a graph convolution layer and a graph pooling layer.

[0034] Graph Convolutional Layer (GCL). The general propagation law of feature transformation in the graph convolutional layer is as follows:

[0035]

[0036] in, Indicates that node v is in l th The output feature of the layer, d (l) represents the dimension, and N(v) represents the adjacent nodes of node v. Indicates l th The weight matrix of the layer. According to the principles proposed by some graph neural networks, it can be noted that the weight matrix of the feature transformation of the node itself (W1) and its neighbors (W2) can be different. σ(·) is the activation function.

[0037] Graph Pooling Layer (GPL). The goal of the graph pooling layer is to reduce the size of the original graph by using a pooling ratio k∈(0,1), thereby reducing the amount of subsequent computation in the network. Specifically, a graph with N nodes will have To achieve this goal, the layer reduces the number of projections to the learnable vector p after each pooling operation. nodes. At the same time, the projection score is also used as Gating value, which allows gradients to flow into Therefore, for the remaining nodes, the degree of feature preservation will be proportional to their projection scores.

[0038] Represents the node feature matrix. A is used to represent the adjacency matrix of the graph. The graph pooling layer calculates a pooled graph (F', A') from the input graph (F, A). Its transformation principle can be formally expressed as:

[0039]

[0040] ||·|| represents the L2 norm, represents a normalized matrix, top-k selects the top-k indices from a given input vector, ⊙ represents element-wise multiplication, tanh represents the hyperbolic tangent activation function, is an index operation, which Gets the node at the specified index.

[0041] Furthermore, in step S4, the graph output layer (GRL) is introduced to flatten the features of all nodes in order to achieve a fixed-length representation of the entire graph for graph classification tasks. Global average pooling and global maximum pooling are used to enhance the representation performance. In addition, a normalization operation is performed after the interleaved graph convolution / pooling layer (Conv-Pool block), and all normalizations are aggregated together. th Convolutional pooling block (F (l) ,A (l) )'s output graph vector It can be expressed as:

[0042]

[0043] Here, represents the feature vector of node i, N (l) represents the number of nodes in the graph, || represents the connection operation, and max represents the maximum value. Finally, the normalized vector of the graph is calculated as the sum of all these normalized vectors (i.e. ). It is worth noting that it is crucial to aggregate across Conv-Pool blocks to preserve information at different processing scales.

[0044] On the other hand, the present invention proposes the application of the above method in the detection of vulnerabilities represented by multiple features of smart contracts.

[0045] Beneficial effects of the present invention:

[0046] By comparing the existing methods, the main reason why traditional detection methods are generally low in accuracy and recall of vulnerability detection is that these methods are mainly based on a single and fixed pattern, and fail to fully consider the rich data dependencies and control dependencies in the smart contract code. The performance of graph-based neural networks in vulnerability detection is significantly better than that of traditional methods. This shows that graph modeling of source code and using graph neural networks for vulnerability detection is a promising solution. Compared with the existing graph neural network-based methods, multimodal deep learning models have obvious advantages in performance. The hardware environment for the experimental operation includes Intel Xeon Gold 5218, 128GB RAM and A10080G. The software environment uses Docker 24.0.1, Docker Compose 2.18.0 and pytorch / pytorch:1.13.0-cuda11.6-cudnn8-devel images. In terms of hyperparameter settings, the optimizer uses Adam, the batch size is 64, the loss function uses Cross-Entropy, and the pooling ratio and dropout rate are both 0.5. On the SmartBugs dataset, the recall rate, accuracy and F1 value of the multimodal deep learning model can reach 0.94, 0.92 and 0.93 respectively; this is mainly because in addition to introducing graph features, the multimodal deep learning model also further introduces a variety of other smart contract feature representations, including code semantic features and computer vision features. This multi-dimensional feature representation method can more comprehensively reflect the characteristics of smart contracts.

[0047] The present invention comprehensively utilizes multiple feature representations of smart contracts, namely computer vision features, code semantic features and graph features.

[0048] The present invention converts the code property graph (CPG) of the smart contract into an image and extracts features through the large-scale pre-trained visual model SwinTransformerV2. The SwinV2 model performs Self-Attention operations on each window to ensure the full extraction of local features, while the sliding window multi-head self-attention operation enhances the ability of global information transmission. This method enables the visual model to recognize large-resolution visual features and capture potential vulnerability patterns in the code structure. The present invention converts the code into a Token and retains its Position information through the UniXcoder model. The application of multiple layers of Transformer layers generates implicit states. This multi-head self-attention mechanism can comprehensively parse the code semantics from the statement level to the contract level, and extract deep semantic features and their contextual relationships. The code semantic features remove the limitations of a single statement perspective and enhance the ability to capture logical vulnerabilities in smart contracts.

[0049] The present invention extracts graph structural features in CPG through graph neural networks. The graph convolution layer not only performs different weight transformations on the features of nodes and their adjacent nodes, making the feature representation richer; the graph pooling layer ensures the priority retention of important node features by gated screening of the projection scores of nodes. After multi-level graph convolution and pooling processing, the information of graph features in each layer is integrated through global pooling and normalization operations, and the pattern features of the complex relationship between codes are effectively extracted. Through the strategy of multimodal feature fusion, each modal feature is reduced in dimension in the fully connected layer and fused into a unified feature space, which significantly improves the expression ability and detection accuracy of the final classification model and avoids the risk of insufficient extraction of single modal features and loss of semantic information.

[0050] In the feature extraction process of the present invention, dimensionality reduction processing of high-dimensional feature vectors is adopted. For example, the 1536-dimensional feature vector extracted by SwinV2 is reduced to 512 dimensions through a fully connected layer, which not only reduces the computational complexity, but also improves the generalization ability of the model: the dimensionality reduction processing reduces the redundant information of the feature vector, so that the model can be trained and reasoned faster. In the feature extraction stage, the feature vectors of each modality are projected to the same dimension (512 dimensions) through a fully connected layer, so as to be uniformly processed in the multimodal fusion process to ensure the weight balance of different modal features. In addition, the graph pooling layer reduces the number of nodes in the graph by screening the projection scores of the nodes, thereby reducing the amount of calculation of the subsequent graph convolutional network. Effective feature extraction and dimensionality reduction strategies not only improve the detection efficiency, but also ensure the stable performance and high accuracy of the model when facing different types of smart contracts.

[0051] The graph feature extractor proposed in the present invention is composed of multiple interlaced graph convolution and pooling layer blocks (Conv-Pool blocks), which improves the representation ability of graph features: Graph convolution layer (GCL): In the feature propagation rule, not only the features of the node itself are transformed, but also the features of the neighboring nodes. Through different weight matrices and integrated activation functions, the features of the graph nodes are enriched. Especially in capturing cross-node relationships and complex interaction patterns, the depth and accuracy of graph feature representation are significantly improved. Graph pooling layer (GPL): Nodes are screened by the projection scores of learnable vectors to reduce the number of nodes with low projection scores, ensuring that the amount of calculation is reduced while retaining the information of important feature nodes. The dynamic adjustment mechanism of the pooling layer makes the retention and discarding of graph features balanced and adapted, and improves the computational efficiency of the graph convolutional network. When performing graph feature aggregation, the global representation of graph features is enhanced through global average pooling and global maximum pooling operations. The final graph output layer fuses multiple layers of features to ensure the complete expression of information of different processing scales, further enhancing the core role of graph features in vulnerability detection.

[0052] Of course, any product implementing the present invention does not necessarily need to achieve all of the advantages described above at the same time. BRIEF DESCRIPTION OF THE DRAWINGS

[0053] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings required for describing the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other accompanying drawings can be obtained based on these accompanying drawings without paying creative work.

[0054] Figure 1 It is a schematic diagram of the system model of the present invention;

[0055] Figure 2 Extract the CPG diagram from the smart contract source code;

[0056] Figure 3 This is a schematic diagram of the architecture of the graph feature;

[0057] Figure 4 The performance comparison between the present invention and existing mainstream detection tools is shown in the figure. DETAILED DESCRIPTION

[0058] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.

[0059] Example 1

[0060] The overall model of the blockchain smart contract vulnerability detection method based on multimodal deep learning described in this embodiment is as follows: Figure 1 shown.

[0061] Step 1: In the embodiment, the code property graph (CPG) of the smart contract is extracted. Figure 2 As shown in Figure 1, CPG integrates the graph representations of multiple smart contracts into a unified graph. This integration is achieved by fusing multiple code representations such as abstract syntax tree (AST), control flow graph (CFG) and program dependency graph (PDG) into one data structure.

[0062] Given a smart contract code S = (s1, s2, ..., s n ), the CPG node can be represented as V = (v1, v2, ..., v n ). Each node relationship (direct edge) ε= <v i ,v j >From vi to v j Indicates th Node and j th The nodes are associated. The edges of CPG are composed of edges of multiple types of graphs λ = λ A ∪λ C ∪λ P The nodes and the relationships between them that appear in the smart contract code are represented by a graph G = (V, E, λ).

[0063] where s i Indicates the smart contract code line, v i represents the node of the CPG graph, λ A Represents AST type edge, λ C represents the CFG type edge, λ P represents a PDG type edge, and E represents the set of edges ε.

[0064] Step 2: In the embodiment, extract computer vision features. Figure 1 As shown in the Computer Vision Features section, a tool called Graphviz is used to convert the generated CPG into image I. The CPG image is as follows Figure 2 As shown in Figure 1, a large-scale pre-trained visual model called SwinTransformerV2 is used as the main component for extracting visual features, taking I as input and outputting a vectorized feature representation. The dimension of the output feature vector is 1536, and the feature vector is projected into a smaller space of 512 dimensions through a fully connected layer, which can be represented as I c ∈R 1×D .

[0065] Among them I c represents the computer vision feature vector, R represents the computer vision model feature matrix, and D is equal to 512.

[0066] Step 3: In the embodiment, extract the code semantic features. Figure 1As shown in the code semantic features section, a large-scale pre-trained model called UniXcoder is used as the main component for extracting code semantic features. First, the code of a given contract is split into separate statements. Then, the entire contract and individual statements (code lines) are labeled by UniXcoder's pre-trained Byte Pair Encoding (BPE) tagger. Next, UniXcoder converts the input smart contract and statement into 768-dimensional vectors respectively at the contract level and statement level. This means that a total of n+1 code features are generated, i.e., 1 feature for the entire contract, and n features for all code lines. Similar to obtaining computer vision features for smart contracts, the acquired smart contract code semantic features are further projected through a fully connected layer. The final smart contract code semantic features can be expressed as T c ∈R 1×D , while the statement-level code feature T node ={t1,t2,…,t n} will be used as the initial node embeddings for the graph.

[0067] Where T c represents the code semantic feature vector, R represents the code semantic model feature matrix, t i The feature vector representing the code line, T node The set of feature vectors representing code lines, D is equal to 512.

[0068] Step 4: In the embodiment, extract the graph features. Figure 1 Figure feature part and Figure 3 As shown in Figure 1, the graph feature extractor consists of multiple interlaced graph convolution / pooling layer blocks (Conv-Pool blocks). The graph output layer integrates features of different graph scales and projects them to the final output result through a fully connected layer (FC). In order to ensure the weight balance of the three modal features, the fully connected layer is further used to project the normalized vector of the obtained graph. The final graph feature can be expressed as V c ∈R 1×D .

[0069] Where V c represents the graph feature vector, R represents the graph feature matrix, and the value of D is equal to 512.

[0070] Step 5: In the embodiment, smart contract vulnerabilities are classified. Figure 1 As shown in the right part, the smart contract vulnerability classification uses the three features I obtained from each feature extractor before classification. c 、V c and T c Fusion together to obtain the multimodal feature F = [I c ,V c,T c ], where F∈R 1×D The overall goal is to evaluate whether a contract is vulnerable, which is a typical binary classification problem. By passing the final representation F to the fully connected layer (i.e., the final classification layer) and the Softmax layer, the probability distribution of the class label of a given input contract can be obtained. During the training phase, the cross entropy loss function is used to minimize the cross entropy loss, so that the predicted probability of the model is as close as possible to the probability distribution of the true label.

[0071] Among them I c represents the computer vision feature vector, V c represents the graph feature vector, T c represents the code semantic feature vector, F represents the multimodal fusion feature vector, R represents the multimodal fusion feature matrix, and the value of D is equal to 1536.

[0072] Example 2

[0073] Experimental content

[0074] Experimental environment

[0075] The hardware environment for the experiment of the present invention includes Intel Xeon Gold 5218, 128GB RAM and A10080G, and the software environment includes Docker 24.0.1, Docker Compose2.18.0 and pytorch / pytorch:1.13.0-cuda11.6-cudnn8-devel image.

[0076] Dataset

[0077] The present invention uses the public dataset SmartBugs Wild dataset. The SmartBugs Wild dataset is based on the Solidity language and contains 47,398 real and unique sol files, covering approximately 203,716 contracts.

[0078] Evaluation Metrics

[0079] This paper adopts the evaluation indicators widely used in the field of smart contract vulnerability detection, including precision, recall and F1 value. The formulas for calculating these indicators are as follows:

[0080]

[0081] Experimental results and analysis

[0082] according to Figure 4From the quantitative results in , the following phenomena are observed. First, the accuracy of existing tools in detecting reentry vulnerabilities in smart contracts is not satisfactory. Among the benchmark methods, the highest accuracy is 85.24% and the average accuracy is only 66.12%. Secondly, the method of this application is superior to the existing methods to a large extent. Specifically, the accuracy of the method of this application is 7.1% higher than that of the best tool. In terms of recall rate, it is 6.76% higher than the best tool. In addition, the F1 value of the method of this application is 6.94% higher than the maximum value of the prior art, which shows that the method of this application has significantly improved in overall performance.

[0083] In summary, this paper proposes a blockchain smart contract vulnerability detection method based on multimodal deep learning, which comprehensively utilizes computer vision, code semantics and Figure 3 The feature fusion of three modalities is used to realize the reentrancy vulnerability detection of blockchain smart contracts. Specifically, the code property graph (CPG) of the smart contract is first extracted, and the computer vision model SwinV2 is used to learn the image visual features of the CPG; the pre-trained model UniXcoder is used to learn the code semantic features of the smart contract source code; and multiple groups of interleaved GNN blocks are used to learn the graph features of the CPG. The three feature vectors of the visual features and graphic features of the image of the smart contract CPG and the semantic features of the smart contract code are spliced ​​to realize the feature fusion of the three modalities, thereby realizing the detection of reentrancy vulnerabilities in blockchain smart contracts. The detection method based on multimodal deep learning disclosed in the present invention can effectively improve the detection accuracy of reentry vulnerabilities in blockchain smart contracts and promote the prevention of security risks of blockchain smart contracts.

[0084] The preferred embodiments of the present invention disclosed above are only used to help illustrate the present invention. The preferred embodiments do not describe all the details in detail, nor do they limit the invention to the specific implementation methods described. Obviously, many modifications and changes can be made according to the content of this specification. This specification selects and specifically describes these embodiments in order to better explain the principles and practical applications of the present invention, so that those skilled in the art can understand and use the present invention well. The present invention is limited only by the claims and their full scope and equivalents.

Claims

1. A blockchain smart contract vulnerability detection method based on multimodal deep learning, characterized in that: The following steps are involved: S1: Extracted the code property graph CPG of the smart contract; S2: Use Swin TransformerV2’s large-scale pre-trained visual model to extract computer vision features. For a given CPG image I, SwinV2 takes it as input and outputs a vectorized feature representation. The dimension of the output feature vector is 1536. The feature vector is projected into a smaller space of 512 dimensions through a fully connected layer. The obtained image feature is represented as I c ∈R 1×D ; where I c represents the computer vision feature vector, R represents the computer vision model feature matrix, and D is equal to 512; S3: UniXcoder’s large-scale pre-trained model is used to extract code semantic features. The code of a given contract is split into separate statements. The entire contract and individual statements are tagged by UniXcoder’s pre-trained byte pair encoding tagger. UniXcoder then performs conversions at the contract level and statement level, converting the input smart contract and statement into 768-dimensional vectors respectively, generating a total of n+1 code features, i.e., 1 feature for the entire contract and n features for all code lines. The obtained smart contract code semantic features are projected through the fully connected layer, and the final smart contract code semantic features are represented as T c ∈R 1×D , while the statement-level code feature T node ={t1,t2,…,t n } will be used as the initial node embedding of the graph; Where T c represents the code semantic feature vector, R represents the code semantic model feature matrix, t i The feature vector representing the code line, T node The set of feature vectors representing code lines, D is equal to 512; S4: Multiple interlaced graph convolution / pooling layer blocks form a graph feature extractor to extract graph features. The graph output layer integrates features of different graph scales and projects them through the fully connected layer to map the features to the final output result. The fully connected layer is used to project the normalized vector of the obtained graph to ensure that the weights of the three modal features are balanced. The final graph feature can be expressed as V c ∈R 1×D ; Where V c represents the graph feature vector, R represents the graph feature matrix, and the value of D is equal to 512; S5: The three features I obtained by the feature extractors in steps S2, S3, and S4 are c 、V c and T c Fusion together to obtain the multimodal feature F = [I c ,V c ,T c ], where F∈R 1×D ; By passing the final representation F to the fully connected layer (i.e. the final classification layer) and the Softmax layer, the probability distribution of the class label of the given input contract is obtained; in the training phase, the cross entropy loss function is used to minimize the cross entropy loss, so that the predicted probability of the model is as close as possible to the probability distribution of the true label, and the smart contract vulnerability classification is performed; Among them I c represents the computer vision feature vector, V c represents the graph feature vector, T c represents the code semantic feature vector, F represents the multimodal fusion feature vector, R represents the multimodal fusion feature matrix, and the value of D is equal to 1536.

2. The blockchain smart contract vulnerability detection method based on multimodal deep learning as claimed in claim 1, characterized in that: The CPG diagram in step S1 is represented as follows: Given a smart contract code S = (s1, s2, ..., s n ), the CPG node is represented by V = (v1, v2, ..., v n ); Each node relationship (direct edge) ε = <v i ,v j >From v i to v j Indicates th Node and j th Nodes are associated; the edges of CPG are composed of edges of multiple types of graphs λ = λ A ∪λ C ∪λ P ; The nodes and the relationships between the nodes that appear in the smart contract code are represented by the graph G = (V, E, λ); where s i Indicates the smart contract code line, v i represents the node of the CPG graph, λ A Represents AST type edge, λ C represents the CFG type edge, λ P represents a PDG type edge, and E represents the set of edges ε.

3. The blockchain smart contract vulnerability detection method based on multimodal deep learning as claimed in claim 1, characterized in that: The calculation process of the Swin Transform Block, the core component of the SwinV2 model in step S2, includes: SwinV2 uses W_MSA and SW_MSA to replace MSA (Multi-head Self Attention); suppose the image size is h×w, the SwinV2 window size is M×M, and the image will be divided into windows, and then perform Self-Attention operation on each window, and finally pass it through the multi-layer perceptron MLP; slide each window down and left through the sliding window multi-head self-attention operation SW_MSA pixels, and perform another window Self-Attention operation in the sliding window. This method allows information to be transferred between adjacent windows. LN represents LayerNormalization regularization. and z l Represents the output of the (S)W_MSA module and the MLP module of block l.

4. The blockchain smart contract vulnerability detection method based on multimodal deep learning as claimed in claim 1, characterized in that: In step S3, UniXcoder first converts the source code into Tokens and retains the Position information of the code during the conversion process; after that, UniXcoder applies N Transformer layers on Tokens and Positions to generate hidden states. Each Transformer consists of a series of MSA (Multi-head Self Attention) operations; the formula for MSA calculation at layer l is as follows: Q=H l-1 W Q K=H l-1 W K V=H l-1 W V in Linearly mapped to Q, K, V triples, where Q, K, V represent query vector, key vector, and value vector respectively; W Q , W K , W V is the weight matrix of the linear transformation; d k is the size of the head, It is a mask matrix, whose function is to limit the focus range of the token during the context calculation process; softmax represents the normalized exponential activation function, and T represents transpose.

5. The blockchain smart contract vulnerability detection method based on multimodal deep learning as claimed in claim 1, characterized in that: The Conv-Pool block in step S4 includes a graph convolution layer and a graph pooling layer; Graph convolution layer GCL; the propagation law of the feature transformation of the graph convolution layer is as follows: in, Indicates that node v is in l th The output feature of the layer, d (l) represents the dimension, N(υ) represents the neighboring nodes of node v; Indicates l th The weight matrix of the layer; σ(·) is the activation function; Graph pooling layer GPL; by using the pooling ratio k∈(0,1) to reduce the size of the original graph, thereby reducing the amount of subsequent computation in the network; after each pooling operation, according to the projection score of the learnable vector p, reduce nodes; at the same time, the projection score is also used as Gating value, which allows gradients to flow into For the remaining nodes, the degree of feature preservation will be proportional to their projection scores; Represents the node feature matrix; A is used to represent the adjacency matrix of the graph; the graph pooling layer calculates a pooling graph (F', A') from the input graph (F, A), and its transformation principle is formally expressed as: ||·|| represents the L2 norm, represents a normalized matrix, top-k selects the top-k indices from a given input vector, ⊙ represents element-wise multiplication, tanh represents the hyperbolic tangent activation function, is an index operation, which Gets the node at the specified index.

6. The blockchain smart contract vulnerability detection method based on multimodal deep learning as claimed in claim 1, characterized in that: In the step S4, the graph output layer GRL is introduced to flatten the features of all nodes, and global average pooling and global maximum pooling are used to enhance the representation performance; in addition, a normalization operation is performed after the interlaced graph convolution / pooling layer, and all normalizations are aggregated together; l th Convolutional pooling block (F (l) ,A (l) )'s output graph vector It can be expressed as: represents the feature vector of node i, N (l) represents the number of nodes in the graph, || represents the connection operation, and max represents the maximum value; finally, the normalized vector of the graph is calculated as the sum of all these normalized vectors (i.e. ).

7. Application of the method as described in any one of claims 1 to 6 in detecting vulnerabilities represented by multiple features of smart contracts.

Citation Information

Cited By

  • Software vulnerability detection method based on multi-modal feature adaptive fusion

    CN119004491A

  • Intelligent contract vulnerability detection method based on multi-mode selection state space fusion

    CN120277682A