Solidiity smart contract standard repair method
By converting smart contract programs into abstract syntax trees and control flowcharts, using the z3 solver to verify the consistency of specifications and programs, and providing automated repair tools, the technical gaps in smart contract specification verification and repair are solved, improving the efficiency and accuracy of contract development, and reducing the risk of error vulnerabilities.
Patent Information
- Application Number
- CN202410086285.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-01-22
- Publication Date
- 2025-07-25
AI Technical Summary
The existing technology lacks smart contract specification verification tools, cannot automatically verify the consistency of contract specifications and procedures, and lacks methods to automatically fix inconsistent specifications, resulting in developers needing inefficient and error-prone to manual writing.
Using SMT solution based on satisfaction theory, smart contract programs are transformed into abstract syntax trees and control flow charts, the z3 solver is used to verify the consistency between the specification and the program, and repair inconsistent specifications through quantifier elimination and graph editing distance, providing automated tools for precondition repair, postcondition repair and function call repair.
Automatic verification and repair of smart contract specifications is realized, the efficiency and accuracy of contract development is improved, manual intervention is reduced, the consistency and correctness of contracts are ensured before deployment, and the risk of errors and vulnerabilities is reduced.
Smart Images

Figure CN120372614A_ABST
Abstract
Description
Technical Field
[0001] The present invention mainly relates to the fields of software engineering and software testing, and particularly to a comprehensive method for verifying and repairing Solidity smart contract specifications. Background Art
[0002] Smart contracts are programs executed on the blockchain and are widely used in various industries and fields such as finance, healthcare, supply chain, Internet of Things, and government affairs processing. Even a tiny error in a smart contract can lead to huge digital asset losses. There have been many such incidents in the past, resulting in significant economic losses. More importantly, due to the immutability of the blockchain being one of its fundamental characteristics, once developers deploy a smart contract, it cannot be repaired. In other words, once a smart contract is deployed online, the errors in it will exist permanently, making the contracts deployed by developers vulnerable and prone to attacks, thus leading to significant losses. Therefore, before deployment, developers must ensure the correctness of smart contracts and ensure that the contract code is accurate and error-free. Thus, it is necessary to verify the correctness of smart contract programs. Effective smart contract verification tools to ensure the correctness of contract programs play an important role in the deployment and use of smart contracts. Smart contract specifications are widely used to assist in the verification of contract correctness, and the specifications play a guiding role in the correctness verification. Smart contract specifications are artificially formulated by developers and can adopt various different logics to ensure the correctness and rationality of the specification language. Over the years, various forms of specification language logics have been developed to strictly reason and verify the correctness of smart contracts and are widely used in verifying the correctness of programs. Specification language logic is a proof logic with a set of formal rules that can be used for static verification of the behavior of programs. Some commonly used specification language logics include Hoare logic, rewrite logic, and reachability logic, which have been used to prove the correctness conditions of smart contracts. The Hoare-style specifications of smart contracts include preconditions, postconditions, and invariants defined for its functions, loops, and the overall contract. The predicates in these specification statements can cover storage and memory variables, environmental variables that capture block or transaction information, and events and operations emitted during execution. Currently, specification languages based on Hoare logic have been widely used in correctness verification tools. Whether it is static program verification or dynamic verification, specification languages based on Hoare logic are being used. For example, the MVP specification is a specification used in the Move language and is also a complete specification language designed based on Hoare logic. It accurately describes the behavior of functions by setting preconditions, postconditions, and a series of invariant information. Similarly, the JML specification is a specification language used for Java programs and can be used for logical reasoning of Java programs. Solidity contracts also have similar uses of specifications based on Hoare logic, such as tools like solc-verify and Solythesis. However, these specifications based on Hoare logic can indeed accurately describe the behavior of functions. But these specifications are artificially defined and may be incorrect. Inaccurate specifications will verify programs with code errors, resulting in a reduced credibility of program correctness.Meanwhile, there is currently no tool that can verify the consistency between contract specifications and programs, that is, there is a lack of tools for verifying the correctness of contracts. Secondly, there is also a lack of a tool for automatically repairing and completing contract specifications. Currently, the writing of contract specifications still requires developers to precisely read the program code to write the corresponding contract specifications, which is inefficient and cumbersome.
[0003] In the process of implementing the present invention, the inventors found the following disadvantages and deficiencies in the prior art:
[0004] 1. Lack of a smart contract specification verification tool to assist developers in verifying the consistency between smart contract specifications and programs.
[0005] 2. Lack of a tool that can automatically generate and complete smart contract specifications. Developers need to carefully understand the function program to write consistent smart contracts. Manually writing smart contracts is inefficient and may be error-prone.
[0006] 3. Lack of a method and tool to automatically repair inconsistent smart contract specifications. Summary of the Invention
[0007] In order to fill the gap in technical tools for the verification and repair of smart contract specifications, the present invention proposes a smart contract specification verification and repair method based on satisfiability theory SMT solving. The aim is to solve the problem of the lack of corresponding verification methods and repair methods for smart contract specifications. The present invention first proposes to parse Solidity smart contract programs and smart contract specifications into abstract syntax trees and control flow graphs, and verify the consistency between the specifications and the programs by means of solving with the z3 solver, and the purpose of repairing inconsistent specifications by means of quantifier elimination and graph edit distance.
[0008] A method for repairing Solidity smart contract specifications, the method comprising:
[0009] Step 1: Use the Slither tool to convert smart contract specifications and program code into abstract syntax trees (ASTs);
[0010] Step 2: Construct a control flow graph (CFG) for the inside of the function;
[0011] Step 3: Convert the control flow graph and function specification nodes of each function into SMT expressions;
[0012] Step 4: Input the SMT expressions obtained for each function into the z3 solver for satisfiability solving. Determine whether the specification of the function is consistent with the program logic according to the solving result;
[0013] Step 5: For an inconsistent smart contract specification, the present invention provides three repair methods, namely precondition repair, postcondition repair, and function call repair;
[0014] As Figure 1 shown, it is a flowchart of the present invention for contract specification verification and repair. The method specifically includes the following processes:
[0015] Step 1: Taking a Solidity program with a contract specification (as Figure 2 shown) as input, the present invention will first use the Slither tool to transform the specification and the Solidity program into an Abstract Syntax Tree (AST), and construct a Control Flow Graph (CFG) for each function. In the CFG, each node represents a basic block of one or more instructions, and the edges between nodes represent the control logic between different basic blocks. Then the present invention verifies the specification and the program in units of functions. The present invention will encode the control flow graph of the function and the function specification into SMT expressions. The contract specification is set based on the specification set by Hoare logic, mainly placed above the function code in the form of comments. The Hoare logic specification consists of a precondition and a postcondition. The meaning of this specification is that if the parameters passed into the function satisfy the precondition, then the result obtained after successfully executing the function must satisfy the postcondition. That is, the contract specification can describe the global attribute state before and after the function execution, and the changes in the input parameters and output results, and can clearly reflect the execution situation of the function, which can help developers quickly understand the role of the function without having to carefully read the program logic code. Figure 2 The content in the ensures part in
[0016] is a contract specification based on Hoare logic. i , s i ) that accepts a pre-state σ i , an execution statement s i as input, and outputs the resulting post-state σ k。For a function m(v) = s that may contain loops and internal and external function calls, the smart contract specification verification process is described as follows. If a contract specification ensures(p, q) is verified consistently on the function implementation s, then when post(p / \!rev, s) returns σ, σ => q holds. Where post(p / \!rev, s) represents starting from the pre-state p before function execution and the default rollback condition false during the encoding process. After the function s is executed, the verification formula σ => q means that if the function does not roll back, the encoding starting from p can satisfy the post-condition q. That is to say, the specification ensure(p, q) of the function s is consistent with the function program s. That is, taking the pre-condition p as the input state of the function program, after successfully executing the function s without rollback during the execution process, the state after executing the function must satisfy the post-condition q. There will be no counterexample such that there is an execution path that gets a result inconsistent with the post-condition q after successfully executing the function s while satisfying the pre-condition p.
[0017] Step 3: For the specifications with inconsistent verification results, repairs are required, and the types of repairs are roughly divided into two categories:
[0018] 1. (Providing missing specification conditions). During the process of developing function specifications, usually developers will first write the pre-condition or the post-condition, and then continue to write the other condition. In this case, the present invention demonstrates how the smart contract repair tool can help developers write correct and general specifications. Figure 2Shows the underlying logic of the function transfer extracted from the smart contract BAT. This function allows the transfer of tokens between two users. The postcondition specifies that the balances of the sender and the receiver are increased and decreased by the same amount respectively. A common incorrect precondition is as follows: balances[msg.sender] >= _value && _value > 0. This precondition ensures that only the branch where the if statement on line 8 is true is executed. Although this precondition seems reasonable, it is actually incorrect. Consider the case where the sender and the receiver are the same person (i.e., msg.sender == _to). When _value > 0, there will be a counterexample to the postcondition, that is, there exists an execution path whose execution result is inconsistent with the result set by the postcondition. In contrast, the smart contract specification repair tool infers based on the control flow graph of the contract function and can effectively generate a general precondition suggestion as follows: (balances[msg.sender] >= _value && msg.sender != _to) || (_value == 0). Intuitively, the present invention can divide the precondition into two cases: the first case indicates that the transfer should not be a self-transfer, that is, the sender and the receiver should be different entities (i.e., msg.sender != _to). The second case indicates that zero-value token transfers are allowed (i.e., _value == 0). It should be noted that self-transfers and zero-value token transfers have been identified as the root causes of various error vulnerabilities, including price manipulation vulnerabilities. Therefore, these situations should be avoided when writing the function transfer. In summary, the present invention can provide general and meaningful preconditions for functions.
[0019] 2. (Fix the existing specification). Figure 3 Shows the repair suggestions for the contract specification of the Tether Gold token (XAUt) to address a vulnerability. The market value of this token is approximately $473 million. This vulnerability was discovered by Blocksec on May 27, 2023. The vulnerability lies in the if statement on lines 20 - 23. This statement allows an attacker to transfer XAUt to a trusted receiver. Although it is not possible to directly profit from this vulnerability, the attacker can transfer XAUt to manipulate the XAUt price in the WETH - XAUt pool and make a profit. The specification on lines 10 - 13 states that if the receiver is trusted and the transferred amount is greater than or equal to 0, the balance will not change. The vulnerability can be fixed by deleting the code on lines 20 to 23. However, this results in an inconsistency between the repaired code and the existing specification. Therefore, the specification must be updated accordingly. However, manually modifying the specification is a time-consuming and error-prone task. For this reason, the present invention can automatically analyze the inconsistency between the code and the specification and generate suggestions for the repaired specification. This greatly saves the time and effort of developers.
[0020] Table 1 Suggestions for Repairing Smart Contract Specifications
[0021]
[0022]
[0023] To prove the correctness of the repair suggestion specification of the present invention, the present invention generated 8 suggestions for repairing contract specifications for the above program. As shown in Table 1, the repaired specification expressions are given. Among them, the #Function column combines the contract name and the function name to distinguish the same function names in different contracts. The Correct column indicates whether the suggested program is correct (i.e., TRUE) or incorrect (i.e., FALSE). A correct contract specification repair suggestion means that after applying the specification repair suggestion, the specification can pass the consistency verification. The table contains 3 types of specification repair suggestions: (1) Precondition suggestion (P-suggest): Replace the original precondition of the function with the inferred precondition for repair. For example, the specification repair suggestion #3 replaces the precondition of the function T2.transferFrom with the inferred condition amount <. (2) Postcondition suggestion (Q-suggest): Replace the postcondition of the function with the inferred postcondition. For example, the specification repair suggestion #6 replaces the postcondition of the function T2.transferFrom with the inferred condition shown in Table 2. (3) Function call suggestion (F-suggest): Replace the precondition and postcondition of the function with a new precondition and postcondition, which are inferred from the position of the function call. For example, the specification repair suggestion #7 replaces both the precondition and postcondition of the function ER.transferFrom, and these conditions are inferred from Figure 2 the function call on line 24 in
[0024] This example shows that there are many ways to correctly repair specifications. The high-level principles of the present invention are: (1) it provides the correct ways to repair specifications and achieves as few modifications as possible (based on the Occam's razor principle); (2) it always involves developers in the process of repair suggestions. For example, a straightforward solution is to repair the specifications one by one until all specifications are correct. However, this is not practical because it may lead to significant changes to the existing specifications. Therefore, the present invention restricts the search space by replacing the preconditions or postconditions of functions with appropriate corresponding ones (i.e., preconditions or postconditions). Thus, the precondition suggestion only replaces the precondition of the function, and the postcondition suggestion only replaces the postcondition of the function. It should be noted that the present invention does not generate specification repair suggestions that can be either precondition suggestions or postcondition suggestions. The only exception is function call repair, which replaces both the precondition and the postcondition, and these conditions are inferred from the position of the function call.
[0025] During the experiment of the present invention, it was observed that among many generated general and semantically correct specification repair suggestions, reasonable suggestion programs are very close to the original specifications syntactically. By measuring the edit distance between the suggestion program and the original specification, it can help sort the generated suggestion expressions for repair, and more developer-intended repair suggestions can be obtained through sorting. The present invention uses the graph edit distance (GED) to select the best specification repair suggestion. Among the 8 available suggestion programs, the present invention selected suggestion program #3 because it has the smallest edit distance from the original specification expression and ensures the correctness and consistency of the specification.
[0026] At a high level, the workflow of the present invention is as follows: First, the call graph is segmented into function components. Then, each function component is topologically sorted to determine the order of repair. Second, the present invention generates the specification repair suggestions with the closest sorted edit distance for each function component. Subsequently, all the specification repair suggestions with the closest sorted edit distance are merged into the final specification repair suggestion. It is assumed that there are no mutually recursive function calls, so the topological sort always has a solution. This assumption is reasonable because writing mutually recursive function calls in smart contracts is not recommended to avoid denial-of-service attacks (DoS). In the update function, if there is no function to traverse, the algorithm saves the current suggestion. On the contrary, if a function is selected, the algorithm will generate P-suggest or Q-suggest. For each function call inside function m, the precondition or postcondition of the called function can be generated with F-suggest.
[0027] The present invention generates intelligent contract specification repair suggestions in a bottom-up manner. This aims to determine the order of repair suggestions to ensure that each function and specification is detected and repaired only once. To obtain the order of repair suggestions, the present invention creates a call graph from the intelligent contract, where each node is a function and there is a directed edge from the caller to the callee. Although the call graph is a directed graph, the present invention treats it as an undirected graph when determining the call relationship. To minimize the overhead associated with suggestions for unrelated functions, the present invention only attempts to repair and suggest the call subgraphs associated with functions where the specification is inconsistent with the program. By examining the call graph, the present invention can identify zero or more call subgraphs. Generating repair suggestions for an intelligent contract is equivalent to generating separate repair suggestions for each call subgraph and then merging them together. For example, Figure 4 The left figure in Figure 1 has 3 call subgraphs: call sub Figure 2 、call sub Figure 3 . There are two functions, add and withdraw, with incorrect specifications. Since add belongs to call sub Figure 1 and withdraw belongs to call sub Figure 2 , only the call subgraphs call sub Figure 1 and call sub Figure 2 associated with the incorrect specifications will be modified and suggested. In Figure 4 the directed graph in the right figure, the present invention performs a topological sort to determine the order of repair suggestions, as shown at the bottom of the figure. According to the topological sort, the present invention suggests the call subgraphs in order, ensuring that each call subgraph is properly processed. In this example, only the function specifications in call sub Figure 1 and call sub Figure 3 are repaired and suggested, and then the function specifications in call sub Figure 2 remain unchanged. In this way, the present invention maintains the developer's involvement and ensures the correctness of the entire intelligent contract.
[0028] As mentioned above, to limit the size of the solution space, the present invention focuses on three types of smart contract specification repairs: precondition repair suggestions (P-suggest), postcondition repair suggestions (Q-suggest), and function call repair suggestions (F-suggest). These suggestions are inferred from the correct program code. The inference process of the present invention always follows a rule: all other specifications are correct except for the smart contract specification that the present invention is trying to infer the repair for. This is because without this assumption, the inference process of the present invention will fall into loops and contradictions, where when trying to repair and suggest a specification, the specification of the called function needs to be obtained, and the specification of the called function must be verified as consistent or repaired. Therefore, the present invention adopts a bottom-up repair order, so that the specification of the called function has been repaired and can pass the contract specification consistency verification program, and the specification that can pass the consistency verification after repair will be used to repair the specification of the subsequent called function. The definition of the correctness of the smart contract specification repair suggestion of the present invention is as follows: Given a set of original specifications I, a repair suggestion R replaces the specifications in I with I n , and obtains I’ = I n ∪ I\I o . The repair suggestion R is correct when each function after replacement conforms to its specification. That is, there are countless preconditions or postconditions that can be used to construct correct specification suggestions. For example, the condition x > 10 is semantically equivalent to x > 10 || x > 20 or!(x <= 10). Although various variations can be used to generate correct suggestions, they are useless. Therefore, the goal of the present invention is to generate the weakest precondition and the strongest postcondition to further reduce useless suggestions.
[0029] The three specification repair strategies of the present invention are as follows:
[0030] 1. Precondition repair (P-suggest). Given a function m associated with ensures(p, q). P-suggest replaces p with the weakest precondition p' to construct the correct specification ensures(p', q). Finding the weakest precondition has been widely studied. In this paper, the present invention adopts a method combining backward inference and temporary variable elimination to implement the weakest precondition. Specifically, the weakest precondition means that given the function m and the specification ensures(p, q), the present invention needs to find a weakest precondition p' such that the specification ensures(p', q) holds. Expressed in a formula: Here, s is the implementation of the function m; V pIncludes variables that are not visible in the precondition, such as local variables and temporary variables. The process QE represents the execution of variable (quantifier) elimination. Encoding post*(true, q) means that the present invention starts the encoding process from an empty precondition (i.e., the precondition is true). The main difference between post and post* is that post performs assertion verification while post* does not. For example, given the statement assert(e), the encoding function post will terminate when σ!≠>e, but post* will skip the verification step. It should be noted that p' always exists. In the worst case, p' is false. This can be illustrated by a simple example Figure 5 to see how the present invention repairs the specification for the missing precondition. The above code shows a public function named main that has a global variable z, a parameter x, and a local variable v. The defined specification ensures(true, z > 10) is verified to be inconsistent. The weakest precondition p' is calculated as follows,
[0031]
[0032] During the encoding process, the present invention must ensure that the variable scopes are consistent in the context. This is because variables in smart contracts may have global scope, function parameter scope, and local scope, and there may be cases where they have the same name. Therefore, when generating the final encoding, the present invention needs to perform postcondition variable scope processing to solve the variable scope problem. In the above example, although the variable z is assigned a new value in the given example, in actual encoding, z refers to the unassigned variable.
[0033] 2. Postcondition Repair: Given a function m with ensures(p, q). A Q-suggest replaces q with a strongest postcondition q', thus constructing a correct specification ensures(p, q'). Similar to P-suggest, the process of finding the strongest postcondition also depends on variable elimination. Formally, QE calculates q', which is defined as follows:
[0034]
[0035] During the process of finding the strongest postcondition, the present invention must ensure that the variable scopes are correctly aligned in the context. This means that the present invention needs to handle variables that are not visible for the postcondition, such as local variables and temporary variables. These variables belong to the internal state of the function and are not included in the specification. To solve this problem, the present invention uses a variable set V qis used to represent variables that are not visible to the postcondition. When generating the strongest postcondition q', the present invention needs to consider the visibility of variables. For example, if a variable v is updated within a function, then there are now two versions of v: old(v) itself and its previous value, and the previous variable v is represented by old(v). If v is visible to the postcondition, then old(v) must also be visible to the postcondition. This ensures that the postcondition correctly captures the state of the variable after the function execution.
[0036] To achieve this, the present invention defines a utility function old(), which represents the previous value of a variable. By using old(v) in the postcondition, the present invention ensures that the updated variable v and its previous value can be correctly aligned in the context of the postcondition. This allows the present invention to handle the situation where variables are updated and correctly consider them in the postcondition. It should be noted that this process is not applicable to all scenarios when deriving the strongest postcondition q', and there are also scenarios where no result can be derived. Especially when there is an assertion failure within the function, the postcondition may not be correctly derived.
[0037] Figure 6 Shows the specification ensures(x + z ≥ 9, false) that has been proven inconsistent. The derivation of the strongest postcondition q' is shown as follows,
[0038]
[0039] 3. Function Call Repair (F-suggest): For a function m with the specification ensures(p, q), F-suggest will use the latest precondition p' and postcondition q' derived from the function call site to construct a correct specification ensures(p', q'). To construct an F-suggest for the function m, the present invention first determines the location where the function call occurs, and then derives the precondition and postcondition of m. Assume the implementation of the function f is s = s0; m(e); s1;, where m(e) represents the call to m, and s0 and s1 are function execution statements. Given the specification ensures(a, b) associated with f, the present invention again uses variable elimination to derive the precondition p' and postcondition q'. The precondition p' is derived by applying variable elimination to the precondition p at the call site to obtain the precondition p' in the context of the function f. The postcondition q' is derived by applying variable elimination to the postcondition q at the call site to obtain the postcondition q' in the context of the function f. Formally, it is expressed as:
[0040]
[0041] Among them, V0 and V1 respectively contain variables that are invisible to p' and q'. Since the present invention is deriving the specification of m, the specification of m cannot be directly used, which is different from Definition 2. The present invention adds auxiliary variables to represent the parameters and return variables of m. For example, a function add has two parameters x, y and a return variable r. The encoding of the statement v = add(10, 20) is c0 = 10 ∩ c1 = 20 ∩ c2 = v, where c0, c1, and c2 are placeholders (temporary variables) representing x, y, and r respectively. Through variable elimination, it can be obtained that c2 = c0 + c1. Subsequently, a substitution is performed to obtain a valid specification r = x + y.
[0042] Given the above code, which contains two functions main and subtract, where z is a global variable. By analyzing the function call on line 4, we can calculate the precondition and postcondition of the subtract function as follows: Precondition: c0 = x ∩ c1 = y ∩ c2 = z; Postcondition: c2 = c0 - c1
[0043] Here, the example uses the markers c0, c1, and c2 to represent the parameters x, y of the subtract function and the global variable z. Through the process of variable elimination, the program obtains c2 = c0 - c1, which means that the function of the subtract function is to assign the difference between the parameters x and y to the global variable z. By analyzing the function call and deriving the specification, we can obtain the correct specification of the subtract function, thereby ensuring the functional correctness of the smart contract. Such a derivation process provides important support for the specification repair and verification of the smart contract, ensuring the correctness and security of the contract during execution.
[0044]
[0045]
[0046] After obtaining p' and q', the present invention performs a consistency verification on them to ensure that they are the correct specifications of the subtract function. The verification process involves applying p' and q' to the implementation of the subtract function to check whether they satisfy all execution paths of the function. The present invention traverses the code of the subtract function, uses p' as the precondition and applies it to the entry point of the function, and then checks whether there is any execution path that violates the precondition p'. Similarly, the present invention uses q' as the postcondition and applies it to each exit point of the function, and then checks whether there is any execution path that violates the postcondition q'.
[0047] If any violation of p' or q' is found during the verification process, it indicates that there may be errors or incompleteness in the derivation process, and further corrections or supplements are required. Otherwise, if all execution paths satisfy p' and q', the present invention can confirm that they are the correct specifications of the function subtract. Through such a verification process, the present invention can ensure that the repaired specifications are correct and can accurately describe the expected behavior of the function subtract. This provides additional guarantees for the specification repair of smart contracts, ensuring that the contracts perform as expected during runtime and do not lead to unexpected errors or vulnerabilities.
[0048] Step 4: The present invention adopts three specification repair strategies for inconsistent specifications to obtain different repair suggestions. The present invention will sort the generated specification repair suggestions and select the one with the smallest graph edit distance as the final repair suggestion. There may be multiple different inference results for the suggestions of specification repair, and consistent results with the program can be obtained in the verification. The present invention proposes a method to sort the multiple generated specification repair suggestions and select the one closest to the original specification as the main repair suggestion. The present invention uses the graph edit distance (GED) to define the distance between the specification suggestion and the specification. The graph edit distance is calculated based on the abstract syntax tree structure (AST) of the specification statement. Essentially, calculating the graph edit distance is to judge the differences in nodes and edges between two graphs, which in the case of specification statements involves variables and inequality relationships. And the present invention has transformed the specification statement into an abstract syntax tree (AST) during the process of solving verification and repair, so it is a good choice to use GED to calculate the distance between the specification suggestion and the original specification. GED essentially calculates the minimum number of insertions, deletions, and replacements required to make different graph structures the same. This coincides with the distance from the original specification to the specification suggestion described by the present invention. Figure 8 Given two expressions, they are first transformed into symbolic expressions and then further presented in the form of a tree structure, where each node is either an operator or an operand, and there is a directed edge from the operator to the operand. The present invention uses an existing tool called NetWorkx to calculate the distance between this specification and the specification suggestion. For example, the previous conditional specification suggestion table of the present invention, the tree structure representation of #pre (original precondition), #sug1 (the first suggestion), and #sug2 (the second suggestion), is as Figure 8 , and their GED edit distances are as follows:
[0049] (1) GED(#pre, #sug1) = 2. To obtain #pre from #sug, the present invention replaces the nodes isTrusted and select with 0 and ≠ respectively.
[0050] (2)GED(#pre, #sug2) = 8. To obtain #pre from #sug2, the present invention needs to add 4 edges and 4 nodes.
[0051] It is worth noting that the cost of each operation is 1. The present invention prefers to select #sug1 rather than #sug2 because GED(#pre, #sug1) is smaller than GED(#pre, #sug2). Since a repair suggestion may replace multiple conditions (i.e., preconditions and / or postconditions), the distance between the repair suggestion specification and the original specification is determined by the sum of the distances of all replaced conditions.
[0052] To evaluate the performance of the method of the present application, experimental studies were conducted on the following problems.
[0053] Problem 1: Can the present invention infer missing specifications?
[0054] Problem 2: Can the present invention repair the inconsistency of function call chain specifications in smart contracts?
[0055] Problem 1 is used to explore whether the present invention can effectively and automatically generate missing smart contract specifications, that is, when developers provide incomplete function specifications for functions, whether the present invention can automatically complete the remaining specifications according to the specification logic provided by the developers. The present invention performs the completion of smart contract specifications for 10 real and well-known smart contract projects. Given incomplete smart contract specifications for functions, and then uses the present invention for repair. The experimental results are shown in Table 2.
[0056] Table 2 Results of Completing Smart Contract Specifications
[0057]
[0058] It can be observed from the experimental results that the present invention has successfully inferred a total of 374 missing conditions, including 187 preconditions and 187 postconditions, and no conditions are missed. The present invention can infer the missing function specifications of smart contracts for correct program codes, and can quickly and effectively give the weakest preconditions and the strongest postconditions. That is, the present invention can quickly and efficiently complete the function specifications with missing preconditions or postconditions.
[0059] Problem 2 is used to explore whether the present invention can repair the smart contract specifications of the called functions through function call relationships. Compared with Problem 1 of completing missing smart contract specifications, the method provided by Problem 2 can solve the problem of cases involving multiple function calls and the inconsistency of smart contract specifications in the call chain. The present invention performs smart contract specification repair on 10 real and well-known smart contract projects. The experimental results are shown in Table 3.
[0060] Table 3 Results of Repairing Smart Contract Specifications
[0061]
[0062]
[0063] It can be observed from the experimental results that the average function call depth is 2.7. Among the 10 projects, ZIL has the highest call depth of 5. This is the main reason for the longest repair time (117.38 seconds) of the present invention. The strategy of the present invention is to repair the specifications on the call chain in a bottom-up manner according to the rules of topological sorting, and a deeper call depth will result in a larger number of potential repair suggestions. In addition, the execution time is also affected by the number of incorrect specifications. For example, the present invention only needs 15.01 seconds to repair the SHIB project, which has only one inconsistent specification. On average, the present invention takes 43.12 seconds to generate a specification repair suggestion. Among them, the present invention uses a heuristic strategy to minimize the number of specification suggestions. That is, the present invention first generates a smart contract specification repair suggestion, calculates the distance of the specification graph through the graph edit distance, and uses it as a standard point. During the process of generating precondition repair suggestions, postcondition repair suggestions, and function call repair suggestions, calculate the distance of the subsequently generated specification repair suggestions. If it exceeds the standard point, discard the repair suggestion for this specification. This heuristic strategy eliminates the need to calculate some irrelevant contract repair suggestions, thereby improving the efficiency of generating specification repair suggestions. It can be seen that the present invention can solve the situation involving multiple function calls and the existence of inconsistent smart contract specifications in the call chain.
[0064] It should be noted that although the present invention has been shown and described with reference to specific exemplary embodiments of the present invention, those skilled in the art should understand that the present invention is not limited to the above embodiments. Any changes to the present invention fall within the protection scope of the present invention application.
[0065] Beneficial effects
[0066] The beneficial effects of the technical method proposed by the present invention are as follows:
[0067] a. Developed a contract function verification method based on Solidity smart contracts for the real world. It can be used for intelligent specification and program consistency detection.
[0068] b. Provided an innovative method to identify and repair errors in smart contract specifications, and provided a useful contract specification repair method for the development of actual Solidity smart contracts.
[0069] c. Contributed a specification completion tool that can assist developers in writing specifications, and provided a tool for developers to set preconditions or postconditions to automatically complete the entire specification. Brief description of the drawings
[0070] Figure 1 Flow chart of the contract specification verification and repair method of the present invention;
[0071] Figure 2 Example diagram of a Solidity program with contract specifications;
[0072] Figure 3 Example diagram of specification repair;
[0073] Figure 4 Example diagram of function call;
[0074] Figure 5 Example diagram of a precondition repair program;
[0075] Figure 6 Example diagram of a postcondition repair program;
[0076] Figure 7 Example diagram of a function call repair program;
[0077] Figure 8 Example diagram of graph editing for specification repair suggestions.
Claims
1. A method for repairing Solidity smart contract specifications, characterized in that, The method includes the following steps: Step 1: Taking the Solidity smart contract program with smart contract specifications as input, the present invention first uses the Slither tool to convert the smart contract and the Solidity program into an Abstract Syntax Tree (AST), and constructs a Control Flow Graph (CFG) for each function. Then, the control flow graph of the function and the function specifications are encoded into boolean expressions. The setting of the smart contract specifications is based on the specifications set by Hoare logic, which are mainly placed above the function code in the form of comments. The Hoare logic specifications consist of a precondition and a postcondition. The meaning of this smart contract is that if the parameters passed into the function satisfy the precondition, then the result obtained after successfully executing the function must satisfy the postcondition. Step 2: Adding the encoded control flow graph and smart contract specifications to the z3 solver for solving, and determining whether the solution result is unsat (not satisfied). If it is unsat (not satisfied), it means that no counterexample can be solved. That is, the smart contract program and the smart contract specifications are consistent. If the result is sat, it means that there is a solution to the counterexample under the current precondition, that is, there is an execution path of the function whose execution result is inconsistent with the postcondition, indicating that the function specifications and the program code are inconsistent, that is, the specifications need to be repaired. Step 3: The inconsistent smart specifications whose verification results are inconsistent need to be repaired. The repair order is topologically sorted according to the function call graph, and the function specifications are repaired from bottom to top. The repair types are divided into two categories: one is to repair missing specifications. This type of repair is that developers write the precondition or postcondition, and the repair program supplements and writes the complete specification conditions that meet the program consistency verification. The second is to repair existing specifications. Three repair methods, namely precondition repair, postcondition repair, and function call repair, are respectively used to generate corresponding repair suggestions, and the obtained suggestions are obtained in conjunctive normal form (CNF) through quantifier elimination. The graph edit distance is used for sorting, and the one closest to the original specification is selected as the repair suggestion.