Tree-lstm and bi-lstm based smart contract vulnerability detection method and system
Patent Information
- Application Number
- CN202310899637.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2023-07-21
- Publication Date
- 2026-09-18
- Estimated Expiration
- 2043-07-21
AI Technical Summary
现有的使用抽象语法树的智能合约漏洞检测方法大都使用遍历的方法将抽象语法树表示为token序列,破坏了原有的结构,无法完整的提取程序的语法特征
[0045] The grammatical and semantic feature extraction modules are used to encode grammatical and semantic information into vectors, respectively, and then use the Tree-LSTM model and BiLSTM+Attention model to extract the grammatical feature vector and semantic feature vector, respectively.
Smart Images

Figure CN117195220B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of smart contract security and involves deep learning technology, specifically a smart contract vulnerability detection method and system based on Tree-LSTM and BiLSTM. Background Technology
[0002] Blockchain is a new distributed computing and storage paradigm that integrates multiple existing technologies, characterized by transparency, immutability, traceability, and decentralization. A smart contract is a piece of code that can run automatically on a blockchain platform, used to describe and automatically execute a contract. Smart contracts can be enforced without third-party supervision, enabling secure and reliable transactions in untrusted environments. Ethereum is currently the most influential open-source blockchain platform, and also the blockchain platform with the most smart contracts, the most types of vulnerabilities, and the greatest losses caused by vulnerabilities. The primary programming language for writing smart contracts on Ethereum is Solidity. Solidity is a high-level language for contract development, drawing inspiration from JavaScript and Python, and is well-suited for developing public decentralized applications (DApps) running on Ethereum, such as voting, crowdfunding, auctions, and multi-signature wallets. Ethereum DApps account for 82% of Ethereum's total value creation, with 80% of these belonging to high-risk categories such as gambling and games.
[0003] Because of the inherent financial attributes of smart contracts, which can bring huge profits to attackers, attacks exploiting their vulnerabilities have proliferated in recent years. Compared to traditional applications, smart contracts, as decentralized applications running on the blockchain, have unique security vulnerabilities due to their lifecycle and the characteristics of their development languages. Furthermore, the transparency of the blockchain makes it easier for ordinary users to obtain the bytecode of smart contracts running on the blockchain, providing opportunities for hackers. Moreover, transactions between users lack third-party protection, allowing hackers to launch attacks on contracts at any time. The immutability of the blockchain also means that smart contracts cannot be patched like ordinary programs to fix vulnerabilities. This makes vulnerability detection for smart contracts exceptionally important.
[0004] The complexity and prevalence of vulnerabilities in smart contracts mean that relying solely on manual methods to detect them is both extremely costly and insufficient to guarantee security. Research into smart contract vulnerability detection aims to automate the detection of vulnerabilities in smart contracts, thereby ensuring their security.
[0005] Currently, methods for detecting smart contract vulnerabilities can be categorized into traditional methods and deep learning-based methods. Traditional methods mainly include static analysis, dynamic analysis, fuzzing, and formal verification. Static analysis analyzes code without executing the program. Dynamic analysis analyzes code while the program is running. Static analysis relies heavily on expert-defined rules, making it prone to false positives and false negatives. Dynamic analysis incurs significant performance overhead and is difficult to reproduce. Fuzzing generates random or semi-random input data to test the program and discover vulnerabilities; however, the generated data is difficult to cover all code paths and requires substantial computational resources. Formal verification detects vulnerabilities based on mathematical logic reasoning, requiring specialized mathematical knowledge and lacking support for complex language features, thus limiting its widespread application.
[0006] Compared to traditional smart contract vulnerability detection methods, deep learning-based smart contract vulnerability detection boasts higher accuracy and completeness. However, most existing machine learning methods directly apply natural language processing techniques to smart contract vulnerability detection. The difference between programming languages and natural languages lies in their strict grammatical rules and distinct structural features; treating programming languages as natural language text is unreasonable. Abstract syntax trees (ASTs) are tree-like representations of the abstract grammatical structure of source code, with each node representing a grammatical structure within the source code. They are suitable for representing the grammatical and structural features of a program. Existing smart contract vulnerability detection methods using ASTs mostly employ traversal methods to represent the AST as a token sequence, disrupting the original structure and failing to fully extract the program's grammatical features. Summary of the Invention
[0007] Purpose of the invention: To overcome the shortcomings of existing technologies, this invention provides a smart contract vulnerability detection method and system based on Tree-LSTM and BiLSTM. By using the Tree-LSTM model to extract syntactic features from the AST, and the BiLSTM+Attention model to extract semantic features from the source code text, the features are fused. Then, a classifier network is used for vulnerability detection, thereby achieving automated detection of vulnerabilities in the source code of smart contracts and ensuring the security of smart contracts.
[0008] Technical Solution: To achieve the above objectives, this invention provides a smart contract vulnerability detection method based on Tree-LSTM and BiLSTM, comprising the following steps:
[0009] S1: Collect data to form a smart contract dataset and perform data processing;
[0010] S2: Use a syntax parser to parse the smart contract source code after data processing in step S1 to obtain the AST, and then process the AST.
[0011] S3: Perform program slicing and normalization on the smart contract source code text after data processing in step S1, and perform text segmentation to train and save the word embedding model word2vec.
[0012] S4: Use the constructed Tree-LSTM model to extract features from the AST processed in step S2 to obtain the syntax feature vector;
[0013] The constructed BiLSTM+Attention model is used to extract features from the processed program slice text in step S3 to obtain semantic feature vectors.
[0014] S5: The syntactic feature vector and semantic feature vector are fused together, and a classifier network is used to detect vulnerabilities in the source code of smart contracts based on the fused feature vector.
[0015] Furthermore, step S1 specifically includes the following steps:
[0016] A1: Use web crawlers to collect smart contract source code from Github and Estherscan;
[0017] A2: Use tools such as Slither to mark the contract source code and perform manual inspection;
[0018] A3: Remove comments and non-ASCII characters from the source code;
[0019] A4: Based on the characteristics of the vulnerability, find the key statements and key methods containing the key statements in the program. Then find all methods that directly call or nest call the key methods and form a method set with the key methods. Find all the variables that the methods depend on and indirectly depend on in the method set, and use them as a variable set.
[0020] A5: Extract the smart contract source code based on the method set and variable set obtained in step A4;
[0021] A6: Use the difflib library that comes with Python to perform a text similarity check on the program slice text obtained in step A5, and discard program slices with too high similarity.
[0022] Furthermore, step S2 specifically includes the following steps:
[0023] B1: Use the ANTLR parser to parse the program slice obtained in step A6 to obtain the parsing class of the abstract syntax tree;
[0024] B2: Perform a depth-first traversal of each node in the abstract syntax tree, number each node, and use only the node type to represent the node in order to better extract syntax information. The abstract syntax tree is stored in the form of an adjacency list.
[0025] B3: Based on the frequency of words in the adjacency list, create a dictionary that stores words and their corresponding indexes;
[0026] B4: Starting from the leaf nodes, iterate through the calculation order of each node, using an array to store the calculation order. Traverse the adjacency list, set all leaf nodes as calculated nodes, and set the calculation order to 0. Traverse the adjacency list again, set all nodes whose child nodes are calculated nodes as calculated nodes, and set the calculation order to 1. Iterate until all nodes in the adjacency list have been calculated. Finally, store the array and the adjacency list together.
[0027] Furthermore, step S3 specifically includes the following steps:
[0028] C1: Contract normalization, replacing function names in program slices with FUN{#}, where # represents a number, and replacing variable names in program slices with VAR{#}, where # represents a number;
[0029] C2: Perform word segmentation on program slices;
[0030] C3: Use all the words in the program slice as training corpus to train the word embedding model word2vec, and save the trained word embedding model.
[0031] Furthermore, in step S4, before feature extraction, the semantic information representation obtained in step S3, the syntactic information representation obtained in step S2, and the labels are combined to form a dataset. Since the number of contracts with vulnerabilities in the dataset is far less than the number of contracts without vulnerabilities, the number of contracts with vulnerabilities and the number of contracts without vulnerabilities are counted separately, and a weighted random sampling method is used to balance the smart contract dataset.
[0032] Furthermore, the process of obtaining the grammatical feature vector in step S4 is as follows: For the grammatical information representation, the dictionary created in step B3 and a randomly initialized embedding matrix M∈R are used. d×v The node type information is encoded into a vector, where v is the size of the vocabulary and d is the length of the output vector. Then, the Tree-LSTM model is used to extract grammatical features. The Tree-LSTM model will perform calculations according to the calculation order obtained in step B4 to finally obtain the grammatical feature vector.
[0033] The Tree-LSTM model used for grammatical feature extraction is Multi-way Tree-LSTM, which is an improvement on Child-sum Tree-LSTM. It uses BiLSTM to learn the relationship between child nodes instead of adding the feature vectors of child nodes, and can learn the order relationship between child nodes.
[0034] Furthermore, the process of obtaining the semantic feature vector in step S4 is as follows: using the word embedding model word2vec obtained in step C3 to encode each word in the code slice into a vector to obtain an embedding matrix, and then using the BiLSTM+Attention model to extract semantic features from the obtained embedding matrix to obtain a semantic feature vector.
[0035] Further, step S5 specifically includes:
[0036] D1: Concatenate the syntactic feature vector and the semantic feature vector to obtain the fused feature vector;
[0037] D2: The fused feature vector is used as the input to the classifier network, which predicts the probability p of a vulnerability. When p > 0.5, the smart contract is judged to have a vulnerability.
[0038] D3: Train the model multiple times using the training dataset, adjust and optimize the model parameters, and save the parameters of the model with the best performance.
[0039] The detection method of this invention can be summarized as follows: A large amount of smart contract source code is obtained from publicly available resources, the source code is marked, and the program is sliced according to the vulnerability type to remove code segments with high similarity. In the syntactic information extraction part, a syntax parser is used to parse the contract source code to obtain an AST. Through depth-first traversal of the AST, each node of the AST is represented using a node type value to obtain the index number and adjacency list representation of each node. The calculation order of each node is calculated and saved. In the semantic information extraction part, the method names and variable names in the program are replaced, and the word embedding model word2vec is trained. In the feature extraction part, the syntactic and semantic information are encoded into vectors, and then the Tree-LSTM model and BiLSTM+Attention model are used respectively to extract syntactic feature vectors and semantic feature vectors. In the vulnerability detection part, feature fusion is performed, and a classifier network is used for vulnerability detection.
[0040] This invention first collects and processes Ethereum smart contract datasets from publicly available online resources, then performs program slicing and filtering. Next, it extracts the syntactic and semantic features of the smart contracts from their source code. Specifically, this invention obtains syntactic information by analyzing the smart contract's Abstract Syntax Tree (AST), using a parser to parse the smart contract program slices and extract the AST node types to represent nodes. A Multi-way Tree-LSTM model is then used to extract the syntactic feature vectors of the smart contract without disrupting the AST's syntactic structure. Semantic features are obtained by analyzing the smart contract's source code text. Normalization and word segmentation are performed first, then a BiLSTM+Attention model is used to extract semantic feature vectors. Finally, the syntactic and semantic feature vectors are fused, and a classifier network is used to classify smart contracts into vulnerable and non-vulnerable contracts.
[0041] This invention also provides a smart contract vulnerability detection system based on Tree-LSTM and BiLSTM, comprising:
[0042] The data collection module is used to collect smart contract datasets from network resources, perform preliminary processing of the datasets, label the datasets, slice the program based on vulnerability information, and filter the program slices to remove duplicate program slices.
[0043] The syntax information representation and acquisition module is used to parse program slices to obtain an abstract syntax tree, traverse the abstract syntax tree to represent each node with a type value and obtain the node index, count the frequency of each word to obtain a vocabulary, and finally calculate and store the calculation order of each node.
[0044] The semantic information representation acquisition module is used to normalize program slicing, text segmentation, and train and save the word embedding model word2vec;
[0045] The grammatical and semantic feature extraction modules are used to encode grammatical and semantic information into vectors, respectively, and then use the Tree-LSTM model and BiLSTM+Attention model to extract the grammatical feature vector and semantic feature vector, respectively.
[0046] The vulnerability detection module is used to concatenate syntactic feature vectors and semantic feature vectors to obtain a fused feature vector, and then uses a classifier network to predict whether a smart contract has vulnerabilities.
[0047] Beneficial effects: Compared with the prior art, the present invention makes full use of the syntactic and semantic features of smart contract code. The Tree-LSTM model can directly extract the features of tree structure data. Therefore, it can extract the syntactic feature vector of smart contract without destroying the AST syntactic structure, and can automatically, quickly and accurately detect smart contract vulnerabilities. Attached Figure Description
[0048] Figure 1 This is a diagram illustrating the overall steps of the method of the present invention;
[0049] Figure 2 This is a flowchart of the method of the present invention;
[0050] Figure 3 This is a diagram of the Tree-LSTM structure. Detailed Implementation
[0051] The present invention will be further illustrated below with reference to the accompanying drawings and specific embodiments. It should be understood that these embodiments are for illustrative purposes only and are not intended to limit the scope of the invention. After reading this invention, any modifications of the invention in various equivalent forms by those skilled in the art will fall within the scope defined by the appended claims.
[0052] like Figure 1 and Figure 2 As shown, this invention provides a smart contract vulnerability detection method based on Tree-LSTM and BiLSTM, comprising the following steps:
[0053] Step 1: Collect smart contract datasets from online resources, label the datasets, slice the code based on vulnerability information, perform preliminary data processing, and filter the code slices to remove duplicates.
[0054] Step 2: Parse program slices to obtain abstract syntax tree, traverse the abstract syntax tree to represent each node with a type value and obtain the node index, count the frequency of each word to obtain the vocabulary, and finally calculate and store the calculation order of each node.
[0055] Step 3: Perform program slicing and normalization on the smart contract source code text, perform text segmentation, train and save the word embedding model word2vec;
[0056] Step 4: Perform word embedding, encode syntactic and semantic information into vectors, and then use Tree-LSTM and BiLSTM+Attention models respectively to extract syntactic and semantic feature vectors.
[0057] Step 5: Concatenate the syntactic feature vector and semantic feature vector obtained in Step 4 to obtain the fused feature vector. Use a classifier network based on the fused feature vector to predict whether the smart contract has vulnerabilities.
[0058] Step 1 specifically includes the following steps:
[0059] Step 11: Use a web crawler to call the GitHub API, search for repositories using the condition 'language:solidity stars:>50', and then crawl the files ending in .sol, which are the contract source code. For EtherScan, request the publicly available smart contract source code webpage, and then use regular expressions and XPath to parse the webpage to obtain the source code;
[0060] Step 12: Use tools such as Slither to perform vulnerability detection on the contract source code. Manually check and mark contracts that Slither identifies as having vulnerabilities. If a contract cannot be compiled, discard it.
[0061] Step 13: Use regular expressions to remove comments and non-ASCII characters from the smart contract, obtaining the smart contract vulnerability dataset CONTRACTS = {CONTRACT1,...,CONTRACT}. t}, where t is the number of contracts;
[0062] Step 14: For a smart contract CONTRACTS in the dataset CONTRACTS k Based on the characteristics of the vulnerability, identify the critical statements in the program (such as statements containing call-statements) and the critical methods containing those statements (FUNC). k Then, based on the key method FUNC k Find all methods that directly or nestedly call key methods, including the method name and parameter list, and the key method FUNC. k Form a method set FUNS k ={FUNC k FUN 1k ,...,FUN nk}, where n is the call or nested call to FUNC k The number of methods. If there are multiple key methods, take the union. Find all variables that methods depend on and indirectly depend on in the method set, and compile them into a variable set VARS. k ={VAR 1k VAR mk}, where m is the number of variables.
[0063] Step 15: For a smart contract CONTRACTS in the dataset CONTRACTS k Traversing smart contracts CONTRACT k For each line of the source code, according to the method set FUNC obtained in step 14 k and variable set VARS kExtract each statement and variable declaration from the method to generate the smart contract. k CODESEG (a collection of program slices) k ={LINE 1K ,...,LINE qK}, where q is the number of statements. The set of program slices CODESEGS = {CODESEG1, ..., CODESEG} is obtained from CONTRACTS. t}, where t is the number of slices;
[0064] Step 16: Use Python's built-in difflib library to perform text similarity checks on the code slice set CODESEGS obtained in Step 15. If the similarity of code slices from multiple smart contracts is higher than 0.95, only one copy is retained, resulting in the code slice dataset CSDS = {CSD1,...,CSD...}. r}, where r is the number of filtered program slices.
[0065] Step 2 specifically includes the following steps:
[0066] Step 21: For a slice of the dataset CSDS, CSD k The ANTLR parser is used to parse the data to obtain the Abstract Syntax Tree (AST) class. k ;
[0067] Step 22: For an Abstract Syntax Tree (AST) parsing class k Depth-first traversal of AST k For each node, extract its information and assign it a number according to the traversal order. A node contains information such as type, value, child nodes, and parent node. To better extract syntactic information, only the node's type is used to represent it, and the parent-child relationships of the nodes in the abstract syntax tree are stored in the form of an adjacency list to obtain the AL. k =[NODE] 1k ,...,NODE sk ], where s is the number of nodes, and the o-th node is NODE. ok ={'type':type ok ,'child':[index ok1 ,...,index oku ]}, where u is the number of child nodes, index is the node number, and type ok Given nodes, the final result is an abstract syntax tree representation set ALS = {AL1,...,AL...} of all program slices. r}, where r is the number of program slices;
[0068] Step 23: Since each type is a word, no word segmentation is needed. Based on the occurrence frequency of types in the ALS, create a dictionary that stores words and their corresponding indexes.
[0069] Step 24: For any abstract syntax tree, the adjacency list AL k Iterate through the calculations for each node, starting from the leaf nodes, using an array ORDER. k Store the calculation order, traverse the adjacency list, set all leaf nodes as calculated nodes, and assign a calculation order of 0. Traverse the adjacency list again, setting all nodes whose child nodes are calculated nodes as calculated nodes and assigning a calculation order of 1. Repeat this process until all nodes in the adjacency list have been calculated, resulting in the array ORDER. k =[i 1k ,...,i sk ], where s is the number of nodes. Different i may have the same value because multiple nodes may have the same computation order. This gives us the set of node computation orders for all abstract syntax trees: ORDERS = {ORDER1, ..., ORDER...} r}, where r is the number of program slices.
[0070] Step 3 specifically includes the following steps:
[0071] Step 31: Process the program slice dataset CSDS, replace the user-defined function names with the regular FUN{#}, where # is a number, and replace the user-defined variable names in the program slice with VAR{#}, where # represents a number;
[0072] Step 32: Perform word segmentation on the processed program slices to obtain the set CSDT = {CSDT1, ..., CSDT}. r}, where r is the number of program slices;
[0073] Step 33: Use the dataset as corpus, use all words as training corpus, train the word embedding model word2vec, and save the trained word embedding model.
[0074] Step 4 specifically includes the following steps:
[0075] Step 41: Combine semantic information representation, syntactic information representation, and labels to form a dataset DATASETS = {{AL1,ORDER1,CSDT1,label1},...,{AL r ORDER r CSDT r ,label r}}, where r is the number of program slices. Since the number of contracts with vulnerabilities in the dataset is far less than the number of contracts without vulnerabilities, let num1 be the number of contracts with vulnerabilities in the dataset DATASETS and num2 be the number of contracts without vulnerabilities. Then, let the weight of the contracts with vulnerabilities be set to . The weight of a contract without vulnerabilities is set to... Each training iteration involves random sampling based on weights;
[0076] Step 42: For the grammatical information representation, use the dictionary created in step 23 and a randomly initialized embedding matrix M∈R d×v Encode the type value of the node into a vector, where v is the size of the vocabulary and d is the length of the output vector;
[0077] Step 43: Apply the Multi-way Tree-LSTM model to the AL k Syntactic feature extraction is performed to obtain syntactic feature vectors, which are then referred to... Figure 3 The Multi-Way Tree-LSTM model is an improvement on the Child-sum Tree-LSTM model. Like the Child-sum Tree-LSTM model, it can handle any number of child nodes. Each Multi-Way Tree-LSTM unit takes the state vectors of multiple child nodes and the word vector representation of the parent node as input, and outputs the state vector of the parent node. Therefore, the Multi-Way Tree-LSTM model can handle tree-structured data. Unlike the Child-sum Tree-LSTM, the Multi-Way Tree-LSTM model takes the hidden states of the child node sequence as input and uses BiLSTM to learn the relationships between child nodes, rather than simply adding the hidden states of the child nodes. The Child-sum Tree-LSTM's method of handling child nodes ignores the order relationship between them. BiLSTM is often used to learn long-term dependencies in sequence data and can learn the order relationship between child nodes, which also allows the Multi-Way Tree-LSTM model to handle any number of child nodes. To accelerate computation, the Tree-LSTM model performs calculations according to the order obtained in step 24, starting from the bottom-level nodes and ending with the hidden layer of the root node as the grammatical feature vector. For example, the calculation order array is ORDER. K When calculating, the order of operations starts from 1 and increases to max(ORDER). k Each time, all ORDERs are computed in parallel. K [index] = the node of order, where index is the node number;
[0078] Step 44: Use the word embedding model word2vec obtained in step 33 to embed the CSDT. k Each word in the matrix is encoded into a vector to obtain an embedding matrix. Then, the BiLSTM+Attention model is used to extract semantic features from the obtained embedding matrix to obtain a semantic feature vector.
[0079] Step 5 specifically includes the following steps:
[0080] Step 51: Feature fusion, concatenating the syntactic feature vector and the semantic feature vector to obtain the fused feature vector;
[0081] Step 52: Use a multilayer perceptron as a classifier, take the fused feature vector as the input of the classifier, and then use the softMax function to predict the probability p of having a vulnerability. When p>0.5, the smart contract is judged to have a vulnerability.
[0082] Step 53: Train the model multiple times, adjust and optimize the model parameters. Perform a comprehensive evaluation of the model using accuracy, precision, recall, and F1 score, and save the parameters of the best-performing model.
[0083] This invention also provides a smart contract vulnerability detection system based on Tree-LSTM and BiLSTM, comprising:
[0084] The data collection module is used to collect smart contract datasets from network resources, perform preliminary processing of the datasets, label the datasets, slice the program based on vulnerability information, and filter the program slices to remove duplicate program slices.
[0085] The syntax information representation and acquisition module is used to parse program slices to obtain an abstract syntax tree, traverse the abstract syntax tree to represent each node with a type value and obtain the node index, count the frequency of each word to obtain a vocabulary, and finally calculate and store the calculation order of each node.
[0086] The semantic information representation acquisition module is used to normalize program slicing, text segmentation, and train and save the word embedding model word2vec;
[0087] The grammatical and semantic feature extraction modules are used to encode grammatical and semantic information into vectors, respectively, and then use the Tree-LSTM model and BiLSTM+Attention model to extract the grammatical feature vector and semantic feature vector, respectively.
[0088] The vulnerability detection module is used to concatenate syntactic feature vectors and semantic feature vectors to obtain a fused feature vector, and then uses a classifier network to predict whether a smart contract has vulnerabilities.
[0089] Based on the above scheme, the following experiment was conducted to verify the effectiveness of the present invention:
[0090] Using the data collection module of this invention, a reentrancy vulnerability dataset containing 3000 smart contracts was obtained as the training dataset, of which 256 contracts contained reentrancy vulnerabilities. The test dataset contained 100 smart contracts, 30 of which contained reentrancy vulnerabilities. After training, the model was comprehensively evaluated on this test dataset using accuracy, precision, recall, and F1 score. The results are as follows:
[0091] Table 1 Experimental Results
[0092]
[0093] Comparative experiments show that the Tree-LSTM model used in this invention can effectively extract the syntactic features of smart contracts. Compared with the BiLSTM and BiLSTM+Attention models, it significantly improves recall, effectively solves the problem of high false positive rate, and enhances the practical value of vulnerability detection models. Furthermore, the method used in this invention achieves the highest accuracy, precision, and F1 score among all models, proving its effectiveness and ability to extract syntactic and semantic features from smart contracts.
[0094] This embodiment also provides a computer storage medium storing a computer program that, when executed by a processor, can implement the methods described above. The computer-readable medium can be considered tangible and non-transitory. Non-limiting examples of non-transitory tangible computer-readable media include non-volatile memory circuitry (e.g., flash memory circuitry, erasable programmable read-only memory circuitry, or masked read-only memory circuitry), volatile memory circuitry (e.g., static random access memory circuitry or dynamic random access memory circuitry), magnetic storage media (e.g., analog or digital magnetic tape or hard disk drive), and optical storage media (e.g., CD, DVD, or Blu-ray disc). The computer program includes processor-executable instructions stored on at least one non-transitory tangible computer-readable medium. The computer program may also include or depend on stored data. The computer program may include a basic input / output system (BIOS) for interacting with the hardware of a dedicated computer, device drivers for interacting with specific devices of the dedicated computer, one or more operating systems, user applications, background services, background applications, etc.
[0095] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-usable storage media (including but not limited to disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0096] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0097] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0098] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
Claims
1. A smart contract vulnerability detection method based on Tree-LSTM and BiLSTM, characterized in that, Includes the following steps: S1: Collect data to form a smart contract dataset and perform data processing; S2: Use a syntax parser to parse the smart contract source code after data processing in step S1 to obtain the AST, and then process the AST. S3: Perform program slicing and normalization on the smart contract source code text after data processing in step S1, and perform text segmentation to train and save the word embedding model word2vec. S4: Use the constructed Tree-LSTM model to extract features from the AST processed in step S2 to obtain the syntax feature vector; The constructed BiLSTM+Attention model is used to extract features from the program slices processed in step S3 to obtain semantic feature vectors. S5: The syntactic feature vector and semantic feature vector are fused, and a classifier network is used to detect vulnerabilities in the source code of smart contracts based on the fused feature vector. Step S1 specifically includes the following steps: A1: Use web crawlers to collect smart contract source code from Github and Estherscan; A2: Mark the contract source code and perform manual inspection; A3: Remove comments and non-ASCII characters from the source code; A4: Based on the characteristics of the vulnerability, find the key statements and key methods containing the key statements in the program. Then find all methods that directly call or nest call the key methods and form a method set with the key methods. Find all the variables that the methods depend on and indirectly depend on in the method set, and use them as a variable set. A5: Extract the smart contract source code based on the method set and variable set obtained in step A4; A6: Use the difflib library that comes with Python to perform text similarity checks on the program slices obtained in step A5, and discard program slices with too high similarity. Step S2 specifically includes the following steps: B1: Use the ANTLR parser to parse the program slice obtained in step A6 to obtain the parsing class of the abstract syntax tree; B2: Depth-first traverse each node of the abstract syntax tree, number each node, represent nodes using only the node type, and store the abstract syntax tree as an adjacency list; B3: Based on the frequency of words in the adjacency list, create a dictionary that stores words and their corresponding indexes; B4: Starting from the leaf nodes, iterate through the calculation order of each node, use an array to store the calculation order, traverse the adjacency list and set all leaf nodes as calculated nodes, and set the calculation order to 0. Traverse the adjacency list again and set all nodes whose child nodes are calculated nodes as calculated nodes, and set the calculation order to 1. Iterate until all nodes in the adjacency list have been calculated. Finally, store the array and the adjacency list together. The process of obtaining the syntactic feature vector in step S4 is as follows: For the syntactic information representation, the dictionary created in step B3 and a randomly initialized embedding matrix are used. The type information of the nodes is encoded into a vector, where It refers to the size of the vocabulary list. It is the length of the output vector. Then, the Tree-LSTM model is used to extract grammatical features. The Tree-LSTM model will perform calculations according to the calculation order obtained in step B4 to finally obtain the grammatical feature vector.
2. The smart contract vulnerability detection method based on Tree-LSTM and BiLSTM according to claim 1, characterized in that, Step S3 specifically includes the following steps: C1: Contract normalization, replacing function names in program slices with FUN{#}, where # represents a number, and replacing variable names in program slices with VAR{#}, where # represents a number; C2: Perform word segmentation on program slices; C3: Use all the words in the program slice as training corpus to train the word embedding model word2vec, and save the trained word embedding model.
3. The smart contract vulnerability detection method based on Tree-LSTM and BiLSTM according to claim 1, characterized in that, In step S4, before feature extraction, the semantic information representation obtained in step S3, the syntactic information representation obtained in step S2, and the labels are combined to form a dataset. The number of contracts with vulnerabilities and the number of contracts without vulnerabilities are counted respectively, and the smart contract dataset is balanced using a weighted random sampling method.
4. The smart contract vulnerability detection method based on Tree-LSTM and BiLSTM according to claim 1, characterized in that, The Tree-LSTM model is a Multi-Way Tree-LSTM model. Each Multi-Way Tree-LSTM unit takes the state vectors of multiple child nodes and the word vector representation of the parent node as input to obtain the state vector of the parent node as output. The Multi-Way Tree-LSTM model takes the hidden state of the child node sequence as input and uses BiLSTM to learn the relationship between the child nodes.
5. The smart contract vulnerability detection method based on Tree-LSTM and BiLSTM according to claim 3, characterized in that, The process of obtaining the semantic feature vector in step S4 is as follows: using the word embedding model word2vec obtained in step C3, each word in the code slice is encoded into a vector to obtain the embedding matrix. BiLSTM processes all words from two directions to obtain the context information representation vector of each word. Then, the Attention mechanism is used to calculate the importance of each word to the code slice to obtain the attention weight. Finally, the weighted sum is obtained to obtain the semantic feature vector.
6. A smart contract vulnerability detection system based on Tree-LSTM and BiLSTM according to claim 1, characterized in that, include: The data collection module is used to collect smart contract datasets from network resources, perform preliminary processing of the datasets, label the datasets, slice the program based on vulnerability information, and filter the program slices to remove duplicate program slices. The syntax information representation and acquisition module is used to parse program slices to obtain an abstract syntax tree, traverse the abstract syntax tree to represent each node with a type value and obtain the node index, count the frequency of each word to obtain a vocabulary, and finally calculate and store the calculation order of each node. The semantic information representation acquisition module is used to normalize program slicing, text segmentation, and train and save the word embedding model word2vec; The grammatical and semantic feature extraction modules are used to encode grammatical and semantic information into vectors, respectively, and then use the Tree-LSTM model and BiLSTM+Attention model to extract the grammatical feature vector and semantic feature vector, respectively. The vulnerability detection module is used to concatenate syntactic feature vectors and semantic feature vectors to obtain a fused feature vector, and then uses a classifier network to predict whether a smart contract has vulnerabilities.
Citation Information
Patent Citations
Ethereum intelligent contract problem detection and prevention method and device
CN111177730A
Intelligent contract multi-vulnerability detection method and system based on source code graph representation learning
CN113360915A