Smart contract threat detection and protection method based on path analysis and code instrumentation

Through path analysis and code instrumentation methods, standardized contract source code is generated, a control flow graph is constructed, and probe statements are inserted, which solves the problem of unknown vulnerability detection and protection after smart contract deployment, achieves accurate tracking of contract execution paths, reduces gas overhead, and improves detection accuracy and versatility.

CN116366322BActive Publication Date: 2025-09-09EAST CHINA NORMAL UNIV +1
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202310291329.7
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2023-03-23
Publication Date
2025-09-09
Estimated Expiration
2043-03-23

AI Technical Summary

Technical Problem

Existing technologies are unable to accurately detect and protect against unknown vulnerabilities after smart contracts are deployed, and have problems such as high false alarm rate, poor versatility, inability to locate vulnerable code, and excessive fuel consumption.

Method used

Through path analysis and code instrumentation, we generate standardized contract source code, build a control flow graph, insert probe statements and state variables, deploy and test on the Ethereum simulator, obtain a set of secure paths, and perform traceability detection and protection on the Ethereum mainnet.

Benefits of technology

It achieves accurate tracking of cyclic and acyclic paths after smart contract deployment, reduces gas overhead, improves detection accuracy and versatility, reduces false positive rates, and can locate the location of vulnerability source code.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN116366322B_ABST
    Figure CN116366322B_ABST
Patent Text Reader

Abstract

The present invention discloses a smart contract threat detection and protection method based on path analysis and code insertion. The method preprocesses the smart contract source code in a regular manner; constructs a smart contract control flow graph based on static single assignment form nodes obtained by static analysis of the source code; selects a path analysis algorithm to encode the path according to whether there is a loop in the control flow graph, and obtains probe statements and edges to be inserted; inserts the source code based on the probe statements of the edges to be inserted, and inserts initialization definition code and security protection code; deploys the inserted source code on an Ethereum simulation environment, tests and obtains a safe path set, and then deploys the source code added to the safe path set to the Ethereum main network; traces the source code based on the path encoding recorded in the smart contract log in the Ethereum main network in combination with the control flow graph and probe information; thereby accurately tracking the cyclic and acyclic execution paths of the smart contract, improving the detection accuracy, reducing the execution Gas overhead, and tracing the abnormal source code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention belongs to the field of information technology and relates to a method for detecting and protecting unknown threats to blockchain smart contracts based on path analysis and code instrumentation. Background Art

[0002] A smart contract is essentially a program code written in a Turing-complete language. It is deployed and executed on a blockchain platform, ensuring transparency and immutability. Ethereum, as a platform combining blockchain and smart contracts, marks the beginning of the "Blockchain 2.0" era. Smart contracts have become a focus of attention for experts in this field. Compared to other programs, smart contracts, which hold significant economic value, are more vulnerable to hacker attacks. From a code development perspective, as human-written program code, smart contracts may contain logic vulnerabilities and other issues, resulting in significant economic losses. Since smart contracts cannot be modified after deployment, security risks will prevent them from running safely and require redeployment, leading to a series of risks such as wasted resources. Furthermore, the high coupling between smart contracts can lead to unexpected security issues. Ethereum smart contracts are written in Solidity and run within the Ethereum Virtual Machine (EVM). The resource consumed by contract code execution is gas.

[0003] As the number of smart contracts increases, security threats to blockchain smart contracts are becoming increasingly prominent. These threats have severely damaged the ecological stability of the blockchain contract layer. Therefore, effectively detecting security threats to blockchains has become a critical issue that needs to be addressed urgently.

[0004] Research at home and abroad on known threat detection technologies for blockchain smart contract security primarily focuses on symbolic execution, fuzz testing, and formal verification. Representative research using symbolic execution includes Oyente [Making smart contracts smarter], while research using fuzz testing includes Harvey [Harvey: A greybox fuzzer for smart contracts]. Detection methods based on formal verification include Securify [Securify: Practical security analysis of smart contracts] from ETH Zurich. These known vulnerability detection methods require predefined vulnerability patterns, are unable to detect unknown vulnerabilities, and are incapable of implementing security detection and protection after contract deployment.

[0005] To detect unknown threats in smart contracts, Zhang et al. proposed the vulnerability detection tool Multi-Object Detection Neural Network (MODNN). This tool extracts key opcode sequences, extracts implicit features from these sequences through a co-occurrence matrix, and outputs multiple vulnerabilities in parallel as probabilities. Using implicit features and a multi-objective detection algorithm, MODNN identifies more unknown types. MODNN does not require expert or predefined knowledge, which increases model scalability and reduces training time. However, this method still has low accuracy in detecting unknown threats. VSCL (automating vulnerability detection in smart contracts with deep learning), proposed by Mi et al., is a smart contract vulnerability detection framework that combines metric learning with deep neural networks. It leverages static features of smart contract bytecode and employs a deep neural network with metric learning to detect vulnerabilities. It labels all vulnerable contract samples as positive, while labeling safe samples as negative. By learning from known threats, it can discover potentially similar unknown threats. However, this method cannot detect vulnerability types that are distinct from known and unknown vulnerabilities, and is limited in its ability to detect unknown vulnerabilities by relying on patterns in known vulnerabilities. Huang et al. from Renmin University of China [Hunting vulnerable smart contracts via graph embedding based bytecode matching] proposed a graph embedding method for smart contract bytecode matching to identify unknown vulnerabilities. This method unifies bytecode by performing data and instruction-level normalization, tracks data flow and control flow to implement slicing of different contracts, and uses an unsupervised graph embedding algorithm to vectorize the code graph of the normalized slices and measure vector similarity to achieve matching detection by extrapolating known vulnerabilities to unknown vulnerabilities. This method uses slicing to detect vulnerabilities caused by improper manipulation of external data, but it cannot detect certain vulnerabilities when they cannot be described by a single slice of a function. Finally, none of the above unknown threat detection methods can achieve threat detection and protection after smart contracts are deployed.

[0006] Existing methods that use path analysis technology for post-deployment contract security testing include ContractGuard [ContractGuard: Defend Ethereum smart contracts with embedded intrusion detection] and EtherProv [EtherProv: Provenance-aware detection, analysis, and mitigation of Ethereum smart contract security issues].

[0007] ContractGuard, proposed by Wang et al., is the first intrusion detection system for smart contracts. It constructs a control flow graph from Ethereum Virtual Machine (EVM) bytecode, uses the Efficient Path Profiling (EPP) algorithm to encode context-free paths, and implements rollback of abnormal transactions through safe path comparison. ContractGuard instrumentes contract bytecode to enable post-deployment detection and protection. However, because it targets contract bytecode, it is difficult to locate the source code of vulnerabilities and has a high execution overhead. Furthermore, ContractGuard cannot accurately track loop paths and is therefore unable to address security threats caused by these loops.

[0008] The EtherProv method proposed by Linoy et al. also encodes the contract control flow graph using the EPP algorithm and adds path probes using source code instrumentation. To enable subsequent security analysis and debugging, EtherProv publishes corresponding Datalog rules for its traceability database. EtherProv handles loops by emitting a loop path each time the loop passes through it. The number of loop executions can be tracked in the traceability database. However, when dealing with contracts with loop paths, it needs to repeatedly emit events, which has a high gas overhead. In addition, although EtherProv can track the number of loop paths, its post-deployment protection strategy is still based on acyclic path encoding and cannot effectively protect against threats existing in cyclic paths. Finally, because it cannot support modifiers and abstract contracts in the source code, its execution success rate is low and its versatility is poor when dealing with real-world contracts.

[0009] In summary, most existing security threat perception methods still require pre-defined specific vulnerability patterns and are unable to accurately detect and protect against unknown vulnerabilities after smart contracts are deployed. Existing methods for detecting and protecting against unknown threats to smart contracts after deployment also have problems such as high false positive rates, poor versatility, inability to locate vulnerable code, and excessive gas consumption. Therefore, realizing unknown threat detection and protection for blockchain smart contracts remains a difficult point in current smart contract security threat research. Summary of the Invention

[0010] The purpose of the present invention is to overcome the shortcomings and deficiencies of the prior art and provide a security detection and protection method that can be implemented after the deployment of a smart contract. This method can accurately track the cyclic and acyclic execution paths of the smart contract, trace the source code of the problematic contract through the control flow graph information, and has low additional gas overhead. The present invention encodes and inserts the smart contract path to obtain the precise contract execution path, and obtains the safe path through testing in an Ethereum simulator environment. The safe path set obtained from the test is added to the contract. By comparing the control flow path of each contract execution with the safe path, the unknown threat detection and protection against triggering abnormal control flow is realized.

[0011] To achieve the above object, the technical solution of the present invention is as follows:

[0012] A smart contract threat detection and protection method based on path analysis and code instrumentation, comprising the following specific steps:

[0013] Step S1: Preprocess the smart contract source code using a regular expression method to generate standardized smart contract source code; specifically, the following steps are performed:

[0014] Use regular expressions to remove all code comments from the smart contract source code;

[0015] Use regular expressions to remove all tab indentations from the smart contract source code;

[0016] Read all the modifier definitions and the functions modified by the modifiers from the smart contract source code, split the modifier definitions using regular expressions, and add the code in the modifier to the modified function code according to the variables passed in the modifier definitions;

[0017] Read all require functions in the smart contract source code and replace them with synonymous if and revert methods; read all if conditional statements in the smart contract source code and add else branches to all if statements without else branches.

[0018] Step S2: Based on the static single assignment form nodes obtained by the static analysis of the source code using the smart contract static analysis tool, a smart contract control flow graph is constructed; specifically, the following steps are included:

[0019] Performing static analysis on the smart contract source code using a smart contract static analysis tool, and constructing a smart contract control flow graph using static single assignment form nodes obtained by the static analysis;

[0020] Add unique entry and exit nodes to the control flow graph, and add call edges between smart contracts;

[0021] The control flow graph is modified to remove nodes representing repeated code segments and orphan nodes that cannot be called.

[0022] Step S3: Using the smart contract control flow graph, dynamically selecting a path analysis algorithm to encode the path, obtaining probe statements and edges to be inserted, and saving the control flow graph information and probe information; specifically, including:

[0023] Traverse the smart contract control flow graph to find out whether there is a back edge;

[0024] Apply the PAP path analysis algorithm to the control flow graph with loop edges, calculate the number of incoming edges of each node, and obtain the edges to be inserted with a number of incoming edges greater than 1 and the probe statements of the corresponding edges;

[0025] Apply the EPP path analysis algorithm to the control flow graph without loop edges, calculate the probe increment of each edge according to the reverse topological order of the control flow graph, and obtain the probe statement;

[0026] Traverse all paths in the control flow graph without loops, save the encoding of each path, and save the control flow graph nodes and corresponding source code location information;

[0027] For a control flow graph with a loop, number all nodes connected to the exit node, save the last node number, save the control flow graph nodes and the corresponding source code location information, and save the probe statements and the edge information to be inserted.

[0028] Step S4: instrumenting the source code based on the probe statement of the edge to be instrumented, and inserting the initialization definition code of the probe state variables and path tracing events, as well as the safety path protection code; specifically including:

[0029] Based on the probe statement and the edge to be inserted, the probe is mapped to the node connected to the edge to be inserted, and the probe statement is inserted into the location of the source code to which the node belongs;

[0030] For functions that are called using the call method, add a calling context state variable to detect unexpected callbacks;

[0031] For smart contracts that have inter-function calls and where the called functions allow external messages to be called by smart contracts, add function tag state variables;

[0032] A unique constant number is assigned to each function that can be called externally. When the smart contract is executed, the number of the function being called externally will be assigned to the variable. The path will be reported and the probe variable value will be restored only when the execution of the externally called function is completely completed, that is, when the current end function number is equal to the variable.

[0033] Insert the initialization definition code of the probe state variables, path reporting events, safe path collection, and security protection code into the source code. In particular, for the case of multiple inheritance smart contracts, establish a separate Path smart contract containing the initialization definition, and have other smart contracts inherit this Path smart contract to implement parameter transfer between smart contracts;

[0034] Convert the path encoding value saved in the probe variable into a string through a function, and then use it as the parameter of the revert rollback function. Insert the value-to-string function into the smart contract source code.

[0035] Step S5: Deploy the instrumented smart contract source code on the Ethereum simulation environment, design security test cases and input them into the instrumented smart contract, obtain a set of security path codes, and then deploy the instrumented smart contract that has been added to the security path set to the Ethereum mainnet. This specifically includes:

[0036] Deploy the instrumented smart contract source code on Ganache, an Ethereum simulation environment. Smart contract administrators design security test cases, or the program automatically generates test cases based on security rules. These are input into the smart contract in the simulation environment, and a set of security paths is obtained through Ethereum logs.

[0037] The measured safe path set is added to the initialization definition part of the safe path in the smart contract after the stub is inserted, and the smart contract is deployed to the Ethereum main network for operation.

[0038] Step S6: Tracing the source based on the events reported by the instrumented smart contract in the Ethereum mainnet and the returned path code, combined with the saved control flow graph information; specifically including:

[0039] Based on the Ethereum mainnet transaction log, track the abnormal control flow path code reported by the smart contract after the stub;

[0040] For a cyclic graph, the path code is input into the traceability program, and the path traceability is performed based on the stored probe variable information, and the execution path and the source code location of each node in the path are output;

[0041] For acyclic graphs, the path and the source code location of each node in the path are directly output according to the path encoding.

[0042] The present invention has the following advantages and effects compared to the prior art:

[0043] 1. This invention improves its applicability in real environments by optimizing the effects of modifiers and require functions on probe code instrumentation, addressing issues such as abstract contract calls and control flow graph construction of super-inherited contracts. Compared with existing methods, the execution success rate is significantly improved, making it more versatile.

[0044] 2. This invention dynamically selects EPP and PAP as contract path encoding algorithms, enabling precise tracking of both looping and non-looping contract execution paths. Because some vulnerabilities exist within loops, whether in inter-function loops or intra-function loops, existing methods are unable to accurately protect against these loops. Furthermore, because this method uniquely encodes loop paths, it eliminates the need for repeated event generation, reducing loop path tracking overhead.

[0045] 3. The present invention is aimed at smart contract source code instrumentation, so the detailed process of cyclic and acyclic path execution and the corresponding source code location can be obtained through the path tracing algorithm in the present invention. BRIEF DESCRIPTION OF THE DRAWINGS

[0046] Figure 1 Flowchart of the present invention;

[0047] Figure 2 This is a schematic diagram of the control flow graph of a non-intelligent contract of the present invention;

[0048] Figure 3 This is a flow chart of the EPP algorithm;

[0049] Figure 4 This is a schematic diagram of the PAP algorithm encoding results;

[0050] Figure 5 This is a schematic diagram of the proportion of Gas expenses in executing the present invention. DETAILED DESCRIPTION

[0051] The present invention is described in detail below with reference to the accompanying drawings and embodiments.

[0052] Example 1

[0053] This embodiment provides a smart contract threat detection and protection method based on path analysis and code instrumentation. The process is as follows: Figure 1 As shown, the following steps are included:

[0054] Step S10: Preprocessing the smart contract source code using a regular expression method to generate a standardized smart contract source code;

[0055] Step S20: Constructing a smart contract control flow graph based on the static single assignment form nodes obtained by static analysis of the source code using a smart contract static analysis tool;

[0056] Step S30: Using the smart contract control flow graph, dynamically selecting a path analysis algorithm to encode the path, obtaining probe statements and edges to be inserted, and saving the control flow graph information and probe information;

[0057] Step S40: instrumenting the source code based on the probe statement of the edge to be instrumented, and inserting initialization definition code of probe state variables and path tracing events, as well as safety path protection code;

[0058] Step S50: Deploy the instrumented smart contract source code on an Ethereum simulation environment, design security test cases and input them into the instrumented smart contract, obtain a security path code set, and then deploy the instrumented smart contract that has been added to the security path set to the Ethereum mainnet;

[0059] Step S60: Tracing the source based on the events reported by the plugged smart contract in the Ethereum mainnet and the returned path code, combined with the saved control flow graph information.

[0060] Wherein, the step S10 specifically includes:

[0061] Step S11: First, filter out the contract files that cannot be compiled, and use regular expressions to replace tab indents with spaces. For contract comments, use regular expression replacement to remove all comments.

[0062] Step S12: Due to the special syntax of modifiers in Solidity, as shown in Code 3-1, the "_;" part refers to the code modified by the modifier. The function modified by the modifier can execute the code in the order of the modifier, which facilitates the reuse of the contract code. Obviously, when multiple functions are modified by the same modifier, the location of the code stub will be ambiguous and a unique code cannot be obtained. Therefore, this embodiment uses Slither to analyze the obtained abstract syntax tree to determine the modifier code and the function modified by the modifier. Then the modifier content is parsed into the corresponding function code;

[0063] 3-1 Solidity Modifier Example

[0064]

[0065] Step S13: This embodiment handles the require function separately. In Solidity, require is a function used to handle errors. When the require parameter is False, the contract execution is directly rolled back. As shown in Code 3-2, the two methods have exactly the same effect. Since require includes a revert function, and this embodiment cannot insert code into the built-in require function, this embodiment uses the if statement in Code 3-2 to replace all require functions.

[0066] 3-2 Different forms of require

[0067]

[0068] Step S14: To facilitate the subsequent insertion of if conditional statements, this embodiment uses the abstract syntax tree obtained through Slither analysis to judge all if conditions, adds else statements to all if conditions that do not contain else branches, and standardizes all for loops and function definitions.

[0069] The step S20 specifically includes:

[0070] Step S21: First, construct a control flow graph based on the standardized source code obtained in step S10. Static single assignment nodes are obtained through static analysis using the Slither tool. Each node is traversed and a control flow graph is constructed based on node attributes and relationships between nodes.

[0071] Step S22: adding a unified entry node (ENTRY) and exit node (EXIT) to the control flow graph obtained in step S21;

[0072] Step S23: Expand the constructed control flow to represent the call relationships within and between contracts. Traverse all functions including the contract construction function to check whether there are external calls. If so, add new edges to the control flow graph to represent their call relationships. In this process, this embodiment does not add new call edges to abstract contracts, because the functions of abstract contracts can lack implementation and are only used to describe the contract and contract inheritance.

[0073] Step S24: Remove nodes with the same source code location information and remove orphan nodes that cannot be reached in the control flow graph, such as variables of the construction function. Finally, the control flow graph is obtained, such as Figure 2 shown.

[0074] The step S30 specifically includes:

[0075] Step S31: traverse the control flow graph to find out whether there is a back edge to determine whether there is a loop in the control flow graph. The dynamic determination of which instrumentation algorithm to use is based on whether there is a loop.

[0076] Step S32: Apply the EPP algorithm to the acyclic graph to obtain the edges that need to be plugged and the probe variable values ​​of the edges. Assign a number to each edge so that the sum of each path is a unique code;

[0077] Next, the algorithm assigns a non-negative constant value Val(e) to each edge e in the directed acyclic graph, requiring that the sum of the values ​​on any path from ENTRY to EXIT is unique. In addition, the path sum should be in the range of (0, number of paths - 1), so that the assignment result is minimal. The algorithm calculates such a Val relationship by visiting the vertices of the directed acyclic graph in reverse topological sequence. It is necessary to ensure that all successor nodes of node v are visited before v itself. The value associated with each node v is NumPaths(v), which records the number of paths from v to the exit node. At v, the algorithm visits all outgoing edges v→w of v. i , 1≤i≤n, and assign a value to the kth outgoing edge.

[0078] Since acyclic graphs have no loop edges, the encoded control flow graph is traversed to obtain all path encodings, and information such as node sequence and source code location is recorded in the Graph_Details.json file.

[0079] The specific acyclic path coding algorithm is shown in Algorithm 1

[0080]

[0081] In this embodiment, Figure 3 (a) Apply the EPP algorithm to the graph in the figure, and the edge value is Figure 3 As shown in (b), finally, the probe Figure 3 (c)

[0082] Step S33: Apply the PAP algorithm to the cyclic graph to obtain the edges that need to be inserted and the probe variable values ​​of the edges.

[0083] PAP combines multiplication and addition to ensure that different paths correspond to different encoding results. The algorithm uses a sequence of nodes in the control flow graph to represent the path, and distinguishes specific paths by different inbound edges of the same node. The encoding of a looped path is shown in Algorithm 2. The algorithm traverses the nodes. If the in-degree of a node is greater than 1, the in-degree is multiplied by the probe variable and the inbound edge number is added. The probe variable is Val in Algorithm 2, the in-degree is s in Algorithm 2, and the inbound edge number is i in Algorithm 2.

[0084] Storing data such as the last node number, source code location, probe statement, edge and corresponding node in the Graph_Details.json file can provide support for subsequent path tracing.

[0085] The cyclic path coding algorithm is specifically shown in Algorithm 2

[0086]

[0087]

[0088] In this embodiment, the results of applying the PAP algorithm are as follows: Figure 4 shown.

[0089] The step S40 specifically includes:

[0090] Step S41: For acyclic control flow graphs, this embodiment corresponds the probe increment to a specific code position and performs instrumentation on the source code. If the probe variable corresponding to the edge has an increment, the instrumentation code of this embodiment is: _val = _val + _inc; here _inc is the increment corresponding to the edge, and _val is the probe variable. If the node pointed to by the edge is an EXIT node, the instrumentation code is: emit_path(_val,-1,_tex); _val = 0; where _path is the event reporting the path, -1 means that the path reported by the log is an acyclic graph, and _tex is the function call context information. In order to reduce the detection overhead, this embodiment uses event events with lower gas overhead to report path information. It should be noted that _tex is a variable added to prevent accidental function calls to record function call context information. For all functions with external calls in the call series, this embodiment increments _tex at the start position of the function call and decrements _tex at the end position of the function execution. After the event is issued, _tex is set to 0, that is, when the reported _tex is not 0, there is an unexpected function callback;

[0091] Step S42: If there is a loop in the control flow graph, the PAP algorithm with higher overhead but accurate tracking is used to encode the contract control flow graph. First, this embodiment calculates the in-degree of each node and records the in-degree on each node. Then the PAP algorithm is applied to add a probe for each incoming edge. To facilitate subsequent path tracing, this embodiment numbers the last node of each connected exit node and emits it in the event. At this time, if the node pointed to by the edge is not the EXIT node, the code for the insertion is: _val = _val*s+i; here s is the in-degree, i is the sequence number of the incoming edge, and _val is the probe variable value. If the node pointed to by the edge is the EXIT node, the code for the insertion is: _val = _val*s+i; emit_path(_val, last_node_id, _tex); _val = 0; here, the meanings of _path, _tex, and _val are the same as those of the acyclic path, and last_node_id is the last node number, which is a constant during actual insertion. In fact, when the administrator only needs to perform path detection without rollback protection, the final _val = _val * s + i can be removed to reduce the reading and writing of state variables and reduce gas consumption. When the node pointing to the loop condition is a loop condition, the loop condition will be judged first, and then whether to execute the probe will be determined.

[0092] Step S43: After this embodiment completes the insertion of all probes, it then inserts other locations in the contract, such as the initialization of the probe state variable _val, the function call context variable _tex, the event _path, and the safe path safe_paths. This embodiment will initialize the variables in the inherited parent function. If there is multiple inheritance, this embodiment will establish a Path contract and have other contracts inherit this Path contract to implement parameter passing between contracts. In addition, to accommodate the problem of inter-function calls, and when the called function allows external contract message calls, this embodiment adds the variable _func_id to this type of contract function. At this time, each function that can be called externally has a unique number. When the contract is executed, the function number of the external call will be assigned to _func_id. The path will be reported and the probe variable value will be restored only when the execution of the externally called function is completely completed, that is, when the current end function number is equal to _func_id. In addition, in Solidity, the rollback function cannot pass numerical variables to issue path codes, and Solidity does not support direct numerical type conversion to string. Therefore, this embodiment needs to convert the path value into a string through a function as a parameter of the revert function. The protection codes for string type conversion and safe path determination in this embodiment are shown in Code 3-3 and Code 3-4 respectively. Finally, this embodiment completes the instrumentation of the contract source code.

[0093] 3-3Solidity integer to string function

[0094]

[0095] 3-4 Safe Path Protection Code

[0096]

[0097] The step S50 specifically includes:

[0098] After the contract is instrumented, this embodiment deploys the contract to the Ethereum simulator Ganache and tests the contract to obtain a set of secure paths. It is worth noting that testing at this stage will not cause actual gas consumption on the Ethereum mainnet. Therefore, this embodiment should make as detailed a test of the secure path set as possible at this stage. In addition to test cases manually written by the contract administrator, this embodiment tests the contract by automatically generating random test cases under security rules through code. After the contract has been deployed on the Ethereum mainnet, the administrator can also add a new secure path set through the function in the contract. The function of adding a secure path is shown in Code 3-5. This embodiment uses the mapping type to store secure paths because it has a smaller gas overhead when searching for values ​​than a variable-length array.

[0099] 3-5 Add code to the security path

[0100]

[0101] The step S60 specifically includes:

[0102] Track the path code of the log report of the instrumented contract on the Ethereum mainnet. If the log report path is not in the safe path set, it triggers an abnormal control flow and causes the transaction to roll back. The contract administrator can perform path backtracking through the path value of the transaction log report. Among them, if it is an acyclic graph, backtracking only needs to compare the path number recorded in the graph information json file recorded in step S32. If it is a cyclic graph, the cyclic path backtracking program needs to be applied, as shown in Algorithm 3. The path backtracking reads the contract json file recorded in step S33 to obtain the control flow graph information, and finally derives the path sequence and path source code;

[0103]

[0104] Compared with the prior art, this embodiment has the following beneficial effects:

[0105] 1. Execution success rate

[0106] By optimizing the impact of decorators on the code, handling abstract contract call issues and super inheritance contract files, etc., the applicability in real environments is improved, and it has a significant improvement compared to the existing open source EtherProv work.

[0107] method Number of successes Number of failures Success rate (%) The present invention 933 67 93.30% EtherProv 256 744 25.60%

[0108] 2. Vulnerability Detection

[0109] Using the experimental data published by ContractGuard, four existing vulnerable contracts were tested. The test data contained 100 test cases for each vulnerability sample, and each test case contained 99 normal transactions and 1 vulnerable transaction. At the beginning of the experiment, the security path was empty, and normal transactions in the test cases were gradually added to the security path set. The final experimental results are shown in the table. The final results show that the present invention has a lower false alarm rate under the same conditions. The present invention is not limited to these known types of attack modes. As long as unknown threats can constitute abnormal control flow paths, they can be detected. In particular, some vulnerabilities exist in loops. Regardless of whether the loop is a function loop call or a loop execution in a function, existing methods such as ContractGuard cannot achieve accurate tracking of the loop. Therefore, the present invention has a higher accuracy rate for unknown threat detection.

[0110]

[0111] 3. Gas consumption ratio

[0112] The present invention performs tests on 3731 contracts to verify the Gas cost, and the additional Gas cost accounts for Figure 5 As shown, the average additional gas cost of the present invention during contract execution is 23.94%, compared to ContractGuard's average runtime overhead of 28.27%. The present invention significantly reduces the average additional gas cost during execution. In the present invention, probe variable changes use basic statements, and path tracking logs are emitted through contract events during threat detection, resulting in lower execution gas consumption. During threat protection, the present invention rolls back transactions using the revert function, enabling the return of path results without deducting gas.

Claims

1. A smart contract threat detection and protection method based on path analysis and code instrumentation, characterized in that: The method comprises the following specific steps: Step S1: Preprocess the smart contract source code using a regular expression method to generate a standardized smart contract source code; Step S2: Constructing a smart contract control flow graph based on the static single assignment form nodes obtained by static analysis of the source code using a smart contract static analysis tool; Step S3: Using the smart contract control flow graph, dynamically select a path analysis algorithm to encode the path, obtain probe statements and edges to be inserted, and save the control flow graph information and probe information; Step S4: instrumenting the source code based on the probe statement of the edge to be instrumented, and inserting the initialization definition code of the probe state variable and the path tracing event, as well as the safety path protection code; Step S5: Deploy the instrumented smart contract source code on the Ethereum simulation environment, design security test cases and input them into the instrumented smart contract, obtain a security path code set, and then deploy the instrumented smart contract that has been added to the security path set to the Ethereum mainnet; Step S6: Tracing the source based on the events reported by the plugged smart contract in the Ethereum mainnet and the returned path code, combined with the saved control flow graph information.

2. The smart contract threat detection and protection method based on path analysis and code instrumentation according to claim 1 is characterized in that: The step S1 specifically includes: Use regular expressions to remove all code comments from the smart contract source code; Use regular expressions to remove all tab indentations from the smart contract source code; Read all the modifier definitions and the functions modified by the modifiers from the smart contract source code, split the modifier definitions using regular expressions, and add the code in the modifier to the modified function code according to the variables passed in the modifier definitions; Read all require functions in the smart contract source code and replace them with synonymous if and revert methods; Read all if conditional statements in the smart contract source code and add else branches to all if statements without else branches.

3. The smart contract threat detection and protection method based on path analysis and code instrumentation according to claim 1 is characterized in that: The step S2 specifically includes: Performing static analysis on the smart contract source code using a smart contract static analysis tool, and constructing a smart contract control flow graph using static single assignment form nodes obtained by the static analysis; Add unique entry and exit nodes to the control flow graph, and add call edges between smart contracts; The control flow graph is modified to remove nodes representing repeated code segments and orphan nodes that cannot be called.

4. The smart contract threat detection and protection method based on path analysis and code instrumentation according to claim 1 is characterized in that: The step S3 specifically includes: Traverse the smart contract control flow graph to find out whether there is a back edge; Apply the PAP path analysis algorithm to the control flow graph with loop edges, calculate the number of incoming edges of each node, and obtain the edges to be inserted with a number of incoming edges greater than 1 and the probe statements of the corresponding edges; Apply the EPP path analysis algorithm to the control flow graph without loop edges, calculate the probe increment of each edge according to the reverse topological order of the control flow graph, and obtain the probe statement; Traverse all paths in the control flow graph without loops, save the encoding of each path, and save the control flow graph nodes and corresponding source code location information; For a control flow graph with a loop, number all nodes connected to the exit node, save the last node number, save the control flow graph nodes and the corresponding source code location information, and save the probe statements and the edge information to be inserted.

5. The smart contract threat detection and protection method based on path analysis and code instrumentation according to claim 1 is characterized in that: The step S4 specifically includes: Based on the probe statement and the edge to be inserted, the probe is mapped to the node connected to the edge to be inserted, and the probe statement is inserted into the location of the source code to which the node belongs; For functions that are called using the call method, add a calling context state variable to detect unexpected callbacks; For smart contracts that have inter-function calls and where the called functions allow external messages to be called by smart contracts, add function tag state variables; A unique constant number is assigned to each function that can be called externally. When the smart contract is executed, the function number of the externally called function will be assigned to the variable. The path will be reported and the probe variable value will be restored only when the execution of the externally called function is completely completed, that is, when the current end function number is equal to the variable. Insert the initialization definition code of the probe state variables, path reporting events, safe path collection, and security protection code into the source code. In particular, for the case of multiple inheritance smart contracts, establish a separate Path smart contract containing the initialization definition, and have other smart contracts inherit this Path smart contract to implement parameter transfer between smart contracts; Convert the path encoding value saved in the probe variable into a string through a function, and then use it as the parameter of the revert rollback function. Insert the value-to-string function into the smart contract source code.

6. The method for detecting and protecting smart contract threats based on path analysis and code instrumentation according to claim 1, wherein: The step S5 specifically includes: Deploy the instrumented smart contract source code on Ganache, an Ethereum simulation environment. Smart contract administrators design security test cases, or the program automatically generates test cases based on security rules. These are input into the smart contract in the simulation environment, and a set of security paths is obtained through Ethereum logs. The measured security path set is added to the initialization definition part of the security path in the smart contract after the stub is inserted, and the smart contract is deployed to the Ethereum main network for operation.

7. The smart contract threat detection and protection method based on path analysis and code instrumentation according to claim 1 is characterized in that: The step S6 specifically includes: Based on the Ethereum mainnet transaction log, track the abnormal control flow path code reported by the smart contract after the stub; For a cyclic graph, the path code is input into the traceability program, and the path traceability is performed based on the stored probe variable information, and the execution path and the source code location of each node in the path are output; For acyclic graphs, the path and the source code location of each node in the path are directly output according to the path encoding.