Intelligent contract reentry attack vulnerability analysis method and system

Through the random forest model, smart contract feature extraction and training can be carried out to achieve accurate detection and early warning of reentry attack vulnerabilities, solving the problems of insufficient detection accuracy and poor real-time performance in the existing technology, dynamically adapting to the new attack mode, and improving blocks Security of the chain system.

CN119150293APending Publication Date: 2024-12-17GUANGDONG UNIV OF TECH
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202411111196.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-08-14
Publication Date
2024-12-17

AI Technical Summary

Technical Problem

The existing smart contract vulnerability detection methods cannot effectively detect reentry attack vulnerabilities, and there are problems such as insufficient accuracy, poor real-time performance and difficulty in model update.

Method used

The random forest model is used for smart contract feature extraction and training, to achieve accurate detection and early warning of reentry attack vulnerabilities, and to adapt to new attack modes through online monitoring and model updates.

Benefits of technology

It improves the accuracy and real-time detection of smart contract reentry attack vulnerability, dynamically adapts to emerging attack modes, reduces the security risks of blockchain systems, and ensures the security and reliability of applications.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119150293A_ABST
    Figure CN119150293A_ABST
Patent Text Reader

Abstract

The invention discloses a smart contract re-entry attack vulnerability analysis method and system. The method comprises the following steps: collecting smart contracts containing re-entry attack vulnerabilities and security verification; marking a corresponding label according to the type of the smart contract, and performing feature extraction on the smart contract; constructing a random forest model, and performing training optimization on the random forest model based on the feature data set to obtain a reentry attack vulnerability judgment model; performing online detection and monitoring on the reentry attack vulnerability judgment model to obtain a new reentry attack behavior data set; and retraining the reentry attack vulnerability judgment model to obtain an updated reentry attack vulnerability judgment model. The system comprises a data collection module, a feature extraction module, a model training module, a monitoring module and a model updating module. According to the invention, the re-entry attack vulnerability in the smart contract can be accurately detected and prevented, and the security and reliability of the block chain system are ensured. The method can be widely applied to the technical field of block chains.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of blockchain technology, and in particular to a smart contract reentry attack vulnerability analysis method and system. Background Art

[0002] As a decentralized distributed ledger technology, blockchain technology has received widespread attention and rapid development in recent years. The core features of blockchain technology are its decentralization, immutability and transparency, which makes it have broad application prospects in many fields such as finance, supply chain management, and the Internet of Things. In the development of blockchain technology, the introduction of smart contracts has greatly expanded the functions and application scope of blockchain. Smart contracts are self-executing codes executed on the blockchain that can automatically execute contract terms when predetermined conditions are met, thereby realizing decentralized automated contract execution.

[0003] However, with the widespread application of smart contracts, their security issues have become increasingly prominent. Reentrancy attack is one of the most common and destructive vulnerabilities in smart contracts. Reentrancy attack means that during an external call, the attacker repeatedly enters the same contract by recursively calling the contract's external interface, thereby bypassing the contract's status check mechanism. This attack method can cause key operations in the contract (such as transfers, data modifications, etc.) to be executed multiple times, causing serious economic losses.

[0004] At present, the analysis methods for smart contract security mainly include static analysis and dynamic analysis. Static analysis methods perform security assessments by checking potential vulnerabilities in smart contract codes. Typical methods and systems include Mythril, Slither, etc. However, the accuracy and coverage of static analysis methods are limited by the complexity of the code, and it is difficult to fully detect all potential vulnerabilities in complex contracts. Dynamic analysis methods detect vulnerabilities by monitoring the behavior of contracts during runtime. Typical methods and systems include Echidna, Manticore, etc. Although dynamic analysis can detect problems that may occur during actual operation, it has a large overhead and cannot prevent potential attacks in advance.

[0005] The existing smart contract vulnerability detection methods and systems cannot effectively detect the problem of smart contract reentrancy attack vulnerabilities, which is mainly manifested in the following three aspects:

[0006] 1. Insufficient accuracy: Static analysis methods and systems are easily affected by code complexity and may miss some hidden reentrancy attack vulnerabilities.

[0007] 2. Poor real-time performance: Most dynamic analysis methods and systems can only detect problems after the contract is executed, and cannot provide early warning and prevention before the attack occurs.

[0008] 3. Difficulty in model updating: Existing methods and systems usually lack self-learning and updating mechanisms, making it difficult to adapt to ever-changing and complex attack patterns. Summary of the invention

[0009] In order to solve the above technical problems, the purpose of the present invention is to provide a smart contract reentrancy attack vulnerability analysis method and system, which can accurately detect and prevent reentrancy attack vulnerabilities in smart contracts and ensure the security and reliability of the blockchain system.

[0010] The first technical solution adopted by the present invention is: a smart contract reentry attack vulnerability analysis method, comprising the following steps:

[0011] Collect smart contracts with reentrancy vulnerabilities and verification security;

[0012] Label the smart contract accordingly according to its type, and extract features from the smart contract to obtain a feature data set;

[0013] Constructing a random forest model, and training and optimizing the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model;

[0014] Performing online detection and monitoring on the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set;

[0015] The reentrancy attack vulnerability judgment model is retrained based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

[0016] Furthermore, the step of labeling the smart contract according to its type and extracting features from the smart contract to obtain a feature data set specifically includes:

[0017] Classify the smart contracts according to the tags, and store the tag types into smart contracts with reentrancy attack vulnerabilities and smart contracts with verification security respectively;

[0018] Parsing and disassembling the bytecode of the smart contract to obtain an operation code sequence of the smart contract;

[0019] Performing n-gram analysis on the operation code sequence of the smart contract to obtain a first feature vector;

[0020] Performing frequency analysis on the operation code sequence of the smart contract to obtain a second feature vector;

[0021] Performing feature fusion on the first feature vector and the second feature vector to obtain a fused feature vector;

[0022] Feature selection and normalization are performed on the fused feature vectors, and the fused feature vectors are assembled into a feature data set.

[0023] Furthermore, the step of constructing a random forest model and training and optimizing the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model specifically includes:

[0024] Constructing a random forest model, and dividing the feature data set into a training set and a test set;

[0025] Randomly sampling the training set, and inputting the randomly sampled samples into the random forest model for training to obtain a trained random forest model;

[0026] Inputting the trained random forest model into the test machine for prediction to obtain a prediction result;

[0027] Calculate various evaluation indicators based on the prediction results;

[0028] Based on various evaluation indicators, the parameters of the trained random forest model are adjusted and optimized to obtain a reentrancy attack vulnerability judgment model.

[0029] Furthermore, the decision tree of the random forest model is expressed as follows:

[0030] Tree i =fit(X',y')

[0031]

[0032] Among them, Tree i represents the i-th decision tree; X' represents a randomly selected sample subset; y' represents the label of a randomly selected sample subset; fit(·) represents the fitting function; N j represents the number of current nodes j; K represents the number of categories of samples in the current node; |X' j | represents the number of samples in node j; |X' jk | represents the number of samples of category k in node j.

[0033] Furthermore, the evaluation indicators include accuracy, precision, recall and F1 score.

[0034] Furthermore, the judgment condition of the new reentrancy attack behavior data set is that if the reentrancy attack vulnerability judgment model detects that the interaction between the smart contract and other smart contracts has reached three or more times when a transaction occurs in the smart contract, then it is judged that the smart contract has a new reentrancy attack behavior, and the smart contract is included in the new reentrancy attack behavior data set.

[0035] The second technical solution adopted by the present invention is: a smart contract reentry attack vulnerability analysis system, comprising:

[0036] Data collection module, used to collect smart contracts with reentrancy attack vulnerabilities and verify security;

[0037] A feature extraction module, which tags the smart contract according to its type and extracts features from the smart contract to obtain a feature data set;

[0038] A model training module is used to construct a random forest model and train and optimize the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model;

[0039] A monitoring module, used for online detection and monitoring of the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set;

[0040] The model updating module retrains the reentrancy attack vulnerability judgment model based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

[0041] Furthermore, the feature extraction module includes a bytecode disassembly module, a 4-gram analysis module, an operation code frequency analysis module, a feature vector merging module, and a feature selection and normalization module.

[0042] The third technical solution adopted by the present invention is: a smart contract reentry attack vulnerability analysis device, comprising:

[0043] at least one processor;

[0044] at least one memory for storing at least one program;

[0045] When the at least one program is executed by the at least one processor, the at least one processor implements the above-mentioned smart contract reentry attack vulnerability analysis method.

[0046] The beneficial effects of the method and system of the present invention are as follows: the present invention realizes the automatic detection and real-time monitoring of smart contract reentrancy attack vulnerabilities through data-driven and model learning methods. Compared with the existing static and dynamic analysis methods, the present invention improves the accuracy of smart contract reentrancy attack vulnerability detection through model learning and training; and realizes real-time monitoring and early warning of smart contracts; through model updates, it can dynamically adapt to new attack modes, maintain the advanced nature of detection methods and systems, and can dynamically adapt to emerging attack modes, improve the accuracy and coverage of detection, and effectively reduce the risks and losses caused by reentrancy attacks; reduce the security risks in the blockchain system, and ensure the security and reliability of blockchain applications. BRIEF DESCRIPTION OF THE DRAWINGS

[0047] Figure 1 It is a flowchart of the steps of a smart contract reentry attack vulnerability analysis method of the present invention;

[0048] Figure 2 It is a structural block diagram of a smart contract reentry attack vulnerability analysis system of the present invention;

[0049] Figure 3 It is a monitoring and early warning schematic diagram of a smart contract reentry attack vulnerability analysis method of the present invention;

[0050] Figure 4 It is a schematic diagram of a model update of a smart contract reentry attack vulnerability analysis method of the present invention. DETAILED DESCRIPTION

[0051] The present invention is further described in detail below in conjunction with the accompanying drawings and specific embodiments. The step numbers in the following embodiments are only provided for the convenience of explanation and description, and the order between the steps is not limited in any way. The execution order of each step in the embodiment can be adaptively adjusted according to the understanding of those skilled in the art.

[0052] Reference Figure 1 The present invention provides a smart contract reentrancy attack vulnerability analysis method, the method comprising the following steps:

[0053] S1. Collect smart contracts with reentrancy vulnerabilities and verify security;

[0054] Specifically, for the collection of smart contracts containing reentrancy attack vulnerabilities, the present invention is carried out through the DeFiHackLabs library and the OpenZeppelin platform. The DeFiHackLabs library is a library that collects reports of attack incidents on blockchains such as Ethereum. Through this library, known reentrancy attack incidents and their related contracts can be found. The OpenZeppelin platform is a blockchain event response service platform, through which public attack reports and vulnerable contracts can be found. By searching on the platform using relevant keywords (such as "reentrancy attack"), after finding the relevant vulnerable contracts, they are manually confirmed. The manual confirmation method includes building an attack contract and experimenting in a test environment to verify the vulnerability of the contract and ensure that it does have a reentrancy attack vulnerability.

[0055] For the collection of smart contracts with verified security, the present invention sorts out popular Ethereum smart contracts from DappRadar. DappRadar provides data such as user transaction volume of decentralized applications. The top 100 decentralized applications are selected based on user transaction volume. These popular contracts have been strictly audited before release, so it is assumed that these smart contracts have no malicious vulnerabilities. The contract addresses of these decentralized applications are obtained and the bytecodes of these contracts are downloaded using a blockchain browser (such as Etherscan).

[0056] Since the present invention performs vulnerability analysis on bytecode-level smart contracts, if the collected contracts are in source code form, they need to be compiled into corresponding bytecode form. The specific embodiment of this method uses the Solidity compiler for compilation.

[0057] S2. Label the smart contract accordingly according to its type, and extract features from the smart contract to obtain a feature data set;

[0058] S2.1. Classify the smart contracts according to the tags, and store the tag types into smart contracts with reentrancy attack vulnerabilities and smart contracts with verification security respectively;

[0059] S2.2. Parse and disassemble the bytecode of the smart contract to obtain an operation code sequence of the smart contract;

[0060] Specifically, the bytecode parsing and disassembly is to parse the bytecode of the smart contract into an opcode sequence. The operation instructions of the Ethereum virtual machine are divided by bytes, and the disassembly is achieved by scanning the bytecode byte by byte and matching the corresponding opcode. Among the many operation instructions, the PUSH instruction is relatively special, and its operand will use the following part of the data as a value rather than an operation instruction. Therefore, when parsing the PUSH instruction, its operand is specially processed and the corresponding bytes are skipped.

[0061] S2.3. Perform n-gram analysis on the operation code sequence of the smart contract to obtain a first feature vector;

[0062] Specifically, in order to capture more complex opcode combinations, the specific embodiment of the present invention sets n to 4 to more accurately identify complex reentrancy attack patterns. 4-gram analysis can capture contextual information in opcode sequences, and by identifying combinations of four consecutive opcodes, the characteristics of reentrancy attacks can be effectively detected. For example, in the opcode sequence of a smart contract PUSH1PUSH1 MSTORE CALLVALUE DUP1 ISZERO PUSH1 JUMPIPUSH1 DUP1 REVERT JUMPDESTPOP PUSH1 MLOAD PUSH1 DUP1 SWAP1, the generated 4-gram sequence is (PUSH1, PUSH1, MSTORE, CALLVALUE), (PUSH1, MSTORE, CALLVALUE, DUP1), (MSTORE, CALLVALUE, DUP1, ISZERO), etc. The specific embodiment of the present invention initializes a feature vector for each smart contract, the length of the feature vector is equal to the size of the dynamic feature space, and the initial value is zero. Scan the opcode sequence of the smart contract, generate a 4-gram sequence, count the frequency of each 4-gram, fill in the corresponding frequency value in the corresponding n-gram feature position in the feature vector, and form the first feature vector. This method can capture the characteristics of complex opcode combinations and help identify reentrancy attack patterns.

[0063] S2.4. Perform frequency analysis on the operation code sequence of the smart contract, count the frequency of occurrence of each operation code in the contract, and obtain a second feature vector;

[0064] Specifically, the frequency analysis can capture the overall operational behavior pattern of the smart contract. For example, for the opcode sequence PUSH1 PUSH1 MSTORE CALLVALUE DUP1 ISZERO PUSH1 JUMPIPUSH1 DUP1 REVERTJUMPDEST POP PUSH1 MLOAD PUSH1 DUP1 SWAP1, the frequency of occurrence of each opcode is counted to obtain the feature vector {PUSH1:5,MSTORE:1,CALLVALUE:1,DUP1:3,ISZERO:1,JUMPI:1,REVERT:1,JUMPDEST:1,POP:1,MLOAD:1,SWAP1:1}. The opcode frequency analysis can reveal the frequent use of certain opcodes, which is very useful for detecting specific behaviors such as reentrancy attacks. The specific embodiment of the present invention obtains the second feature vector by counting the frequency of occurrence of each opcode and filling the corresponding opcode feature position in the feature vector with the corresponding frequency value.

[0065] S2.5. Merge the first feature vector and the second feature vector in series to obtain a fused feature vector;

[0066] Specifically, merging the feature vectors of n-gram analysis and opcode frequency analysis can provide a more comprehensive feature representation and improve the model's ability to detect reentrancy attack vulnerabilities. n-gram analysis captures the combination and contextual information of opcodes, which is suitable for identifying complex attack patterns; opcode frequency analysis reveals the overall operational behavior pattern of the contract, which is suitable for detecting frequently used opcodes and their possible risky behaviors. By merging the features of these two methods, we can take advantage of the advantages of both methods to more accurately identify and detect reentrancy attack vulnerabilities.

[0067] S2.6. Perform feature selection and normalization on the fused feature vectors and aggregate them into a feature data set.

[0068] Specifically, feature selection is performed on the fused feature vector to retain the feature subset that best represents the reentrancy attack feature. The key opcode combinations of the n-gram feature include (CALL, DUP, SSTORE, JUMP) and (CALL, POP, JUMP, JUMPDEST). The (CALL, DUP, SSTORE, JUMP) opcode combination is common in the reentrancy attack pattern, where CALL is used for external calls, DUP is used to copy the top element of the stack, SSTORE is used to store status, and JUMP is used to jump the control flow. The (CALL, POP, JUMP, JUMPDEST) opcode combination is also common in the reentrancy attack pattern, where POP is used for stack operations, and JUMP and JUMPDEST are used for control flow.

[0069] The key opcodes that the frequency analysis features include: CALL, SSTORE, JUMP, and JUMPDEST. The frequency of the CALL opcode is an important feature of reentrancy attacks, because reentrancy attacks often rely on multiple calls to external contracts. The frequency of the SSTORE opcode is also an important feature of reentrancy attacks, because state storage operations may be called multiple times in reentrancy attacks. The frequency of the JUMP and JUMPDEST control flow opcodes can reveal complex control flow structures, which are also important in reentrancy attacks.

[0070] By selecting the above feature subsets through feature selection, the characteristic patterns of reentrancy attacks can be effectively captured. The key opcode combination of n-gram features can capture the contextual information in the opcode sequence and reveal complex attack patterns; the key opcodes of frequency analysis features reveal the overall operational behavior pattern of the smart contract and can identify frequently used opcodes and their possible risky behaviors.

[0071] Then the selected feature subset is normalized and scaled to a specific range (such as 0 to 1) to meet the requirements of model training. The normalization formula is as follows:

[0072]

[0073] Among them, X represents the original eigenvalue, X norm represents the normalized eigenvalue, X min and X max represent the minimum and maximum eigenvalues ​​respectively.

[0074] Finally, the processed feature vectors are grouped into a feature dataset and saved in a structured format, such as JSON or CSV file. Each row of the feature dataset represents a feature vector of a smart contract, and each column represents a feature. Labels are added to the feature dataset to indicate whether each smart contract contains a reentrancy attack vulnerability. Each row of the feature dataset includes a feature vector and a corresponding label.

[0075] S3. Construct a random forest model, and train and optimize the random forest model based on the feature data set to obtain a reentrancy attack vulnerability judgment model;

[0076] S3.1, constructing a random forest model, and dividing the feature data set into a training set and a test set;

[0077] Specifically, the feature data set is divided into a training set and a test set. In particular, the specific embodiment of the present invention adopts an 80 / 20 ratio, that is, 80% of the data is used for training the model and 20% of the data is used for testing the model. This can be achieved by a random sampling method to ensure the randomness and representativeness of the data division.

[0078] Select a machine learning model suitable for detecting reentrancy attack vulnerabilities. Commonly used models include decision trees, random forests, support vector machines (SVMs), and neural networks. Each model has its advantages and applicable scenarios, and a suitable model can be selected according to actual needs. In particular, in a specific embodiment of the present invention, a random forest model (Random Forest) is selected as a machine learning model for detecting reentrancy attack vulnerabilities for training, because random forests have high accuracy and robustness when dealing with classification problems, and can process high-dimensional data.

[0079] The random forest model of the specific embodiment of the present invention selects 100 trees (n estimators = 100), because more trees can improve the stability and accuracy of the model; the maximum depth is set to 10 (max depth=10), which can prevent overfitting while ensuring that the model complexity is sufficient to detect reentrancy vulnerabilities. The random forest model consists of multiple decision trees, each of which randomly samples and selects features to form an integrated model. The prediction result of the random forest model is the average of the prediction results of all decision trees.

[0080] The decision tree of the random forest model is expressed as follows:

[0081] Tree i =fit(X',y')

[0082]

[0083] Among them, Tree i represents the i-th decision tree; X' represents a randomly selected sample subset; y' represents the label of a randomly selected sample subset; fit(·) represents the fitting function; N j represents the number of current nodes j; K represents the number of categories of samples in the current node; |X' j | represents the number of samples in node j; |X' jk | represents the number of samples of category k in node j.

[0084] S3.2, randomly sampling the training set, and inputting the randomly sampled samples into the random forest model for training, to obtain a trained random forest model;

[0085] Specifically, refer to Figure 3 During the training process, the random forest model will learn the mapping relationship between feature vectors and reentrancy attack vulnerability labels. The feature data set X is a feature matrix, each row represents the feature vector of a smart contract, and each column represents a feature. The label set y is a label vector, indicating whether each smart contract contains a reentrancy attack vulnerability. For each decision tree, the random forest model randomly samples from the training set to form a subset X' and y', where X' and y' are samples randomly selected from X and y. In particular, a label y of 1 indicates that the smart contract contains a reentrancy attack vulnerability; a label y of 0 indicates that the smart contract does not contain a reentrancy attack vulnerability.

[0086] For each input sample x, the random forest model predicts through all decision trees and takes the average as the prediction result, which is expressed as follows:

[0087]

[0088] Where T represents the number of decision trees.

[0089] During the training process, the parameters of the random forest model are continuously adjusted to continuously narrow the distance between the prediction results and the reentry attack vulnerability labels, and thus a trained random forest model is obtained.

[0090] S3.3, inputting the trained random forest model into the test machine for prediction to obtain a prediction result;

[0091] Specifically, input the test set data X test and label y test Input into the trained random forest model for prediction and get the prediction result

[0092] S3.4. Calculate various evaluation indicators based on the prediction results;

[0093] Specifically, the evaluation indicators include accuracy, precision, recall and F1 score. The accuracy is expressed as follows:

[0094]

[0095] Among them, Accuracy represents the accuracy; TP, TN, FP, and FN represent true positive, true negative, false positive, and false negative, respectively.

[0096] The accuracy is expressed as follows:

[0097]

[0098] Among them, Precision represents the accuracy.

[0099] The recall rate is expressed as follows:

[0100]

[0101] Among them, Recall represents the recall rate.

[0102] The F1 score is expressed as follows:

[0103]

[0104] Among them, F1Score represents the F1 score.

[0105] S3.5. Based on various evaluation indicators, the parameters of the trained random forest model are adjusted and optimized to obtain a reentrancy attack vulnerability judgment model.

[0106] Specifically, the trained random forest model is optimized according to the evaluation results. The detection performance of the model can be improved by adjusting model parameters, increasing the amount of training data, selecting more appropriate features, and the like. The adjustment of the parameters of the random forest model includes but is not limited to increasing the number of trees, adjusting the maximum depth, and observing the impact on the model performance; the increase in the amount of training data is to improve the generalization ability of the model by collecting more contracts containing reentrancy attack vulnerabilities and verifying the safety of contracts; the selection of more appropriate features is to extract features that are more representative of reentrancy attack vulnerabilities through feature selection and feature engineering, thereby improving the detection ability of the model.

[0107] After optimization, the specific embodiment of the present invention selects the random forest model with the best performance as the final detection model. The final model is saved as a model file so that it can be called and used in practical applications. Through the above steps, the method can train a machine learning model that can accurately detect the reentrancy attack vulnerability of smart contracts. In practical applications, the model can judge whether the contract contains a reentrancy attack vulnerability by inputting the feature vector of the smart contract, thereby improving the security and reliability of the smart contract.

[0108] The trained machine learning model is output to determine whether there is a reentrancy attack vulnerability in the smart contract. The results of the model output can be used for subsequent smart contract security detection and early warning. The output of the model includes the probability value of vulnerability detection and the specific vulnerability type, providing a strong guarantee for the security of smart contracts.

[0109] S4, performing online detection and monitoring on the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set;

[0110] Specifically, refer to Figure 4 , the user enters the address of the target smart contract that needs to be reentrant attack vulnerability detection through the interface or command line. Then, the corresponding bytecode is obtained through the blockchain API according to the corresponding address. This specific embodiment uses the API interface provided by Ethereum, such as Infura or EtherscanAPI, to obtain the bytecode of the smart contract.

[0111] After obtaining the bytecode, the bytecode is input into the reentrancy attack vulnerability judgment model for detection. If the model determines that the contract contains a reentrancy attack vulnerability, a detection report is directly generated, which includes the contract address, detection results and corresponding detailed descriptions.

[0112] If the model determines that the contract does not contain a reentrancy attack vulnerability, the transaction behavior of the smart contract will be monitored for one day (the monitoring time can be set according to demand). During the monitoring period, the present invention will collect and analyze the transaction records of the smart contract, especially the interaction between the smart contract and other smart contracts. The criterion for judging reentrancy attack behavior is that the interaction between the smart contract and other smart contracts reaches three or more times (under normal circumstances, no interaction loop will be formed). If it is detected that the number of interactions between the smart contract and other smart contracts reaches or exceeds three times in one day, it is judged that a reentrancy attack behavior exists.

[0113] If there is no reentrancy attack during the monitoring period, the smart contract is reported to be safe and the relevant information is recorded. If a reentrancy attack is detected during the monitoring period, the smart contract is reported to have a reentrancy attack vulnerability and has been attacked. The report should include detailed interaction records and analysis results for developers to conduct further investigation and processing. The transaction records and bytecode information of the smart contract are then saved as a new reentrancy attack behavior dataset.

[0114] Through the above steps, this method can realize online detection and monitoring of smart contracts, timely discover and report reentrancy attack vulnerabilities, thereby improving the security and reliability of smart contracts.

[0115] S5. Retrain the reentrancy attack vulnerability judgment model based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

[0116] Specifically, the newly appeared reentrancy attack behavior data set detected in step S4 is marked as a sample containing a reentrancy attack vulnerability. Specifically, when a smart contract is monitored to have three or more interactive cycles with other contracts in one day, the transaction records and bytecode information of the smart contract are saved as new training data in a specific embodiment of the present invention.

[0117] Then, the newly collected data is added to the original training data set. The new data includes the detected smart contracts with reentrancy attack vulnerabilities and their transaction behavior records. In this way, the data set can reflect the latest attack patterns and behavior characteristics, improving the generalization ability of the model.

[0118] Next, the reentrancy attack vulnerability judgment model is retrained using the updated data set. During the retraining process, the present invention can adopt an incremental training method, that is, training is performed based on the existing model instead of training from scratch. This can speed up the training and reduce the consumption of computing resources. The specific steps are as follows: First, the new training data is merged with the original data set, and then the model is retrained using the merged data set. The specific embodiment of the present invention continues to select the random forest model and maintains the same parameter settings, such as 100 trees (n estimators = 100) and a maximum depth of 10 (max depth =10) to ensure comparability between the new and old models.

[0119] After training is completed, the present invention uses the updated test set to evaluate the new model. The performance of the new model is evaluated by calculating the accuracy, precision, recall, and F1 score of the new model on the test set. If the new model improves in all indicators, it is deployed as the final detection model; if the performance does not improve significantly, further analysis and optimization of the model is required.

[0120] Finally, the new model is deployed to the detection system to replace the old model. In this way, the method of the present invention can ensure that the detection system always uses the latest and optimal model, and improve the accuracy and reliability of smart contract reentry attack vulnerability detection. At the same time, this method requires regular model updates and optimizations to maintain the advancement and effectiveness of the detection system.

[0121] Through the above steps, this method can realize the continuous updating and optimization of the smart contract detection model, ensuring its effectiveness and accuracy in practical applications. In this way, it can not only improve the security and reliability of smart contracts, but also respond to changing attack patterns and threats in a timely manner.

[0122] Reference Figure 2 , the present invention provides a smart contract reentrancy attack vulnerability analysis system, comprising:

[0123] Data collection module, used to collect smart contracts with reentrancy attack vulnerabilities and verify security;

[0124] A feature extraction module, which tags the smart contract according to its type and extracts features from the smart contract to obtain a feature data set;

[0125] A model training module is used to construct a random forest model and train and optimize the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model;

[0126] A monitoring module, used for online detection and monitoring of the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set;

[0127] The model updating module retrains the reentrancy attack vulnerability judgment model based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

[0128] Preferably, the feature extraction module includes a bytecode disassembly module, a 4-gram analysis module, an opcode frequency analysis module, a feature vector merging module, and a feature selection and normalization module.

[0129] The contents of the above method embodiments are all applicable to the present system embodiments. The functions specifically implemented by the present system embodiments are the same as those of the above method embodiments, and the beneficial effects achieved are also the same as those achieved by the above method embodiments.

[0130] The present invention provides a smart contract reentry attack vulnerability analysis device, comprising:

[0131] at least one processor;

[0132] at least one memory for storing at least one program;

[0133] When the at least one program is executed by the at least one processor, the at least one processor implements the smart contract reentry attack vulnerability analysis method.

[0134] The contents of the above method embodiments are all applicable to the present device embodiments. The functions specifically implemented by the present device embodiments are the same as those of the above method embodiments, and the beneficial effects achieved are also the same as those achieved by the above method embodiments.

[0135] The above is a specific description of the preferred implementation of the present invention, but the invention is not limited to the embodiments. Those skilled in the art may make various equivalent modifications or substitutions without violating the spirit of the present invention. These equivalent modifications or substitutions are all included in the scope defined by the claims of this application.

Claims

1. A smart contract reentrancy attack vulnerability analysis method, characterized in that: The following steps are involved: Collect smart contracts with reentrancy vulnerabilities and verification security; Label the smart contract accordingly according to its type, and extract features from the smart contract to obtain a feature data set; Constructing a random forest model, and training and optimizing the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model; Performing online detection and monitoring on the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set; The reentrancy attack vulnerability judgment model is retrained based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

2. According to claim 1, a smart contract reentrancy attack vulnerability analysis method is characterized in that: The step of labeling the smart contract according to its type and extracting features from the smart contract to obtain a feature data set specifically includes: Classify the smart contracts according to the tags, and store the tag types into smart contracts with reentrancy attack vulnerabilities and smart contracts with verification security respectively; Parsing and disassembling the bytecode of the smart contract to obtain an operation code sequence of the smart contract; Performing n-gram analysis on the operation code sequence of the smart contract to obtain a first feature vector; Performing frequency analysis on the operation code sequence of the smart contract to obtain a second feature vector; Performing feature fusion on the first feature vector and the second feature vector to obtain a fused feature vector; Feature selection and normalization are performed on the fused feature vectors, and the fused feature vectors are assembled into a feature data set.

3. According to claim 1, a smart contract reentrancy attack vulnerability analysis method is characterized in that: The step of constructing a random forest model and training and optimizing the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model specifically includes: Constructing a random forest model, and dividing the feature data set into a training set and a test set; Randomly sampling the training set, and inputting the randomly sampled samples into the random forest model for training to obtain a trained random forest model; Inputting the trained random forest model into the test machine for prediction to obtain a prediction result; Calculate various evaluation indicators based on the prediction results; Based on various evaluation indicators, the parameters of the trained random forest model are adjusted and optimized to obtain a reentrancy attack vulnerability judgment model.

4. According to claim 1, a smart contract reentrancy attack vulnerability analysis method is characterized in that: The decision tree of the random forest model is expressed as follows: Tree i =fit(X’,y') Among them, Tree i represents the i-th decision tree; X' represents a randomly selected sample subset; y' represents the label of a randomly selected sample subset; fit(·) represents the fitting function; N j represents the number of current nodes j; K represents the number of categories of samples in the current node; |X' j | represents the number of samples in node j; |X' jk | represents the number of samples of category k in node j.

5. According to claim 3, a smart contract reentrancy attack vulnerability analysis method is characterized in that: The evaluation indicators include accuracy, precision, recall and F1 score.

6. According to claim 1, a smart contract reentrancy attack vulnerability analysis method is characterized in that: The judgment condition of the new reentrancy attack behavior data set is that if the reentrancy attack vulnerability judgment model detects that the interaction between the smart contract and other smart contracts has reached three or more times when a transaction occurs in the smart contract, it is judged that the smart contract has a new reentrancy attack behavior, and the smart contract is included in the new reentrancy attack behavior data set.

7. A smart contract reentrancy attack vulnerability analysis system, characterized in that: include: Data collection module, used to collect smart contracts with reentrancy attack vulnerabilities and verify security; A feature extraction module, which tags the smart contract according to its type and extracts features from the smart contract to obtain a feature data set; A model training module is used to construct a random forest model and train and optimize the random forest model based on a feature data set to obtain a reentrancy attack vulnerability judgment model; A monitoring module, used for online detection and monitoring of the reentrancy attack vulnerability judgment model to obtain a new reentrancy attack behavior data set; The model updating module retrains the reentrancy attack vulnerability judgment model based on the new reentrancy attack behavior data set to obtain an updated reentrancy attack vulnerability judgment model.

8. According to claim 7, a smart contract reentrancy attack vulnerability analysis system is characterized in that: The feature extraction module includes a bytecode disassembly module, a 4-gram analysis module, an operation code frequency analysis module, a feature vector merging module, and a feature selection and normalization module.

9. A smart contract reentry attack vulnerability analysis device, characterized in that: include: at least one processor; at least one memory for storing at least one program; When the at least one program is executed by the at least one processor, the at least one processor implements the method according to any one of claims 1 to 6.

Citation Information

Cited By

  • Intelligent contract vulnerability detection method based on machine learning and dynamic and static combined analysis

    CN121834827A