A smart contract vulnerability detection method based on transfer learning

CN114547621BActive Publication Date: 2024-11-05YANGZHOU UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202210065372.7
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2022-01-20
Publication Date
2024-11-05
Estimated Expiration
2042-01-20

AI Technical Summary

Technical Problem

大多数机器学习方法都依赖大量现有的已知存在漏洞的智能合约代码,而现有的已知漏洞的智能合约代码数量十分匮乏,机器学习一旦缺少数据的训练量,就会导致模型的精度降低,无法适用于快速变化的智能合约应用和大规模代码的检测

Benefits of technology

[0039] Beneficial effects: Compared with the existing technology, the present invention has the following beneficial effects: The present invention establishes a smart contract vulnerability detection model based on migration learning, extracts and learns the characteristics of a large number of Java code vulnerabilities through pre-training, and then detects smart contract vulnerabilities. Fine-tuning the downstream tasks to complete the detection of new smart contract code vulnerabilities, alleviating the lack of smart contract code, and is not suitable for situations where traditional machine learning requires a large number of training samples; the present invention uses a Java code set with a vulnerability label established as a training Set, input the code processed into a sequence into the model to learn syntax and semantic features. And in the learning process, the attention mechanism is used, without considering the distance of the input elements in the sequence, and can be trained in parallel, which improves the efficiency of intelligent vulnerability detection. It can quickly know whether the contract contains vulnerabilities, which improves the efficiency of intelligent vulnerability detection.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN114547621B_ABST
    Figure CN114547621B_ABST
Patent Text Reader

Abstract

The present invention discloses a smart contract vulnerability detection method based on transfer learning. The method first collects java source code and smart contract source code data, performs preprocessing to establish labels, and constructs a sample set for machine learning; then the java sample set is input into the model for training, the features represented by the java code and the detection of java vulnerabilities are learned, and the java pre-trained model is reused and fine-tuned for the downstream task of detecting smart contract codes, so that it can be competent for the detection of smart contract vulnerabilities. The present invention can more quickly and automatically detect whether a Solidity smart contract has vulnerabilities.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention belongs to the field of software security, and specifically relates to a smart contract vulnerability detection method based on transfer learning. Background Art

[0002] In recent years, blockchain technology has flourished and has gradually surpassed the era of programmable currency and entered the era of smart contracts. Smart contracts are a kind of consensus rules that digitize traditional contracts and run them on the blockchain platform. They are decentralized and cannot be tampered with. They are visible to everyone, ensuring the transparency of smart contracts. They are widely used in many fields such as digital payment, cloud computing, and the Internet of Things.

[0003] However, compared to traditional software, since smart contracts manage a large amount of virtual assets, if they themselves have vulnerabilities and are attacked by exploiters, and the smart contracts are difficult to resolve quickly after being attacked, it will cause huge economic losses.

[0004] Most of the existing smart contract vulnerability detection methods rely on manually defined expert rules and perform vulnerability detection through technologies such as symbolic execution, taint analysis, and formal verification. These methods have problems such as low execution efficiency, low code coverage, and long detection cycle. Some methods use machine learning to train models and use the trained models to detect smart contract vulnerabilities. Most machine learning methods rely on a large number of existing smart contract codes that are known to have vulnerabilities, but the number of existing smart contract codes with known vulnerabilities is very scarce. Once machine learning lacks the amount of training data, the accuracy of the model will be reduced, and it will not be suitable for rapidly changing smart contract applications and large-scale code detection. Summary of the invention

[0005] Purpose of the invention: In view of the problems existing in the above-mentioned prior art, the purpose of the present invention is to provide a smart contract vulnerability detection method based on transfer learning with better adaptability and higher execution efficiency.

[0006] Technical solution: The present invention provides a smart contract vulnerability detection method based on transfer learning, comprising the following steps:

[0007] (1) Collect Java source code from the open source community and Solidity smart contract source code through the Etherscan platform, process them into sequences, and construct Java datasets and Solidity smart contract datasets;

[0008] (2) Use the Java dataset in step (1) to train a pre-trained CodeBERT model for Java code vulnerability detection;

[0009] (3) Retain some parameters of the Encoder trained in step (2), and use the Solidity smart contract source code dataset in step (2) to complete the fine-tuning process of the Java pre-trained model to achieve the migration process;

[0010] (4) Use the detection model trained in step (3) to input the smart contract code to detect whether there are any vulnerabilities.

[0011] Furthermore, the step (1) comprises the following steps:

[0012] (1.1) Obtain Java source code from the open source community and obtain the Solidity smart contract source code with tags from the Etherscan platform;

[0013] (1.2) Use a programming language vulnerability detection tool to detect the collected Java source code and mark it according to the detection results. The Java source code with vulnerabilities shown by the detection tool is marked as "1", otherwise it is marked as "0";

[0014] (1.3) Manually audit Java samples marked as having vulnerabilities to ensure the accuracy of sample marking;

[0015] (1.4) Convert the Java source code and Solidity smart contract source code into the sequence form of "<natural language text>, <programming language code>" respectively, and use them as Java dataset and smart contract dataset for machine learning.

[0016] Furthermore, the step (2) comprises the following steps:

[0017] (2.1) Input the Java dataset into the CodeBERT model, perform word embedding on the input word sequence and convert it into a word vector representation; add position encoding to each word vector; then the word vector flows into the Self-Attention layer of the Encoder encoder;

[0018] (2.2) In the Self-Attention layer of the Encoder, the weight of attention to each word vector is calculated using the scaled dot product; given an input word vector i, representing the embedding of each token, three vectors are created: the query vector q i , the key vector k i , value vector v i ; Use the query vector q of the i-th input i and the key vector k for each word in the input sentence j , the attention score is calculated by dot product, and the attention score for the i-th input is:

[0019]

[0020] Where d is q i and k j The dimension of , the attention score determines the degree of attention paid to the j-th input when encoding the j-th input;

[0021] (2.3) In order to normalize the scores of all words to be positive and sum to 1, the normalized scores are obtained by using the softmax function:

[0022]

[0023] Multiply each value vector by the softmax score to focus on semantically related words and weaken irrelevant words, and sum the weighted values:

[0024]

[0025] To speed up processing, the calculation uses matrix form:

[0026]

[0027] (2.4) The output of the Self-Attention layer is connected to a parameter matrix W, which is then linearly projected by the linear layer:

[0028] A=concat(Attention i (Q i ,K i ,V i ))W

[0029] Using the Mult-headedAttention multi-head attention mechanism, perform 8 different weight matrix calculations on each attention head to obtain 8 matrices, then concatenate all the attention heads and multiply them by the additional weight matrix W 0 :

[0030]

[0031] Among them, Z is the matrix obtained by fusing all the attention head information, thereby compressing the 8 matrices into one matrix; then the vector matrix Z of this layer is output to the feedforward neural network layer;

[0032] (2.5) In the feedforward neural network of the encoder, the encoder first converts the input vector matrix Z into a set of attention vectors, a combination of key vectors k and value vectors v, and inputs them into the encoder decoder for use;

[0033] (2.6) At each decoding stage in the Decoder, one element is output from the output sequence each time, and the process is repeated until a special symbol appears to complete the output of the decoder; each output is then fed back to the bottom decoder, and the positional encoding embedding is added to the decoder input to indicate the position of the word; the final output is a floating point vector, which is input to the Linear layer;

[0034] (2.7) In the Linear layer, the vector produced by the decoder stack is projected into a larger logits vector, which sets a specific cell width. Each cell corresponds to the score of a unique word. The scores are passed to the Softmax layer; in the Softmax layer, the scores are converted to probabilities, all positive and summing to 1.0, and then the cell with the highest probability is selected and the word associated with it is generated as the output for that time step.

[0035] Furthermore, the step (3) comprises the following steps:

[0036] (3.1) Use the Java pre-trained model trained in step (2), input the labeled smart contract dataset, and access the pre-trained Encoder encoder parameters to obtain Java code vulnerability knowledge;

[0037] (3.2) Fine-tune the model during the Solidity smart contract vulnerability detection process to learn and adapt the code semantics and vulnerability knowledge from the Java pre-trained model; reuse the pre-trained encoder to learn the representation of the smart contract code, and the decoder receives the results of smart contract vulnerability detection from the pre-trained encoder to achieve downstream detection tasks;

[0038] (3.3) The detected results are compared with the vulnerability labels of the smart contract samples to ensure the correctness of the model.

[0039] Beneficial effects: Compared with the prior art, the present invention has the following beneficial effects: The present invention establishes a smart contract vulnerability detection model based on transfer learning, extracts and learns the features of a large number of Java code vulnerabilities through pre-training, and then fine-tunes the downstream tasks of smart contract vulnerability detection, thereby completing the detection of new smart contract code vulnerabilities, alleviating the lack of smart contract code, and is not suitable for the situation where a large number of training samples are required for traditional machine learning; the present invention uses a Java code set with vulnerability labels as a training set, and inputs the code processed into a sequence into the model to learn grammatical and semantic features. In the learning process, the attention mechanism is adopted, and there is no need to consider the distance of the input elements in the sequence, and parallel training can be performed, which improves the efficiency of smart vulnerability detection, and can quickly know whether the contract contains vulnerabilities, thereby improving the efficiency of smart vulnerability detection. BRIEF DESCRIPTION OF THE DRAWINGS

[0040] Figure 1 It is a flow chart of the present invention. DETAILED DESCRIPTION

[0041] The present invention will be further described in detail below in conjunction with the accompanying drawings.

[0042] The present invention proposes a smart contract vulnerability detection method based on transfer learning, such as Figure 1 As shown, the following steps are included:

[0043] Step 1: Collect Java source code from the open source community, collect Solidity smart contract source code through the Etherscan platform, process them into sequences, and construct Java datasets and Solidity smart contract datasets. The specific process includes:

[0044] (1.1) Obtain the Java source code from the open source community and obtain the Solidity smart contract source code with tags from the Etherscan platform.

[0045] (1.2) The collected Java source code is detected by a programming language vulnerability detection tool and marked according to the detection results. The Java source code with vulnerabilities shown by the detection tool is marked as "1", otherwise it is marked as "0".

[0046] (1.3) Perform manual audits on Java samples marked as having vulnerabilities to ensure the accuracy of sample labeling.

[0047] (1.4) Convert the Java source code and Solidity smart contract source code into the sequence form of "<natural language text>, <programming language code>" respectively, and use them as Java dataset and smart contract dataset for machine learning.

[0048] Step 2: Use the Java dataset in step 1 to train a pre-trained model for Java code vulnerability detection. The specific process includes:

[0049] (2.1) Input the Java dataset into the CodeBERT model, embed the input word sequence into word vectors; in order to make the model understand the order of words, add position encoding to each word vector; then the word vector flows into the Self-Attention layer of the Encoder encoder.

[0050] (2.2) In the Self-Attention layer of the Encoder, the scaled dot product is used to calculate the weight of attention to each word vector; given an input word vector i, representing the embedding of each token, the first step is to create three vectors: query vector qi , the key vector k i , value vector v i ; Use the query vector q of the i-th input i and the key vector k for each word in the input sentence j , the attention score is calculated by dot product, and the attention score for the i-th input is:

[0051]

[0052] d is q i and k j The attention score determines the degree of attention paid to the j-th input when encoding the j-th input.

[0053] (2.3) In order to normalize the scores of all words to be positive and sum to 1, the normalized scores are obtained by using the softmax function:

[0054]

[0055] To keep the values ​​we want to focus on unchanged and ignore irrelevant tokens, we multiply each value vector by the softmax score to focus on semantically relevant words and weaken irrelevant words, and sum the weighted values:

[0056]

[0057] To speed up the process, the calculation can be done in matrix form:

[0058]

[0059] (2.4) The output of the Self-Attention layer is connected to a parameter matrix W, which is then linearly projected by the linear layer: A = concat(Attention i (Q i ,K i ,V i ))W

[0060] In order to pay attention to different channels of the input vector, the Mult-headed Attention mechanism is used to perform 8 different weight matrix calculations on each attention head to obtain 8 matrices. Then all the attention heads are concatenated and multiplied by the additional weight matrix W. 0 :

[0061]

[0062] Z is the matrix obtained by fusing all the attention head information, thereby compressing the 8 matrices into one matrix; then the vector matrix Z of this layer is output to the feedforward neural network layer;

[0063] (2.5) In the feedforward neural network of the Encoder encoder, the encoder first converts the input vector matrix Z into a set of attention vectors (a combination of key vectors k and value vectors v), which are input into the Encoder decoder for use, helping the decoder to focus on the appropriate positions in the input sequence.

[0064] (2.6) At each decoding stage in the Decoder, one element is output from the output sequence each time, and the process is repeated until a special symbol appears to complete the output of the decoder. Each output is then fed back to the bottom decoder, and the positional encoding embedding is added to the input of the decoder to indicate the position of the word; the final output is a floating-point vector, which is input to the Linear layer.

[0065] (2.7) In the Linear layer, the vector produced by the decoder stack is projected into a larger logits vector, which sets a specific cell width. Each cell corresponds to the score of a unique word. The scores are passed to the Softmax layer; in the Softmax layer, the scores are converted to probabilities, all positive and summing to 1.0, and then the cell with the highest probability is selected and the word associated with it is generated as the output for that time step.

[0066] Step 3: Keep some parameters of the Encoder trained in step 2, and use the Solidity smart contract source code dataset in step (2) to complete the fine-tuning process of the CodeBERT model to achieve the migration process. The specific process includes:

[0067] (3.1) Use the Java pre-trained model trained in step 2, input the labeled smart contract dataset, and access the pre-trained Encoder encoder parameters to obtain Java code vulnerability knowledge.

[0068] (3.2) During the Solidity smart contract vulnerability detection process, the model is fine-tuned to learn and adapt the code semantics and vulnerability knowledge from the Java pre-trained model; the pre-trained encoder is reused to learn the representation of the smart contract code, and the decoder receives the results of smart contract vulnerability detection from the pre-trained encoder to achieve downstream detection tasks.

[0069] (3.3) The detected results are compared with the vulnerability labels of the smart contract samples to ensure the correctness of the model.

[0070] Step 4: Use the detection model trained in step 3 to input the smart contract code to detect whether there are any vulnerabilities. The specific process includes:

[0071] (4.1) Input the Solidity smart contract source code into the trained detection model;

[0072] (4.2) The output is whether the smart contract code contains a vulnerability.

[0073] The above embodiments are preferred implementation modes of the present invention, but the implementation modes of the present invention are not limited to the above embodiments. Any other changes, modifications, substitutions, combinations, and simplifications that do not deviate from the spirit and principles of the present invention are equivalent replacement methods and are included in the protection scope of the present invention.

Claims

1. A smart contract vulnerability detection method based on transfer learning, characterized in that: The following steps are involved: (1) Collect Java source code from the open source community and Solidity smart contract source code through the Etherscan platform, process them into sequences, and construct Java datasets and Solidity smart contract datasets; (2) Use the Java dataset in step (1) to train a pre-trained CodeBERT model for Java code vulnerability detection; (3) Retain some parameters of the Encoder trained in step (2) and use the Solidity smart contract source code dataset in step (1) to complete the fine-tuning process of the Java pre-trained model to achieve the migration process; (4) Use the detection model trained in step (3) to input the smart contract code to detect whether there are any vulnerabilities; The step (2) comprises the following steps: (2.1) Input the Java dataset into the CodeBERT model, perform word embedding on the input word sequence and convert it into a word vector representation; add position encoding to each word vector; then the word vector flows into the Self-Attention layer of the Encoder encoder; (2.2) In the Self-Attention layer of the Encoder, the weight of attention to each word vector is calculated using the scaled dot product; given an input word vector i, representing the embedding of each token, three vectors are created: the query vector q i , the key vector k i , value vector v i ; Use the query vector q of the i-th input i and the key vector k for each word in the input sentence j , the attention score is calculated by dot product, and the attention score for the i-th input is: Where d is q i and k j The dimension of , the attention score determines the degree of attention paid to the j-th input when encoding the j-th input; (2.3) In order to normalize the scores of all words to be positive and sum to 1, the normalized scores are obtained by using the softmax function: Multiply each value vector by the softmax score to focus on semantically related words and weaken irrelevant words, and sum the weighted values: To speed up processing, the calculation uses matrix form: (2.4) The output of the Self-Attention layer is connected to a parameter matrix W, which is then linearly projected by the linear layer: A=concat(Attention i (Q i ,K i ,V i ))W Use the Mult-headedAttention multi-head attention mechanism to obtain the matrix Z that integrates all attention head information, and then output the vector matrix Z of this layer to the feedforward neural network layer; (2.5) In the feedforward neural network of the encoder, the encoder first converts the input vector matrix Z into a set of attention vectors, a combination of key vectors k and value vectors v, and inputs them into the encoder decoder for use; (2.6) At each decoding stage in the Decoder, one element is output from the output sequence each time, and the process is repeated until a special symbol appears to complete the output of the decoder; each output is then fed back to the bottom decoder, and the positional encoding embedding is added to the decoder input to indicate the position of the word; the final output is a floating point vector, which is input to the Linear layer; (2.7) In the Linear layer, the vector produced by the decoder stack is projected into a larger logits vector. Logits sets a specific cell width, and each cell corresponds to the score of a unique word. The scores are passed to the Softmax layer. In the Softmax layer, the scores are converted to probabilities, all positive and summing to 1.

0. Then the cell with the highest probability is selected and the word associated with it is generated as the output for that time step. The step (3) comprises the following steps: (3.1) Use the Java pre-trained model trained in step (2), input the labeled smart contract dataset, and access the pre-trained Encoder encoder parameters to obtain Java code vulnerability knowledge; (3.2) Fine-tune the model during the Solidity smart contract vulnerability detection process to learn and adapt the code semantics and vulnerability knowledge from the Java pre-trained model; reuse the pre-trained encoder to learn the representation of the smart contract code, and the decoder receives the results of smart contract vulnerability detection from the pre-trained encoder to achieve downstream detection tasks; (3.3) The detected results are compared with the vulnerability labels of the smart contract samples to ensure the correctness of the model.

2. The method for detecting smart contract vulnerabilities based on transfer learning according to claim 1, characterized in that: The step (1) comprises the following steps: (1.1) Obtain Java source code from the open source community and obtain the Solidity smart contract source code with tags from the Etherscan platform; (1.2) Use a programming language vulnerability detection tool to detect the collected Java source code and mark it according to the detection results. The Java source code with vulnerabilities shown by the detection tool is marked as "1", otherwise it is marked as "0"; (1.3) Manually audit Java samples marked as having vulnerabilities to ensure the accuracy of sample marking; (1.4) Convert the Java source code and Solidity smart contract source code into the sequence form of "<natural language text>, <programming language code>" respectively, and use them as Java dataset and smart contract dataset for machine learning.

3. The method for detecting smart contract vulnerabilities based on transfer learning according to claim 1, characterized in that: The process of obtaining the matrix Z described in step (2.4) is as follows: Perform 8 different weight matrix calculations on each attention head to obtain 8 matrices. Then concatenate all the attention heads together, compress the 8 matrices into one matrix, and multiply them by the additional weight matrix W. 0 :