Intelligent contract multiplexing hierarchical detection method based on grammar and semantic separation
Through syntax and semantic separation and neural network technology, the syntax and semantic features of smart contracts are extracted, which solves the problem of affecting detection results in the existing technology, and achieves hierarchical detection and efficient detection of smart contract code reuse levels.
Patent Information
- Application Number
- CN202410750280.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-06-12
- Publication Date
- 2024-09-10
AI Technical Summary
Existing smart contract code reuse detection technology cannot effectively separate syntax and semantic information, resulting in affected detection results, unable to meet the security requirements of smart contracts, and has problems of over-fitting and low training efficiency.
Adopt a smart contract reuse hierarchical detection method based on syntax and semantic separation, construct contract-level and function-level detection data sets, use abstract syntax tree (AST) and program dependency graph (PDG) to extract syntax and semantic features, and combine with neural networks The model performs classifier training to achieve hierarchical detection of code reuse levels.
It realizes the feature extraction of syntactic and semantic separation of smart contract code, improves the accuracy and efficiency of detection, meets the security requirements of smart contracts, and realizes hierarchical detection of code reuse levels.
Smart Images

Figure CN118626376A
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of code reuse detection, and specifically relates to a smart contract reuse hierarchical detection method based on grammatical and semantic separation. Background Art
[0002] Code reuse refers to the reuse of existing code in the software development process to avoid rewriting similar functions or logic; code reuse helps improve the maintainability, reusability and scalability of the code, while also reducing development costs and time. A smart contract is a program that can run on a blockchain, usually written in solidity (a Turing-complete language). Unlike other programming languages, the execution of each line of code in a smart contract consumes Gas, or Ether. Therefore, when developing smart contracts, special attention should be paid to the simplicity of the code and to minimize the presence of redundant code; at the same time, in smart contracts, the need for code reuse is more common than in other programming languages.
[0003] At present, the reuse of smart contract code has become a trend in blockchain development, with a code reuse rate of smart contracts as high as 79.2%. Reasonable smart contract code reuse can help developers build smart contracts more efficiently and improve development efficiency. However, the reuse of smart contract code also brings some potential disadvantages: some vulnerable codes are often copied to new smart contracts together with normal codes, causing the spread of vulnerabilities and security issues of smart contracts; a large number of smart contract reuses will also cause plagiarism and infringement of source code.
[0004] Code similarity detection is one of the effective technical means to check code reuse. It can determine whether two pieces of code contain the same or similar code fragments. In the field of code similarity of traditional software, code reuse is usually divided into four levels: T1 is complete reuse; T2 is complete reuse of code except spaces, comments, variable or function renaming, etc.; T3 is code with slightly modified running logic based on T2; T4 is code with different implementation methods but the same functions. In the field of smart contracts, code similarity detection technology is used to discover real code cloning behavior in blockchain platforms.
[0005] After investigation and retrieval, it was found that the Chinese patent application with publication number CN113312268A provides a smart contract code similarity detection method. This method extracts the AST (Abstract Syntax Tree) of the smart contract source code, analyzes the variable sequence and the relationship between variables, and constructs a contract semantic graph. However, the detection results are affected by the problem that the AST contains too little semantic information.
[0006] The Chinese patent application with publication number CN117609005A parses the traditional source code through a code analysis tool to generate AST, CFG (Control Flow Graph) and function call relationships, and then adds function call edges to the corresponding nodes of AST and CFG according to the function call relationship, and uses word embedding technology to convert the nodes of AST and CFG into vector representations. Each layer uses the GAT (Graph Attention Network) model for feature learning, and uses the BiLSTM (Bidirectional Long Short-Term Memory) model for aggregate learning; however, the semantic information of CFG is always too scarce, and it does not contain data flow information, and the extensive use of neural network models is prone to overfitting problems; at the same time, the construction of contract-level AST and CFG and deep learning of them require a lot of computing power, and there are problems such as low training efficiency.
[0007] In the above technical solution, the separate processing of grammatical and semantic information is not actually achieved, and the stratification of contract reuse levels cannot be achieved. The similarity detection for traditional software source code cannot grasp the code writing characteristics of smart contracts, which cannot meet the security requirements of smart contracts. With the improvement of deep learning technology, the use of newer deep learning technology can effectively improve the accuracy and efficiency of detection. Summary of the invention
[0008] In view of the above, the present invention provides a smart contract reuse hierarchical detection method based on grammatical and semantic separation, which can realize smart contract code-level reuse detection at both grammatical and semantic levels, and extract features of the grammatical and semantic information of the contract code through neural network technology, thereby realizing the stratification of code reuse levels.
[0009] A smart contract reuse layered detection method based on grammatical and semantic separation includes the following steps:
[0010] (1) Construct contract-level and function-level smart contract code reuse detection datasets respectively;
[0011] (2) Perform text detection on each contract-level smart contract code to be tested in the dataset, detect and mark similar reused codes at the T1 and T2 levels;
[0012] (3) For unidentified smart contract code pairs, they are preprocessed first, then the contracts are split into functions and converted into abstract syntax trees (ASTs), and then the ASTs are multi-layered with weighted allocations to extract grammatical features of the codes;
[0013] (4) For unidentified smart contract code pairs, extract data flow, control flow and dependency relationships from their functions, generate a program dependency graph (PDG), and extract semantic features of the code;
[0014] (5) The extracted grammatical features and semantic features are combined and passed through a classifier to detect the similar results of smart contract code pairs T3 and T4 or the dissimilar results of T0.
[0015] Furthermore, the specific implementation method of step (1) is as follows: in the case that there is no well-labeled open source dataset in the field of smart contract code reuse detection, by collecting real contract codes from Ethereum, whose source code is publicly available, and marking whether they are similar and the degree of similarity, a contract-level smart contract code reuse detection dataset is constructed; the collected contract codes are split according to functions, the functions are matched and combined, and they are marked again according to the above method to construct a function-level smart contract code reuse detection dataset.
[0016] Furthermore, the specific implementation method of step (2) is as follows: text detection is performed on any of the contract-level smart contract codes C1 and C2 to be tested, which is divided into T1-level text detection and T2-level text detection; the T1-level text detection is to perform a text check on C1 and C2 word by word. If they are exactly the same after the check, C1 and C2 are determined to be reused codes similar to the T1 level; if the above detection determines that C1 and C2 are not similar, then a T2-level text detection is performed on them, that is, all non-critical characters in C1 and C2 (including code comments, spaces, line breaks, indentation characters, etc. that are not related to code compilation) are deleted, and the variables in C1 and C2 are uniformly identified, and the processed C1 and C2 are checked word by word again. If they are exactly the same after the check, C1 and C2 are determined to be reused codes similar to the T2 level.
[0017] Furthermore, in the process of T2 level text detection, the variables in C1 and C2 are uniformly identified. The specific implementation method is: for any section of the smart contract code to be tested, its data dictionary Dict is constructed and initialized according to the following expression ch , and replace the variable names with virtual variable names to obtain the code after unified identification processing;
[0018] Dict ch ={var1:simpleVar1,var2:simpleVar2,…,var i :simpleVar i}
[0019] Where: var iIndicates the i-th variable name found by traversing the contract code, simpleVar i Indicates the corresponding var i The virtual variable name is set, and i is the index number of the variable name.
[0020] Furthermore, in step (3), for the smart contract codes C1 and C2 that are not identified as similar, the function blocks of C1 and C2 are first split and serialized to obtain function block sets F1 = {f m ∈C1|f1,f2,…,f m} and F2={v n ∈C2|v1,v2,…,v n}, m and n are the number of function blocks in C1 and C2 respectively, and then an abstract syntax tree AST is constructed for each function block to obtain the abstract syntax tree set of C1 and C2.
[0021] Abstract syntax tree (AST) is a tree-structured data used to represent the abstract syntax structure of program code. In computer science, AST is a commonly used data structure in compilers and interpreters, used to analyze and operate on code when compiling or interpreting it. AST represents the syntax structure of the source code as a tree structure, where each node represents a syntax structure unit in the source code, such as an expression, statement, function definition, etc. AST node is the smallest unit token for processing and encoding in this article. Each node of the tree usually has a node type, representing different syntax structures in the code, and may have child nodes to represent the substructure of the node.
[0022] Furthermore, the specific method for implementing code syntax feature extraction in step (3) is as follows: for any AST, first perform a pre-order traversal on it, delete unnecessary modification statements of the AST, and only retain the type information of the token to obtain the pre-order traversal sequence of the AST; then use the word2vec encoding technology to encode the AST to obtain the feature vector of each token therein, and combine these feature vectors to obtain the feature matrix of each function block Where p represents the dimension of the feature vector, and i represents the number of tokens in the AST. Then, by adding weights to the key nodes that contain identifiers that play a key role in the operation of the smart contract (such as transfer operations, msg.sender, etc.), the feature matrix The vectors in are weighted average pooled to obtain the function block f m The eigenvector of In this way, all function blocks in F1 and F2 are traversed to obtain the characteristic matrices of C1 and C2 respectively. and Finally, the feature matrix and Perform average pooling respectively to obtain the grammatical feature vectors of C1 and C2 and
[0023] Furthermore, in step (4), for any function block of the smart contract code, delete the modifier that affects the compilation (for example, limiting the specific address onlyOwner, limiting the administrator onlyAdmin, etc.), and then compile to generate bytecode, construct a control flow graph CFG and a data flow graph DFG (Data Flow Graph) for the bytecode of each function block, and combine the program dependencies to generate the PDG sets of C1 and C2.
[0024] The program dependency graph (PDG) is a graphical representation used to analyze program structure and dependency relationships. It uses statements in a program as nodes and control flow, data flow, and dependency relationships as edges. In PDG, control flow edges represent the order of program execution, data flow edges represent dependencies between variables, and dependency edges represent dependencies in the program, including control dependencies and data dependencies.
[0025] Furthermore, the specific method for implementing code semantic feature extraction in step (4) is as follows: first, construct a graph neural network model based on the node attention mechanism, use the function-level smart contract code reuse detection dataset to train the model, the model outputs a function-level feature vector pair, and uses the fully connected layer to obtain the similarity score and calculate the loss function (it should be noted that the similarity score is only applied to the training process of the graph neural network model, so that the model improves the accuracy in the direction of semantic similarity detection, and is not applied to the final similarity judgment); then the function block f m The corresponding PDG obtains the function block f through the trained graph neural network model m The eigenvector of In this way, each function block in F1 and F2 is tested through the model to obtain the characteristic matrices of C1 and C2 respectively. and Finally, the feature matrix and Perform average pooling respectively to obtain the semantic feature vectors of C1 and C2 and
[0026] Furthermore, the specific implementation of step (5) is as follows: first, the grammatical feature vector of the smart contract code pair to be tested is and And the semantic feature vector and Connect the end to end to get Then, an MLP (multi-layer perceptron) model is constructed and trained using the contract-level smart contract code reuse detection dataset. The model parameters are optimized through labels and loss functions and set to a multi-classification task (three categories: T3, T4, and T0, where T0 is the smart contract code pair marked as dissimilar). Finally, t input The input is fed into the trained MLP model to obtain the final classification result, which is to determine whether the smart contract code pair to be tested is a similar result of T3 and T4 or a dissimilar result of T0.
[0027] The present invention starts from the source code of the smart contract, first screens out similar codes at the T1 and T2 levels through text detection, then constructs the corresponding AST and PDG respectively, and then extracts the code syntax features through the node embedding and multi-layer pooling technology of the AST, extracts the code semantic features through the graph neural network after embedding the graph node code of the PDG, and finally further extracts the syntax and semantic features through the multi-layer perceptron to realize code similarity detection and stratification of the similarity levels of T3, T4 and T0. Therefore, the present invention can effectively detect the problem of smart contract code reuse and realize the stratification of code reuse levels. Compared with the traditional code cloning detection method, the present invention performs feature extraction of syntax and semantic separation on the smart contract source code, and finally realizes more accurate code reuse detection effect through neural network technology, and realizes accurate reuse level stratification, which has good versatility and practical value. Its beneficial technical effects and innovation are mainly reflected in the following three aspects:
[0028] 1. The present invention proposes AST-based node embedding and multi-layer pooling technology, which solves the balance problem between feature extraction efficiency and feature dimension control (i.e., computational efficiency and dimensionality explosion) at the code level. At the same time, the present invention distributes weights to important nodes of smart contracts, improves the ability to obtain features of sensitive operations of smart contracts, and realizes effective grammatical feature extraction for smart contracts.
[0029] 2. The present invention proposes a semantic feature extraction technology based on PDG and graph neural network. By acquiring and encoding the PDG of the smart contract, the semantic information of the smart contract is effectively acquired. At the same time, the present invention uses a graph neural network based on the self-attention mechanism to extract semantic information in PDG, thereby improving the accuracy and efficiency of feature extraction and realizing effective semantic feature extraction for smart contracts.
[0030] 3. The present invention uses a multi-layer perceptron to train the collected grammatical and semantic features through a data set, thereby improving the accuracy and efficiency of similarity detection of test code pairs and realizing the stratification of code reuse levels. BRIEF DESCRIPTION OF THE DRAWINGS
[0031] Figure 1 The figure is a schematic diagram of the overall process of the smart contract reuse layered detection method of the present invention.
[0032] Figure 2 A schematic diagram of the process of extracting grammatical features of smart contracts in the present invention.
[0033] Figure 3 A schematic diagram of the process of extracting semantic features of smart contracts in the present invention.
[0034] Figure 4 This is a schematic diagram of similarity detection and reuse layering based on grammatical and semantic separation of the present invention. DETAILED DESCRIPTION
[0035] In order to describe the present invention more specifically, the technical solution of the present invention is described in detail below in conjunction with the accompanying drawings and specific implementation methods.
[0036] like Figure 1 As shown, the smart contract reuse layered detection method of the present invention uses deep learning technology to realize smart contract reuse detection and reuse layer stratification, which specifically includes the following steps:
[0037] (1) Text detection is performed on the contract-level smart contract code pairs C1 and C2. For T1-level text detection, the text of C1 and C2 is checked word by word. Two contracts that are completely identical after the check are determined to be T1-level similar. For C1 and C2 that are determined to be dissimilar by the above detection, T2-level text detection is performed on them. The processed C1 and C2 are checked word by word again using the above method. Two contracts that are completely identical after the check are determined to be T2-level similar.
[0038] (2) Extract the grammatical information of the contract-level smart contract codes C1 and C2, split C1 and C2 and serialize the identifiers to obtain the function block sets F1 and F2; generate an abstract syntax tree AST for each function in F1 and F2, traverse the AST in pre-order to obtain a token-based pre-order traversal sequence, use the word2vec encoder to encode the sequence, obtain a token-based feature matrix, perform weighted average pooling on the feature matrix, and obtain a function-based feature vector; after average pooling the feature vectors of all functions of a contract, obtain the final grammatical feature vector pair of the contract.
[0039] The specific implementation process of extracting smart contract code syntax information is as follows Figure 2 As shown:
[0040] 2.1 For the contract-level smart contract codes C1 and C2, the C1 and C2 function blocks are split and serialized to obtain the function block set F1 = {f m ∈C1|f1,f2,…,f m} and F2={v n ∈C2|v1,v2,…,v n}, where m and n are the number of functions in F1 and F2 respectively. For each function block, an abstract syntax tree AST is constructed to obtain the abstract syntax tree sets ASTSet1 and ASTSet2 of C1 and C2. The specific implementation is as follows:
[0041] ASTSet = {f k ∈F n |AST(f1),AST(f2),…,AST(f k )}
[0042] Among them: F n Represents the above serialized function block, and AST() represents AST construction.
[0043] Process all ASTs in ASTSet1 and ASTSet2, delete some unnecessary identifiers, retain only the type information of each token in AST, traverse the processed AST in pre-order, and obtain the serialized representation of the function token. In this step, compared with directly processing the contract code text, the processing of AST can discard unnecessary symbols and identifiers in the code and retain the main grammatical information of the code, which is convenient for the word2vec encoding technology below.
[0044] 2.2 For the token sequence generated above, use the word2vec tool to obtain the feature vector of each token in the sequence and merge it into a feature matrix. The specific implementation method is as follows:
[0045]
[0046] Where: i represents the number of tokens in the function, p represents the length of the feature vector, and w2c() represents the use of word2vec technology to vectorize the token. Word2vec is a tool for natural language processing that maps words in a text into a continuous vector space. It aims to capture the semantic associations between words by mapping the semantic relationships in the language into the vector space. Word2vec uses a shallow neural network model to represent each word as a dense vector of a fixed length by learning contextual information from a large text corpus. These vectors capture the grammatical relationship between words, so that the relationship between words can be inferred through vector operations in the vector space. Word2vec needs to learn from a large amount of training text. In this embodiment, we serialize all the data in the function set smart contract code data set mentioned above according to the above steps as the training set of word2vec.
[0047] 2.3 For the obtained feature matrix, the node that needs to be assigned key weights is added with weights, and the average weight pooling calculation is performed. The specific implementation method is as follows:
[0048]
[0049] Where: i represents the number of tokens in the function, p represents the length of the feature vector, W is the weight distribution matrix, This is the obtained eigenvector of the function.
[0050] 2.4 Perform average pooling on the feature vectors of all functions of a contract to obtain the final grammatical feature vector of the contract. The specific implementation method is as follows:
[0051]
[0052] Where: m represents the number of functions in the contract, p represents the length of the feature vector, t sy This is the obtained eigenvector of the function.
[0053] By using the above method, given a pair of smart contracts C1 and C2, we can get the grammatical feature vector pair of the contract: and
[0054] (3) Extract the semantic information of C1 and C2. For function blocks F1 and F2, delete the modifiers that affect compilation and generate bytecode after compilation. Construct a program dependency graph PDG for the bytecode of each function. Use Graph2vec encoding technology to encode each node and edge of PDG to obtain the feature vector representation of the node and edge. Construct a graph neural network model based on the self-attention mechanism to obtain the semantic feature vector pair at the function level.
[0055] The specific implementation process of extracting semantic information of smart contract code is as follows: Figure 3 As shown:
[0056] 3.1 For the contract-level smart contract codes C1 and C2, the C1 and C2 function blocks are split and serialized to obtain the function block set F1 = {f m ∈C1|f1,f2,…,f m} and F2={v n ∈C2|v1,v2,…,v n}, where m and n are the number of functions in F1 and F2 respectively. Construct a program flow graph PDG for each function block, and obtain the abstract syntax tree sets PDGSet1 and PDGSet2 of C1 and C2. The specific implementation is as follows:
[0057] PDGSet = {fk ∈F n |PDG(f1),PDG(f2),…,PDG(f k )}
[0058] Among them: F n Represents the above serialization function block, and PDG() represents PDG construction.
[0059] 3.2 Use graph2vec to encode the nodes and edges of PDG to obtain a data structure that can be processed by the graph neural network. The specific implementation method is as follows:
[0060] G=H2V(PDG m )=(V,E,X)
[0061] Among them: PDG m Represents the PDG graph to be converted, G2V() represents graph2vec encoding, V represents the structured graph node set, E represents the structured edge set, and X represents the edge e i Represented by (v i ,v j ) is a set of mapping relationships, where x i ∈X,e i ∈E,v i ,v j ∈V. Graph2Vec is a technology that represents graphs as fixed-length vectors. Its goal is to capture the structural information in the graph into the vector so that the graph can be compared, clustered, and classified in the vector space; the main idea of Graph2Vec is to use the local substructure of the graph to generate a graph representation, which usually includes steps such as graph partitioning, substructure embedding, graph embedding, and dimensionality reduction.
[0062] 3.3 Construct a graph neural network model based on the attention mechanism. After training, output the feature vector of the PDG graph of the input structured function-level smart contract code.
[0063] Graph Neural Network (GNN) is a neural network model used to process graph data. GNN can learn the complex relationships between nodes and the global structure of the graph. It is suitable for tasks such as graph classification, node classification, and graph generation. The formula expression of GNN is usually related to the structure of the graph and the characteristics of the nodes.
[0064] In this embodiment, we use a GNN model based on a node attention mechanism to obtain the semantic information of PDG through the attention mechanism. The construction method of the GNN model based on the node attention mechanism is as follows:
[0065] First, set the attention score function. In this embodiment, we use the scaled dot product method to calculate the attention score. The specific implementation is as follows:
[0066]
[0067] Where: h i and h j Represents the feature vector of two adjacent nodes, and d is the dimension of the feature vector.
[0068] Further, the attention weight is calculated for each node. In this embodiment, we use the softmax function to calculate the attention weight. The specific implementation is as follows:
[0069]
[0070] Where: N(i) is the node v i The set of neighbor nodes of That is v i For v j The attention weight.
[0071] Then, a graph convolution layer is constructed to realize message passing and aggregation of graph nodes. In this embodiment, we use a three-layer graph convolution network for training. The specific implementation of the graph convolution of each layer is as follows:
[0072]
[0073] in: Indicates that node v after calculating the attention weight i ∈V is the representation of the lth layer, N(i) is the node v i The set of neighbor nodes of Indicates v i v j The attention weight.
[0074] Next, the results are residually connected and layer normalized:
[0075]
[0076] in: is node v i ∈V is the feature representation of the lth layer, RelU() is the activation function, and LayerNorm() is the layer normalization operation.
[0077] Finally, for the function-level smart contract code pair to be tested, the above trained model is used for prediction, and the feature representation of the last layer of each node is averaged and pooled to obtain the final graph feature vector:
[0078]
[0079] in: is the final eigenvector representation of the graph and N is the number of nodes.
[0080] In this embodiment, the graph neural network model based on the node self-attention mechanism is only used to fit the semantic similarity prediction of two function-level smart contract codes. Therefore, the neural network model is trained using an independent data set. Instead of extracting semantic prediction results and training them separately from MLP, we use the fully connected layer to calculate For each classification category score, the softmax function is used to obtain the predicted probability of each category, and the semantic similarity and semantic dissimilarity are classified into two categories. Finally, the cross entropy loss is used to calculate the model loss. The specific implementation method is as follows:
[0081]
[0082] Where: W, b are the weight matrix and bias vector in the fully connected layer, respectively, z is The output vector obtained by the classifier, z c represents the score of z for category c∈C, represent For the predicted probability of category c∈C, y c represent The label value in the data set, loss is the required cross entropy loss.
[0083] Through the above-mentioned multi-layer attention mechanism, message passing, and aggregation operations, the graph neural network based on the node attention mechanism can capture the complex relationships in the graph structure, learn the representation of the nodes, and obtain the feature representation of the function-level contract code.
[0084] 3.4 Perform average pooling on the feature vectors of all functions of a contract to obtain the final semantic feature vector of the contract. The specific implementation method is as follows:
[0085]
[0086] Where: m represents the number of functions in the contract, p represents the length of the feature vector, t sa This is the obtained eigenvector of the function.
[0087] By using the above method, given a pair of smart contracts C1 and C2, we can get the grammatical feature vector pair of the contract: and
[0088] (4) The grammatical feature vector and semantic feature vector obtained above are concatenated head to tail; a multi-layer perceptron MLP is constructed and set as a multi-classification task. After training, the final classification result is obtained, which is determined to be a similar result of T3 and T4 or a dissimilar result of T0.
[0089] The specific implementation process of similarity detection and reuse layering based on grammatical and semantic separation is as follows: Figure 4 As shown:
[0090] Through the above method, a pair of grammatical feature vectors of smart contracts C1 and C2 are extracted. and And the semantic feature vector pair and Connect the four vectors end to end to get the joint eigenvector t C , input the multi-layer perceptron MLP, and use the softmax function for three classifications.
[0091] Multilayer Perceptron MLP is a basic artificial neural network model. MLP is a multi-layer network composed of several neurons, including an input layer, at least one or more hidden layers and an output layer. In MLP, each neuron is connected to all neurons in the previous layer, and each connection has a weight. Each neuron contains an activation function, and nonlinear activation functions are usually used in the hidden layer and the output layer. The existence of hidden layers enables MLP to learn nonlinear patterns. MLP is usually used for supervised learning tasks such as classification and regression.
[0092] The classification task in this embodiment uses a three-layer MLP, including an input layer, a hidden layer, and an output layer, and uses a softmax function to achieve multi-classification.
[0093] The specific implementation method is as follows:
[0094]
[0095] h1=ReLU(W1·t C +b1)
[0096] h2=ReLU(W2·h1+b2)
[0097]
[0098] in: represents the feature connection operation of the vector, W k is the weight matrix of each layer in MLP, b k is the bias vector of each layer, ReLU() is the ReLU activation function, and softmax() is the softmax activation function.
[0099] Then, the cross entropy function is used to calculate the loss of the model. The specific implementation is as follows:
[0100]
[0101] in: Represents t C For the predicted probability of category c∈C, y represents t C The label value in the data set, loss is the required cross entropy loss.
[0102] The MLP is trained by using labels and loss functions and set as a multi-classification task to obtain the final classification result, which is determined as the similar result of T3 and T4 or the dissimilar result of T0, thus realizing code similarity detection and reuse stratification based on grammatical and semantic separation.
[0103] Below, we evaluate the accuracy of the model of the present invention on the validation sets of the two contract-level smart contract similarity datasets constructed, and quantitatively compare the prediction results of the present invention with other methods. The specific results are shown in Table 1:
[0104] Table 1
[0105]
[0106] In the table, Deckard, SmartEmbed and EClone are all the existing models with the highest accuracy for smart contract similarity detection. P represents the precision of the model, R represents the recall of the model, and F1-score represents the accuracy score that combines the precision and recall. It can be seen that the F1 scores of the model of the present invention are better than those of the existing models in both data sets, which shows that the model of the present invention is relatively balanced in the detection of positive and negative examples, and there is no situation where the detection is biased towards a certain category, and both are at the leading level in the industry; in terms of the average detection speed of a single piece of data, the model of the present invention is also better than the existing model.
[0107] At present, all classifiers for smart contract similarity detection in the industry do not subdivide the stratification of smart contract reuse levels. Therefore, the classification accuracy of the model of the present invention for different reuse levels is shown in Table 2:
[0108] Table 2
[0109]
[0110]
[0111] It can be seen that in the similarity of T1 and T2 levels, since the contract similarity detection at this level is relatively simple, the previous work (text-based detection) can be done quite well, and the model of the present invention has also reached a 100% detection level. For the similarity detection of T3 and T4 levels (ST3 / MT3 / WT3 represent the similarity categories of smart contracts at the statement level / function body level / contract level code, respectively, where the WT3 level corresponds to the same semantics of the contract level code, so it is classified as the same as the T4 level when statistics are taken), since the model of the present invention uses function as the minimum detection granularity, the classification accuracy scores at the ST3 and MT3 similarity levels are relatively insufficient, but for the WT3 / T4 reuse level, the model of the present invention effectively classifies the results of similar syntax and semantics and only semantic similarity; at the same time, for the T3 major category level, the classification results of the present invention also achieve satisfactory results. In general, the model of the present invention has achieved excellent results in the reuse level stratification.
[0112] The above description of the embodiments is to facilitate the understanding and application of the present invention by those skilled in the art. It is obvious that those skilled in the art can easily make various modifications to the above embodiments and apply the general principles described herein to other embodiments without creative work. Therefore, the present invention is not limited to the above embodiments. Improvements and modifications made by those skilled in the art to the present invention based on the disclosure of the present invention should be within the protection scope of the present invention.
Claims
1. A smart contract reuse hierarchical detection method based on grammatical and semantic separation, comprising the following steps: (1) Construct contract-level and function-level smart contract code reuse detection datasets respectively; (2) Perform text detection on each contract-level smart contract code to be tested in the dataset, detect and mark similar reused codes at the T1 and T2 levels; (3) For unidentified smart contract code pairs, they are preprocessed first, then the contracts are split into functions and converted into abstract syntax trees (ASTs), and then the ASTs are multi-layered with weighted allocations to extract grammatical features of the codes; (4) For unidentified smart contract code pairs, extract data flow, control flow and dependency relationships from their functions, generate a program dependency graph (PDG), and realize semantic feature extraction of the code; (5) The extracted grammatical features and semantic features are combined and passed through a classifier to detect the similar results of smart contract code pairs T3 and T4 or the dissimilar results of T0.
2. The smart contract reuse layered detection method according to claim 1 is characterized in that: The specific implementation method of step (1) is as follows: in the case that there is no well-labeled open source dataset in the field of smart contract code reuse detection, by collecting real contract codes from Ethereum, whose source code is publicly available, and marking whether they are similar and the degree of similarity, a contract-level smart contract code reuse detection dataset is constructed; the collected contract codes are split according to functions, the functions are matched and combined, and they are marked again according to the above method to construct a function-level smart contract code reuse detection dataset.
3. The smart contract reuse layered detection method according to claim 1 is characterized in that: The specific implementation method of step (2) is as follows: for any of the contract-level smart contract codes C1 and C2 to be tested, text detection is performed, which is divided into T1-level text detection and T2-level text detection; the T1-level text detection is to check the text of C1 and C2 word by word. If they are exactly the same after the check, C1 and C2 are determined to be reused codes similar to the T1 level; if the above detection determines that C1 and C2 are dissimilar, then T2-level text detection is performed on them again, that is, all non-key characters in C1 and C2 are deleted, and the variables in C1 and C2 are uniformly identified, and the processed C1 and C2 are checked word by word again. If they are exactly the same after the check, C1 and C2 are determined to be reused codes similar to the T2 level.
4. The smart contract reuse layered detection method according to claim 3 is characterized by: In the process of T2 level text detection, the variables in C1 and C2 are uniformly identified. The specific implementation method is: for any section of smart contract code to be tested, its data dictionary Dict is constructed and initialized according to the following expression ch , and replace the variable names with virtual variable names to obtain the code after unified identification processing; Dict ch ={var1: simpleVar1, var2: simpleVar2,…, var i :simpleVar i } Where: var i Indicates the i-th variable name found by traversing the contract code, simpleVar i Indicates the corresponding var i The virtual variable name is set, and i is the index number of the variable name.
5. The smart contract reuse layered detection method according to claim 1 is characterized in that: In step (3), for the smart contract codes C1 and C2 that are not identified as similar, the function blocks of C1 and C2 are first split and serialized to obtain function block sets F1 = {f m ∈C1|f1,f2,…,f m } and F2 = {v n ∈C2|v1,v2,…,v n }, m and n are the number of function blocks in C1 and C2 respectively, and then an abstract syntax tree AST is constructed for each function block to obtain the abstract syntax tree set of C1 and C2.
6. The smart contract reuse layered detection method according to claim 5 is characterized by: The specific method for implementing code syntax feature extraction in step (3) is as follows: for any AST, firstly perform a pre-order traversal on it, delete unnecessary modification statements of the AST, and only retain the type information of the token to obtain the pre-order traversal sequence of the AST; then use the word2vec encoding technology to encode the AST to obtain the feature vector of each token therein, and combine these feature vectors to obtain the feature matrix of each function block. Where p represents the dimension of the feature vector, and i represents the number of tokens in the AST. Then, by adding weights to the key nodes including the identifiers that are key to the operation of the smart contract, the feature matrix The vectors in are weighted average pooled to obtain the function block f m The eigenvector of In this way, all function blocks in F1 and F2 are traversed to obtain the characteristic matrices of C1 and C2 respectively. and Finally, the feature matrix and Perform average pooling respectively to obtain the grammatical feature vectors of C1 and C2 and 7. The smart contract reuse layered detection method according to claim 6 is characterized by: In step (4), for any function block of the smart contract code, delete the modifier that affects the compilation, then compile and generate bytecode, construct a control flow graph CFG and a data flow graph DFG for the bytecode of each function block, and combine the program dependencies to generate the PDG sets of C1 and C2.
8. The smart contract reuse layered detection method according to claim 7 is characterized in that: The specific method for implementing code semantic feature extraction in step (4) is as follows: first, construct a graph neural network model based on the node attention mechanism, use the function-level smart contract code reuse detection dataset to train the model, the model outputs a function-level feature vector pair, uses a fully connected layer to obtain a similarity score and calculate a loss function; then, the function block f m The corresponding PDG obtains the function block f through the trained graph neural network model m The eigenvector of In this way, each function block in F1 and F2 is tested through the model to obtain the characteristic matrices of C1 and C2 respectively. and Finally, the feature matrix and Perform average pooling respectively to obtain the semantic feature vectors of C1 and C2 and 9. The smart contract reuse layered detection method according to claim 8 is characterized in that: The specific implementation method of step (5) is as follows: first, the grammatical feature vector of the smart contract code pair to be tested is and And the semantic feature vector and Connect the end to end to get Then, the MLP model is constructed and trained using the contract-level smart contract code reuse detection dataset. The model parameters are optimized through labels and loss functions and set to a multi-classification task. Finally, t input The input is fed into the trained MLP model to obtain the final classification result, which is to determine whether the smart contract code pair to be tested is a similar result of T3 and T4 or a dissimilar result of T0.
Citation Information
Cited By
Smart contract code clone detection method based on AST multi-dimensional feature fusion
CN115422541A
Smart contract code clone detection method based on AST multi-dimensional feature fusion
CN115422541B
Code similarity detection method based on deep learning
CN120336871A
