A vulnerability detection method for smart contracts based on low-dimensional bytecode features

By constructing an opcode sequence control flow graph and adjacency matrix, low-dimensional features are extracted for smart contract vulnerability detection, solving the problems of low efficiency and high feature dimensionality in existing methods, and achieving efficient and interpretable vulnerability detection.

CN115758388BActive Publication Date: 2026-07-21ZHEJIANG UNIV +1
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
ZHEJIANG UNIV
Filing Date
2022-11-30
Publication Date
2026-07-21

Smart Images

  • Figure CN115758388B_ABST
    Figure CN115758388B_ABST
Patent Text Reader

Abstract

The application provides a vulnerability detection method of a smart contract based on a low-dimensional bytecode feature, and comprises the following steps: constructing an opcode sequence control flow graph through an Ethereum smart contract bytecode; recording each basic block in the opcode sequence control flow graph and numbering, then traversing the edges associated with each basic block to establish an adjacency matrix; based on the adjacency matrix, obtaining the features of the opcode sequence control flow graph, which are the number of edges, the number of nodes, the maximum out-degree and the maximum in-degree, obtaining the vulnerability category and the opcode category that may be related to the vulnerability category, and taking the proportion of the total number of opcodes occupied by each type of opcode in the opcode sequence as a feature; normalizing the features, then taking the features as input and the vulnerability category as output to train a machine learning model; and using the trained machine learning model to detect vulnerabilities. The application effectively improves the detection efficiency of the machine learning model and the analysis and interpretation ability of the problem contract.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of smart contract vulnerability detection technology, and specifically relates to a method for detecting vulnerabilities in smart contracts based on low-dimensional bytecode features. Background Technology

[0002] Smart contracts, as program code running on the blockchain, can automatically and correctly execute and update their state in a zero-trust environment when predefined conditions are met. They offer advantages such as decentralization, immutability, and transparency. With the introduction of the Turing-complete smart contract programming language Solidity and the execution engine EVM into the Ethereum blockchain, blockchain applications have expanded from simple cryptocurrency transactions to complex scenarios such as edge intelligence, federated learning, and group learning, enabling secure data resource sharing and trusted collaborative computing tasks. Smart contracts manage and manipulate sensitive information such as digital assets, cryptographic tokens, and model parameters / gradients. Once deployed on-chain, the contract code can be accessed and analyzed by blockchain nodes. Vulnerable or erroneous contract code is difficult to modify or update, and erroneous transactions, once authenticated by consensus, are irreversible, leading to serious security issues such as digital asset loss and sensitive data leakage. Therefore, efficient and rapid security testing of large-scale smart contracts is crucial to improving the security of on-chain contracts and reducing security risks and vulnerabilities.

[0003] Existing smart contract vulnerability detection methods can be categorized into traditional methods and machine learning methods. Traditional methods include formal verification, symbolic execution, fuzzing, and intermediate representation methods. In traditional methods, formal verification uses mathematical methods to verify the absence of vulnerabilities in the system. Symbolic execution traverses all executable paths in the program to detect vulnerabilities. Fuzzing inputs automatically or semi-automatically generated random data into the system and determines vulnerabilities based on the system's response. Intermediate representation methods typically convert smart contract source code or bytecode into a unique intermediate representation to detect specific types of vulnerabilities. Machine learning methods include graph neural network methods, random forest algorithms, gradient boosting algorithms, etc. Graph neural network-based machine learning methods construct flowcharts from program source code to detect vulnerabilities. Other machine learning methods directly analyze opcode sequence features to detect vulnerabilities.

[0004] Hildenbrandt et al. proposed KEVM based on formal verification and provided an executable formal specification for the EVM programming language using the K framework. Luu et al. proposed Oyente based on symbolic execution, which mainly uses the contract control flow graph to traverse the smart contract execution path to detect vulnerabilities. Jiang et al. proposed Contractfuzzer based on fuzzing, which detects vulnerabilities by setting test cases and analyzing smart contract behavior logs. Albert et al. proposed Ethir based on intermediate representation, which analyzes the security properties of bytecode by converting Oyente's control flow graph into a rule-based representation (RBR). Tann et al. proposed SafeSC, which uses a Long Short-Term Memory (LSTM) model to analyze Ethereum opcode sequences to detect vulnerabilities, including contracts with indefinite asset freezes, contracts that easily leak assets to unknown accounts, and contracts that can be arbitrarily destroyed. Qin proposed ReChecker, which converts smart contract source code into contract fragments, detects reentrant vulnerabilities through bidirectional Long Short-Term Memory (BLSTM) and attention mechanisms, and utilizes captured semantic and control flow information. Zhuang proposed DR-GCN and TMP. DR-GCN transforms smart contract source code into a contract graph and uses graph convolutional neural networks to build a vulnerability detection model. Based on DR-GCN, TMP considers the temporal information in the contract graph and uses temporal graph neural networks to build a vulnerability detection model. Wang proposed ContractWard, which treats smart contract opcodes as text sequences and uses N-gram segmentation to extract tuples from the smart contract opcodes, constructing thousands of dimensions of data features for training five machine learning models to achieve contract vulnerability detection.

[0005] The existing technology has the following drawbacks: (1) Traditional methods have too low detection efficiency. Traditional vulnerability detection methods mainly include formal verification, symbolic execution, and fuzzing. They primarily focus on analyzing the vulnerability type or cause of the problem in the discovered problematic contracts. However, since most traditional methods require traversing the code execution path, they suffer from low efficiency, symbolic execution path explosion, large computational load, and large search space in large-scale test sample sets. As a result, the detection time is long and the detection efficiency is low, making it unable to meet the needs of rapid analysis of large-scale smart contracts.

[0006] (2) Machine learning methods have too many feature dimensions and lack interpretability. Current machine learning methods primarily rely on the bytecode or source code sequences of Ethereum smart contracts as model input. They treat the contract source code or bytecode sequences as text sequences for feature analysis, using N-gram segmentation to extract sequence features for model training and vulnerability analysis. However, due to the long length of Ethereum smart contract bytecode or source code sequences, the model features are excessively dimensional, resulting in little improvement in efficiency compared to traditional methods. Furthermore, because they simply extract text features directly from the Ethereum smart contract bytecode or source code sequences, the features lack interpretability, leading to a corresponding lack of interpretability in the model results. Summary of the Invention

[0007] This invention addresses the technical problems existing in the prior art by providing a vulnerability detection method for smart contracts based on low-dimensional bytecode features. First, it improves the efficiency of vulnerability detection for large-scale smart contracts by reducing the feature dimension. Second, it enhances the interpretability of the detection model and detection results by combining it with the adjacency matrix features of the contract bytecode and feature contribution analysis, effectively improving the detection efficiency of the machine learning model and the analytical and interpretable capabilities of problematic contracts.

[0008] The technical solution adopted in this invention is: a vulnerability detection method for smart contracts based on low-dimensional bytecode features, comprising the following steps: Step 1: Construct an opcode sequence control flow graph using Ethereum smart contract bytecode; Step 2: Record and number each basic block in the control flow graph according to the opcode sequence, and then traverse the edges associated with each basic block to build an adjacency matrix; Step 3: Based on the adjacency matrix, obtain the features of the opcode sequence control flow graph, namely the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree; Obtain the vulnerability category and the opcode category that may be related to it, and use the proportion of each type of opcode in the total number of opcodes in the opcode sequence as a feature; Step 4: Normalize the features from Step 3, and then use them as input and vulnerability categories as output to train the machine learning model; Step 5: Use the trained machine learning model to perform vulnerability detection.

[0009] Furthermore, in step 1, the Ethereum smart contract bytecode contains runtime code and metadata. The runtime code is separated from the Ethereum smart contract bytecode, and the bytecode of the runtime code is converted into opcodes to obtain an opcode sequence. The bytecode of the runtime code is converted into opcodes according to the bytecode-opcode conversion rules defined in the Ethereum blockchain. An opcode sequence control flow graph is constructed based on the opcode sequence, where the basic block of the opcode sequence control flow graph is an opcode sequence between a jump address and the next jump instruction, and the edges of the opcode sequence control flow graph are the jump relationships between jump instructions and jump destination addresses.

[0010] Furthermore, in step 1, the number of each type of opcode in the opcode sequence is counted and the proportion of each type of opcode is calculated.

[0011] Furthermore, in step 2, if the element in the i-th row and j-th column of the adjacency matrix is ​​1, it indicates that there is an edge connecting the i-th basic block and the j-th basic block, and the direction of the edge is from the i-th basic block to the j-th basic block; if the element is 0, there is no edge connecting the two basic blocks.

[0012] Furthermore, in step 3, the number of edges: in the adjacency matrix, the sum of the elements in the adjacency matrix represents the number of edges in the opcode sequence flow graph; Number of nodes: In the adjacency matrix, the number of rows or columns represents the number of nodes in the opcode sequence-based flow graph; Maximum out-degree: In the adjacency matrix, the sum of the elements in the i-th row represents the out-degree of the i-th basic block; Maximum in-degree: In the adjacency matrix, the sum of the elements in the i-th column represents the maximum in-degree of the i-th basic block.

[0013] Furthermore, in step 4, the machine learning model is one of Xtreme Gradient Boosting, K-Nearest Neighbors, Logistic Regression, Decision Tree, Random Forest, NavieBayes, and Long Short-Term Memory.

[0014] Furthermore, the machine learning model is a Decision Tree.

[0015] Furthermore, in step 4, the features are normalized: the maximum and minimum values ​​of each feature dimension in the dataset are found, and the data of each feature dimension is mapped to decimals between 0 and 1 according to the proportion. Then, these decimals are spread out to integers within 1000.

[0016] Further, step 6: Based on the trained machine learning model, use the feature_importances_ method, permutation_importance() method, or model.coef_ method to calculate the contribution of each feature for each type of vulnerability, and determine the features associated with each type of vulnerability.

[0017] Furthermore, in step 3, the vulnerability categories are integer positive overflow vulnerability, integer negative overflow vulnerability, stack call depth attack vulnerability, transaction execution order dependency vulnerability, timestamp dependency vulnerability, and reentrancy vulnerability; the opcode categories are unary operation opcode, binary operation opcode, block information opcode, control flow opcode, environment opcode, system opcode, stack opcode, and invalid opcode. In step 6, the integer positive overflow vulnerability, integer negative overflow vulnerability, stack call depth attack vulnerability, transaction execution order dependency vulnerability, timestamp dependency vulnerability, and reentrancy vulnerability are all related to the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree. Furthermore, the integer positive overflow vulnerability is also related to the ratio of unary opcodes and the ratio of binary opcodes; the integer negative overflow vulnerability is also related to the ratio of unary opcodes and the ratio of binary opcodes; the stack call depth attack vulnerability is also related to the ratio of system opcodes and the ratio of stack opcodes; the transaction execution order dependency vulnerability is also related to the ratio of environment opcodes; the timestamp dependency vulnerability is also related to the ratio of block information opcodes; and the reentrancy vulnerability is also related to the ratio of control flow opcodes.

[0018] Compared with existing technologies, the beneficial effects of this invention are as follows: This invention constructs an adjacency matrix from Ethereum smart contract bytecode and extracts lower-dimensional scalable features for efficient large-scale smart contract vulnerability detection. The dimensionality of the features directly affects the efficiency of contract vulnerability detection. Compared with existing machine learning detection methods based directly on semantics or graph neural networks, the feature dimensionality proposed in this invention is reduced by hundreds of times, and the detection latency is improved by 25-650 times. While improving detection efficiency, feature normalization can support the training and detection of more machine learning algorithms. The model interpretability is optimized by utilizing feature contribution and adjacency matrix features, and the detection performance of the features is not affected. The low-dimensional scalable features proposed in this invention are highly efficient and effective. Attached Figure Description

[0019] Figure 1 This is a flowchart of an embodiment of the present invention; Figure 2 This is a schematic diagram of the adjacency matrix according to an embodiment of the present invention. Detailed Implementation

[0020] To enable those skilled in the art to better understand the technical solution of the present invention, the present invention will be described in detail below with reference to the accompanying drawings and specific embodiments.

[0021] Embodiments of the present invention provide a method for detecting vulnerabilities in smart contracts based on low-dimensional bytecode features, such as... Figure 1 As shown, it includes the following steps: Step 1: Construct an opcode sequence control flow graph using Ethereum smart contract bytecode. The specific process is as follows: Step 1.1: Ethereum smart contract bytecode contains runtime code and metadata. The metadata is removed from the Ethereum smart contract bytecode to separate the runtime code. The metadata is then removed based on the analyzed metadata header. A portion of the metadata header is shown below: Solc0.4.17: 0xa1 0x65 'b' 'z' 'z' 'r' '0' 0x58 0x20 <32 bytes swarmhash> 0x00 0x29; Solc0.5.9: 0xa2 0x65 'b' 'z' 'z' 'r' '0' 0x58 0x20 <32 bytes swarmhash> 0x64 's' 'o' 'l' 'c' 0x43 <3 bytes version encoding> 0x00 0x32; Solc0.6.0: 0xa2 0x64 'I' 'p' 'f' 's' 0x58 0x22 <34 bytes IPFS hash>0x64 's' 'o' 'l' 'c' 0x43 <3 bytes version encoding> 0x00 0x32; ABIEncoderV2: 0xa2 0x65 'b' 'z' 'z' 'r' '0' 0x58 0x20 <32 bytes swarmhash> 0x6c 'e' 'x' 'p' 'e' 'r' 'I' 'm' 'e' 'n' 't' 'a' 'l' 0xf5 0x00 0x37.

[0022] Step 1.2: Convert the runtime code's bytecode to opcodes according to the bytecode-opcode conversion rules defined in the Ethereum blockchain. For example, bytecode 0x00 is converted to opcode STOP; bytecode 0x01 is converted to opcode ADD; bytecode 0x03 is converted to opcode SUB, and so on. For these non-PUSH opcodes, the conversion is performed directly according to the defined rules. For PUSH opcodes, such as PUSH1-PUSH32, the parameters of these opcodes are first obtained, and then the bytecode conversion is performed. After completing the bytecode and opcode conversion, the number of each type of opcode in the opcode sequence is counted, and the proportion of different types of opcodes is calculated.

[0023] Step 1.3: Construct an opcode sequence control flow graph based on the opcode sequence. The main graph information in the opcode sequence control flow graph consists of edges and basic blocks. A basic block is an opcode sequence from a jump address to the next jump instruction, and an edge is the jump relationship between a jump instruction and the jump destination address.

[0024] The opcode sequence is divided into multiple basic blocks based on the JUMP-type opcodes, and then edges are constructed between these basic blocks. Each basic block has the following parameters: Types: COMMON, DISPATCHER, FALLBACK, EXIT; Starting point: JUMPDEST; End point: JUMP, JUMP I, STOP, REVERT, RETURN, INVALID, SELFDESTRUCT; Identifier: The offset of the first opcode in the basic block.

[0025] The edges between basic blocks are mainly divided into the following four types: A JUMP followed by a PUSH opcode takes the offset of the JUMP's target address as its parameter, and the corresponding edge is added to the control flow graph. This means that if a basic block ends with a JUMP, an edge originating from that block will be created.

[0026] A JUMP I followed immediately by a PUSH opcode indicates a conditional jump. If the condition is true, the edge determined by the offset of the destination address pointed to by the parameter of the PUSH opcode is added to the control flow graph; if the condition is false, the edge determined by the next opcode after the JUMP I opcode is added to the control flow graph. This means that if a basic block ends with a JUMP I opcode, then two edges originating from that block will be generated.

[0027] A JUMP is not immediately followed by a PUSH: the destination address of the JUMP operation is calculated using a symbolic stack execution algorithm. The symbolic stack execution algorithm, for this type of JUMP, iterates through the preceding opcode sequence and constructs a symbolic execution stack for the opcodes within the basic block. For the elements in this symbolic execution stack, only opcodes from the PUSH, DUP, and SWAP series, as well as AND and POP opcodes, are considered. For each other opcode, the symbolic stack only POPs or PUSHs an "unknown" element, as these are not related to the jump address.

[0028] REVERT, SELFDESTRUCT, RETURN, INVALID, STOP: These opcodes signify an interruption of control flow, therefore basic blocks ending with these opcodes do not have subsequent basic blocks.

[0029] Step 2: Record and number each basic block in the control flow graph according to the opcode sequence, then traverse the edges associated with each basic block and build an adjacency matrix. For example... Figure 2 As shown, this graph represents an adjacency matrix composed of n basic blocks. If the element in the i-th row and j-th column of the adjacency matrix is ​​1, it indicates that there is an edge connecting the i-th and j-th basic blocks, and the direction of the edge is from the i-th basic block to the j-th basic block; if the element is 0, there is no edge connecting the two basic blocks. The elements have only two values: 0 or 1.

[0030] Step 3: Based on the adjacency matrix, obtain the features of the opcode sequence control flow graph, namely the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree. These four features are the graph information of the opcode sequence control flow graph, representing the complexity of the opcode sequence control flow graph, which is also the complexity of smart contract transitions.

[0031] Number of edges: In the adjacency matrix, the sum of the elements in the adjacency matrix represents the number of edges in the opcode sequence-controlled flow graph; Number of nodes: In the adjacency matrix, the number of rows or columns represents the number of nodes in the opcode sequence-based flow graph; Maximum out-degree: In the adjacency matrix, the sum of the elements in the i-th row represents the out-degree of the i-th basic block; Maximum in-degree: In the adjacency matrix, the sum of the elements in the i-th column represents the maximum in-degree of the i-th basic block.

[0032] The vulnerability categories and their potentially related opcode categories are obtained, and the proportion of each type of opcode in the opcode sequence is used as a feature; the proportion of each type of opcode has already been calculated in step 1.2. This embodiment selects six vulnerabilities as detection targets and eight related opcode categories. The vulnerability categories are integer positive overflow vulnerabilities, integer negative overflow vulnerabilities, stack call depth attack vulnerabilities, transaction execution order dependency vulnerabilities, timestamp dependency vulnerabilities, and reentrancy vulnerabilities. The opcode categories are unary operation opcodes, binary operation opcodes, block information opcodes, control flow opcodes, environment opcodes, system opcodes, stack opcodes, and invalid opcodes. The type and number of opcodes are selected according to the vulnerability categories; therefore, the opcode types are scalable.

[0033] The features of the scalable eight-dimensional opcode ratio based on vulnerability category analysis in this embodiment are the unary operation opcode ratio, binary operation opcode ratio, block information opcode ratio, control flow opcode ratio, environment opcode ratio, system opcode ratio, stack opcode ratio, and invalid opcode ratio.

[0034] Unary opcode ratio: When extracting this feature, the function COUNT(opcodes) is defined to calculate the total number of opcodes of each type, where the total number of opcodes is COUNT(total opcodes) and the number of unary arithmetic opcodes is COUNT(una), thus obtaining the unary opcode ratio as COUNT(una) / COUNT(total opcodes).

[0035] Binary opcode ratio: When extracting this feature, a function COUNT(opcodes) is defined to calculate the total number of opcodes of each type, where the total number of opcodes is COUNT(total opcodes) and the number of binary opcodes is COUNT(bin). Thus, the feature value of the binary opcode ratio feature is COUNT(bin) / COUNT(total opcodes).

[0036] System opcode ratio: When extracting this feature, the number of system opcodes is defined as COUNT(sys), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the system opcode ratio feature values ​​are COUNT(sys) / COUNT(total opcodes).

[0037] Stack opcode ratio: When extracting this feature, the number of stack opcodes is defined as COUNT(sta), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the feature values ​​of the stack opcode ratio feature are COUNT(sta) / COUNT(total opcodes).

[0038] Environment opcode ratio: When extracting this feature, the number of environment opcodes is defined as COUNT(env), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the feature value of the environment opcode ratio feature is COUNT(env) / COUNT(total opcodes).

[0039] Block opcode ratio: When extracting this feature, the number of block opcodes is defined as COUNT(blo), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the feature value of the block opcode ratio feature is COUNT(blo) / COUNT(total opcodes).

[0040] Control flow opcode ratio: When extracting this feature, the number of control flow opcodes is defined as COUNT(con), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the feature value of the control flow opcode ratio feature is COUNT(con) / COUNT(total opcodes).

[0041] Invalid opcode ratio: The last type of opcode is the invalid opcode, which is the sum of all other opcodes besides those mentioned above. When extracting this feature, the number of invalid opcodes is defined as COUNT(inv), and the total number of opcodes is defined as COUNT(total opcodes). Therefore, the feature value of the invalid opcode feature is COUNT(inv) / COUNT(total opcodes).

[0042] In summary, this embodiment employs 12-dimensional features and 6-dimensional vulnerabilities.

[0043] Step 4: Normalize the 12-dimensional features and use them as input, with the 6-dimensional vulnerabilities as output, to train the machine learning model.

[0044] To better adapt to current mainstream machine learning models, the extracted scalable 12-dimensional features were normalized. Firstly, due to the differences in feature extraction, the first four dimensions (features of the opcode sequence control flow graph) are large integers, while the latter eight dimensions are decimals between 0 and 1. Therefore, directly using these twelve dimensions as input to a machine learning model could cause some models (such as KNN) to focus only on the first four dimensions during training, neglecting the latter eight. Furthermore, some machine learning models have requirements for the input data format; for example, LSTM requires integer input. Therefore, the above data features were normalized by identifying the maximum and minimum values ​​of each dimension in the dataset, mapping each dimension to decimals between 0 and 1 according to a ratio, and then spreading these decimals to integers within 1000. The normalization formula is shown below:

[0045] Where x(n,f) represents the eigenvalue in the nth row and fth column of the feature space.

[0046] The mainstream machine learning models are Xtreme Gradient Boosting (XGBoost), K-Nearest Neighbors (KNN), Logistic Regression, Decision Tree, Random Forest, Navie Bayes, and Long Short-Term Memory (LSTM).

[0047] Step 5: Use the trained machine learning model to perform vulnerability detection.

[0048] Compared to existing N-gram extraction methods that extract thousands of dimensions of data features, the features in this embodiment reduce vulnerability detection latency from 15ms to 0.2ms on the XGBoost model without decreasing accuracy, precision, F1 score, or recall index—a 75-fold improvement. On the decision tree model, without decreasing any parameters, the vulnerability detection latency is reduced from 2.6ms to 0.004ms—a 650-fold improvement, representing the largest improvement among all models. Furthermore, compared to traditional detection methods, such as the Oyente vulnerability detection tool (with a detection latency of 7.89s) and graph neural network-based detection methods (with a detection latency of 1.9s), our method shows a significant improvement in detection latency.

[0049] Step 6: Based on the trained machine learning model, use the `feature_importances_` method, `permutation_importance()` method, or `model.coef_` method to calculate the contribution of each feature for each type of vulnerability, and determine the features associated with each type of vulnerability. For the same machine learning model, when predicting the vulnerability type of anomaly contracts, if the contribution of a certain feature is higher than the average feature contribution, then the anomaly contract is highly likely to have the vulnerability corresponding to that feature.

[0050] Calculations show that the integer positive overflow vulnerability, integer negative overflow vulnerability, stack call depth attack vulnerability, transaction execution order dependency vulnerability, timestamp dependency vulnerability, and reentrancy vulnerability are all related to the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree.

[0051] Furthermore, the proportions of unary and binary opcodes are associated with integer overflow vulnerabilities. Contract integer overflow vulnerabilities arise when certain variables exceed their defined word length or fall below their minimum value during computation. This is closely related to unary and binary opcodes; therefore, arithmetic opcodes are categorized into unary and binary opcodes, and the proportion of each opcode is calculated as a characteristic for detecting this vulnerability.

[0052] The ratio of system opcodes and stack opcodes is associated with stack call depth vulnerabilities. Contract stack call depth vulnerabilities occur when a caller invokes another contract and the call stack depth exceeds a threshold. Instead of throwing an exception, the instruction returns false, making the caller unaware of the call failure. Opcodes related to inter-contract calls are relevant to this vulnerability and can be categorized into system opcodes and stack opcodes. The ratio of system opcodes to stack opcodes is calculated as a characteristic for detecting this vulnerability.

[0053] The ratio of environment opcodes is associated with transaction execution order dependency vulnerabilities. These vulnerabilities are related to opcodes that discover transaction information, are classified as environment opcodes, and the ratio of environment opcodes is calculated as a characteristic for detecting these vulnerabilities.

[0054] The block opcode ratio is associated with a timestamp dependency vulnerability. This vulnerability arises because block information in Ethereum, such as block timestamps, block numbers, and block hash values, is used as judgment conditions for critical operations in smart contracts or as seeds for generating random numbers. The opcodes associated with this vulnerability primarily contain block information and are categorized as block opcodes. The block opcode ratio is calculated as a characteristic for detecting this vulnerability.

[0055] The ratio of control flow opcodes is associated with reentrancy vulnerabilities. Contract reentrancy vulnerabilities arise from the unique nature of the Ethereum programming language, Solidity. Solidity's unique fallback mechanism allows attackers to re-enter a called function before the program's command execution has finished, resulting in duplicate calls. Such vulnerabilities can cause substantial economic losses. This vulnerability is closely related to control flow opcodes, and is categorized as a control flow opcode vulnerability. The ratio of control flow opcodes is calculated as a characteristic for detecting this vulnerability.

[0056] In this embodiment, we propose a rule-based method for constructing a contract bytecode adjacency matrix. This method separates metadata and converts runtime code into an opcode sequence, then converts it into an adjacency matrix form based on specific opcodes. Next, we extract 12-dimensional data features from this adjacency matrix that satisfy six contract vulnerability detection criteria. These include 4-dimensional adjacency matrix features for analyzing and diagnosing errors in problematic contracts, and 8-dimensional opcode ratio features for identifying six known contract vulnerabilities. The 12-dimensional data features can be extended to detect new vulnerabilities. Finally, we validate the detection efficiency and performance metrics of these 12-dimensional data features using seven different machine learning algorithms. An optional feature normalization method supports the effective detection of more machine learning algorithms, and feature contribution is used for error diagnosis and analysis of problematic contracts, improving the interpretability of the features. Compared to existing N-gram models that extract thousands of dimensions of data features, our features reduce vulnerability detection latency from 15ms to 0.2ms on the XGBoost model without decreasing accuracy, precision, F1 score, or recall index—a 75-fold improvement. On the decision tree model, without decreasing any parameters, we reduce vulnerability detection latency from 2.6ms to 0.004ms—a 650-fold improvement, representing the largest improvement among all models. Furthermore, compared to traditional detection methods, such as the Oyente vulnerability detection tool (which has a detection latency of 7.89s) and graph neural network-based detection methods (which have a detection latency of 1.9s), our method significantly improves upon these methods.

[0057] The present invention has been described in detail above through embodiments, but the content described is only an exemplary embodiment of the present invention and should not be considered as limiting the scope of the present invention. The scope of protection of the present invention is defined by the claims. Any technical solutions designed by those skilled in the art using the technical solutions described in the present invention, or designed by those skilled in the art under the inspiration of the technical solutions of the present invention, within the substance and protection scope of the present invention, to achieve the above-mentioned technical effects, or any equivalent changes and improvements made to the scope of the application, should still fall within the patent protection scope of the present invention.

Claims

1. A vulnerability detection method for smart contracts based on low-dimensional bytecode features, characterized in that: Includes the following steps: Step 1: Construct an opcode sequence control flow graph using Ethereum smart contract bytecode; Step 2: Record and number each basic block in the control flow graph according to the opcode sequence, and then traverse the edges associated with each basic block to build an adjacency matrix; Step 3: Based on the adjacency matrix, obtain the features of the opcode sequence control flow graph, namely the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree; Obtain the vulnerability category and the opcode category that may be related to it, and use the proportion of each type of opcode in the total number of opcodes in the opcode sequence as a feature; Step 4: Normalize the features from Step 3, and then use them as input and vulnerability categories as output to train the machine learning model; Step 5: Use the trained machine learning model to perform vulnerability detection.

2. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: In step 1, runtime code is separated from the Ethereum smart contract bytecode, and the bytecode of the runtime code is converted into opcodes to obtain an opcode sequence. An opcode sequence control flow graph is constructed based on the opcode sequence. The basic block of the opcode sequence control flow graph is an opcode sequence between a jump address and the next jump instruction, and the edge of the opcode sequence control flow graph is the jump relationship between the jump instruction and the jump destination address.

3. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: In step 1, the number of each type of opcode in the opcode sequence is counted and the proportion of each type of opcode is calculated.

4. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: In step 2, if the element in the i-th row and j-th column of the adjacency matrix is ​​1, it indicates that there is an edge connecting the i-th basic block and the j-th basic block, and the direction of the edge is from the i-th basic block to the j-th basic block; if the element is 0, there is no edge connecting the two basic blocks.

5. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 4, characterized in that: In step 3, the number of edges: In the adjacency matrix, the sum of the elements in the adjacency matrix represents the number of edges in the opcode sequence-controlled flow graph; Number of nodes: In the adjacency matrix, the number of rows or columns represents the number of nodes in the opcode sequence-based flow graph; Maximum out-degree: In the adjacency matrix, the sum of the elements in the i-th row represents the out-degree of the i-th basic block; Maximum in-degree: In the adjacency matrix, the sum of the elements in the i-th column represents the maximum in-degree of the i-th basic block.

6. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: In step 4, the machine learning model is one of Xtreme Gradient Boosting, K-Nearest Neighbors, Logistic Regression, Decision Tree, Random Forest, Navie Bayes, and Long Short-Term Memory.

7. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 6, characterized in that: The machine learning model is a Decision Tree.

8. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: In step 4, the features are normalized: the maximum and minimum values ​​of each feature dimension in the dataset are found, and the data of each feature dimension are mapped to decimals between 0 and 1 according to the proportion. Then, these decimals are spread out to integers within 1000.

9. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 1, characterized in that: Step 6: Based on the trained machine learning model, use the feature_importances_ method, permutation_importance() method, or model.coef_ method to calculate the contribution of each feature for each type of vulnerability, and determine the features associated with each type of vulnerability.

10. The vulnerability detection method for smart contracts based on low-dimensional bytecode features as described in claim 9, characterized in that: In step 3, the vulnerability categories are integer positive overflow vulnerability, integer negative overflow vulnerability, stack call depth attack vulnerability, transaction execution order dependency vulnerability, timestamp dependency vulnerability, and reentrancy vulnerability. The opcode categories are unary opcode, binary opcode, block information opcode, control flow opcode, context opcode, system opcode, stack opcode, and invalid opcode; The aforementioned integer positive overflow vulnerabilities, integer negative overflow vulnerabilities, stack call depth vulnerabilities, transaction execution order dependency vulnerabilities, timestamp dependency vulnerabilities, and reentrancy vulnerabilities are all related to the number of edges, the number of nodes, the maximum out-degree, and the maximum in-degree. Furthermore, integer positive overflow vulnerabilities are also related to the ratio of unary opcodes and binary opcodes; integer negative overflow vulnerabilities are also related to the ratio of unary opcodes and binary opcodes; stack call depth vulnerabilities are also related to the ratio of system opcodes and stack opcodes; transaction execution order dependency vulnerabilities are also related to the ratio of environment opcodes; timestamp dependency vulnerabilities are also related to the ratio of block information opcodes; and reentrancy vulnerabilities are also related to the ratio of control flow opcodes.