Smart contract decompilation code optimization method and system
By building a contract dependency graph for smart contracts and using large language models for code optimization, the shortcomings of method boundary recognition, variable type recovery and contract attribute inference in the existing technology are solved, and a more comprehensive optimization solution is achieved, which improves the quality and reliability of decompilation output.
Patent Information
- Application Number
- CN202510255846.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Priority Date
- 2025-01-09
- Filing Date
- 2025-03-05
- Publication Date
- 2025-05-23
- Estimated Expiration
- 2045-03-05
AI Technical Summary
Existing smart contract decompilation code optimization methods cannot provide a more comprehensive optimization solution, especially in terms of method boundary recognition, variable type recovery and contract attribute inference.
By obtaining the decompiled code of the smart contract to be optimized, building a contract dependency graph, generating a variable method code context and multiple thinking chain prompts, and using a large language model to optimize the code with preset variable types and contract attribute inference candidate sets, and finally perform consistency checks through preset program analysis and verification technology.
A more comprehensive optimization solution is realized, which can accurately identify method boundaries, restore variable types and contract attributes, improve the quality and reliability of decompilation output, and support more effective program understanding, vulnerability detection and component analysis.
Smart Images

Figure CN120029630A_ABST
Abstract
Description
[0001] This application claims priority to Chinese patent application filed on January 9, 2025, with application number 202510036616.2, the entire contents of which are incorporated herein by reference Technical Field
[0002] The present invention relates to the field of information security technology, and in particular to a smart contract decompilation code optimization method and system. Background Art
[0003] Smart contracts are automatically executed programs running on the blockchain. Due to the transparency of the blockchain, the bytecode of smart contracts is publicly visible, but its source code is usually not public. According to statistics, more than 99% of smart contracts only disclose bytecode but not source code. Therefore, decompilation becomes a key technology for understanding and analyzing smart contracts.
[0004] Decompilation is the process of converting low-level machine code (such as EVM bytecode, Ethereum Virtual Machine Bytecode) back to a high-level representation (such as Solidity code). It plays an important role in program analysis, especially in program understanding and vulnerability detection. Decompilation involves recovering variables, functions, and control flow abstractions through various program analysis methods, and then synthesizing these abstractions using heuristic rules to reconstruct high-level code representation.
[0005] Most of the existing smart contract decompilation code optimization methods are based on the smart contract decompilation framework to convert EVM bytecode into high-level code similar to Solidity, and optimize the smart contract decompilation code by identifying method boundaries by analyzing the pattern of repeated calls. However, this method only focuses on a single problem and cannot provide a more comprehensive optimization solution. Summary of the invention
[0006] The present invention provides a smart contract decompilation code optimization method and system, which are used to solve the technical problem that the existing smart contract decompilation code optimization method cannot provide a more comprehensive optimization solution.
[0007] A first aspect of the present invention provides a smart contract decompilation code optimization method, comprising:
[0008] Obtain the decompiled code of the smart contract to be optimized, and construct a contract dependency graph based on the decompiled code of the smart contract to be optimized;
[0009] Extracting fragments from the contract dependency graph to generate variable method code context;
[0010] Based on the contract dependency graph, generate multiple thought chain prompts;
[0011] Using a large language model to optimize the decompiled smart contract code to be optimized according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set and the preset contract attribute reasoning candidate set, and outputting the intermediate smart contract decompiled code;
[0012] A preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized, and the target smart contract decompiled code is determined.
[0013] Optionally, constructing a contract dependency graph based on the decompiled code of the smart contract to be optimized includes:
[0014] Perform type dependency identification on the decompiled smart contract code to be optimized, and output multiple contract dependency data corresponding to the decompiled smart contract code to be optimized; the multiple contract dependency data include type dependency, state dependency and control flow dependency;
[0015] A contract dependency graph is constructed according to the type dependency, the state dependency and the control flow dependency.
[0016] Optionally, the variable method code context includes a variable code snippet and a method code snippet; extracting the snippet from the contract dependency graph to generate the variable method code context includes:
[0017] Perform code slicing on the contract dependency graph to generate variable code snippets;
[0018] Perform call chain analysis on the contract dependency graph to generate method code snippets.
[0019] Optionally, the adopting of a large language model to optimize the decompiled smart contract code to be optimized according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set and the preset contract attribute reasoning candidate set, and outputting the intermediate smart contract decompiled code includes:
[0020] Performing data extraction on the variable code snippet and the method code snippet, and outputting structural features and semantic information corresponding to the variable code snippet, and structural features and semantic information corresponding to the method code snippet;
[0021] Taking the structural features and semantic information corresponding to the variable code snippet and the structural features and semantic information corresponding to the method code snippet as constraints, the preset variable type inference candidate set and the preset contract attribute inference candidate set are used to perform large language model inference to generate code optimization suggestions;
[0022] The decompiled code of the smart contract to be optimized is optimized using a plurality of the thought chain prompts and the code optimization suggestions, and an intermediate smart contract decompiled code is output.
[0023] Optionally, the preset program analysis and verification technology includes a formal verification method and a violation rejection rule; the preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized to determine the target smart contract decompiled code, including:
[0024] Perform symbolic execution on the decompiled smart contract code to be optimized and the intermediate smart contract decompiled code respectively, and generate a symbolic digest corresponding to the decompiled smart contract code to be optimized and a symbolic digest corresponding to the intermediate smart contract decompiled code;
[0025] Using a formal verification method to determine whether the symbol digest corresponding to the decompiled code of the smart contract to be optimized and the symbol digest corresponding to the decompiled code of the intermediate smart contract are equivalent;
[0026] If so, determining whether the decompiled code of the intermediate smart contract complies with the violation rejection rule;
[0027] If it meets the requirements, the intermediate smart contract decompiled code is used as the target smart contract decompiled code.
[0028] Optionally, the violation of the rejection rule is specifically:
[0029] ;
[0030] Among them, π is the intermediate smart contract decompiled code, which represents the context containing a list that assigns variable types to expression patterns; e is the expression; θ is the variable type.
[0031] A second aspect of the present invention provides a smart contract decompilation code optimization system, comprising:
[0032] An acquisition module is used to acquire the decompiled code of the smart contract to be optimized, and to construct a contract dependency graph based on the decompiled code of the smart contract to be optimized;
[0033] An extraction module, used to extract fragments from the contract dependency graph and generate variable method code context;
[0034] A generation module, used for generating a plurality of thought chain prompts based on the contract dependency graph;
[0035] An optimization module, configured to optimize the decompiled smart contract code to be optimized by using a large language model according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set, and the preset contract attribute reasoning candidate set, and output an intermediate smart contract decompiled code;
[0036] The checking module is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized by using a preset program analysis and verification technology to determine the target smart contract decompiled code.
[0037] A third aspect of the present invention provides a computer device, comprising a memory and a processor, wherein a computer program is stored in the memory, and when the computer program is executed by the processor, the processor executes the steps of the smart contract decompilation code optimization method as described in any one of the above items.
[0038] A fourth aspect of the present invention provides a computer-readable storage medium having a computer program stored thereon, which, when executed, implements the steps of the smart contract decompilation code optimization method as described in any one of the above items.
[0039] A fifth aspect of the present invention provides a computer program product, which includes a computer program stored on a non-transitory computer-readable storage medium, and the computer program includes program instructions, wherein when the program instructions are executed by a computer, the computer executes the steps of the smart contract decompilation code optimization method as described in any one of the above items.
[0040] It can be seen from the above technical solutions that the present invention has the following advantages:
[0041] The above technical scheme of the present invention provides a method for optimizing the decompiled code of a smart contract. First, the decompiled code of the smart contract to be optimized is obtained, and a contract dependency graph is constructed based on the decompiled code of the smart contract to be optimized. Then, a fragment is extracted from the contract dependency graph to generate a variable method code context. Based on the contract dependency graph, multiple thought chain prompts are generated. A large language model is used to optimize the decompiled code of the smart contract to be optimized according to the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets and preset contract attribute reasoning candidate sets, and an intermediate smart contract decompiled code is output. Finally, a preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the decompiled code of the smart contract to be optimized, and a target smart contract decompiled code is determined. Based on the above scheme, the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets and preset contract attribute reasoning candidate sets are combined and input into the large language model for code optimization, and then a consistency check is performed based on the preset program analysis and verification technology to determine the process of the target smart contract decompiled code. The present invention simultaneously considers the three key issues of method boundary identification, variable type recovery and contract attribute inference, and can provide a more comprehensive optimization scheme. BRIEF DESCRIPTION OF THE DRAWINGS
[0042] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the drawings required for use in the embodiments or the description of the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative labor.
[0043] Figure 1 A flowchart of a method for optimizing smart contract decompilation code provided in Embodiment 1 of the present invention;
[0044] Figure 2 The overall framework diagram of smart contract decompilation code optimization provided in the second embodiment of the present invention;
[0045] Figure 3 This is a structural block diagram of a smart contract decompilation code optimization system provided in Example 3 of the present invention. DETAILED DESCRIPTION
[0046] The embodiments of the present invention provide a smart contract decompilation code optimization method and system, which are used to solve the technical problem that the existing smart contract decompilation code optimization method cannot provide a more comprehensive optimization solution.
[0047] In order to make the purpose, features and advantages of the present invention more obvious and easy to understand, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the embodiments described below are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0048] Terminology explanation:
[0049] Smart Contract: An automatically executed program running on the blockchain that automatically executes contract terms when predetermined conditions are met.
[0050] Decompiler: A tool that converts low-level machine code (such as bytecode) back into high-level programming language code.
[0051] EVM (Ethereum Virtual Machine): Ethereum Virtual Machine is the operating environment of smart contracts and executes smart contract codes on Ethereum.
[0052] Solidity: The most commonly used smart contract programming language, designed specifically for writing Ethereum smart contracts.
[0053] Bytecode: A low-level representation of a compiled smart contract, which is the code form that the EVM directly executes.
[0054] Large Language Model (LLM): A natural language processing model based on deep learning, such as the GPT series, that can understand and generate human language.
[0055] Static Analysis: A technique for analyzing the structure and semantics of program code without actually running the program.
[0056] Dependency Graph: A graph structure that represents the dependency relationships between elements (such as variables and functions) in a program.
[0057] Symbolic Execution: A technique that uses symbolic values rather than concrete values to analyze the execution path of a program.
[0058] SMT Solver: A tool used to solve Satisfiability ModuloTheories problems, such as Z3.
[0059] Method Boundary: Defines the start and end of a method (function) in the code.
[0060] Variable Type Recovery: The process of inferring and recovering the data type of a variable during decompilation.
[0061] Contract Attribute: An attribute that describes the characteristics or functions of a smart contract, such as assets, identities, routers, etc.
[0062] Chain-of-Thought Prompt: A series of intermediate reasoning steps provided to large language models to guide the model to perform more complex reasoning.
[0063] Correctness Verification: The process of ensuring that the optimized code is functionally equivalent to the original code.
[0064] Program Slicing: A technique for extracting the parts of a program that are relevant to a specific computation.
[0065] Abstract Syntax Tree (AST): A tree data structure that represents the structure of a program's source code.
[0066] Control Flow Graph (CFG): A graph that represents all possible execution paths of a program.
[0067] Formal Verification: A technique that uses mathematical methods to prove or disprove the correctness of a software system.
[0068] Fuzz testing: An automated software testing technique that discovers software vulnerabilities by providing unexpected or random data as input.
[0069] See also Figure 1 , Figure 1 A flowchart of the steps of a smart contract decompilation code optimization method provided in Example 1 of the present invention.
[0070] The present invention provides a smart contract decompilation code optimization method, comprising:
[0071] Step 101: Obtain the decompiled code of the smart contract to be optimized, and build a contract dependency graph based on the decompiled code of the smart contract to be optimized.
[0072] Specifically, the process of constructing a contract dependency graph based on the decompiled code of the smart contract to be optimized can be achieved by executing the following sub-steps S11 to S12:
[0073] Step S11: perform type dependency identification on the decompiled smart contract code to be optimized, and output multiple contract dependency data corresponding to the decompiled smart contract code to be optimized; the multiple contract dependency data include type dependency, state dependency and control flow dependency;
[0074] Step S12: Construct a contract dependency graph based on type dependency, state dependency, and control flow dependency.
[0075] It should be noted that the key semantic information is first extracted from the decompiled code of the smart contract to be optimized, that is, three types of dependencies are identified: type dependency, state dependency, and control flow dependency; among them, type dependency refers to the dependency between the type of variable va and another variable vb or a specific expression eb. The system uses the expression grammar rules of the Solidity language (such as Figure 2 As shown in the figure, type dependency is identified; state dependency refers to the dependency between different state variables or between state variables and expressions, such as the read and write dependency of state variables. The system uses SmartState analyzer to identify state dependency; control flow dependency refers to the dependency in the program execution process, such as conditional statements, loops, etc. Among them, the rules for identifying type dependency can be expressed as:
[0076]
[0077] In a smart contract, an expression (e) can be any of the following forms: a single variable (v), such as x, balance, totalSupply; a constant value (c), such as 5, "hello", true; two expressions connected by Boolean operators (e blop e), such as isActive && isOwner; two expressions connected by mathematical operators (e numop e), such as a + b, price * quantity; two expressions connected by comparison operators (e cmpope), such as balance > 0; two expressions connected by bitwise operators (e bitop e), such as flags & mask; a tuple of multiple expressions ((e, . . . , e)), such as (x, y, z); an array of multiple expressions ([e, . . ., e]), such as [1, 2, 3]; a function call expression (e(e, . . . , e)), such as transfer(address, amount); use indexes to access arrays or mappings (e[e]), such as balances[userAddress]; slice arrays (e[e: e]), such as array[1:4]; access object properties (ev), such as msg.sender.
[0078] Furthermore, based on the identified dependencies, the system constructs a dependency graph (DG), i.e., a contract dependency graph. DG can be represented as a triple Gc = (Nc, Ec, Xe), where: Nc: the set of nodes in the graph, including variable nodes Nv and expression nodes Ne. Ec: the set of edges in the graph, including control flow dependency edges Ed, state dependency edges Es, and type dependency edges Et. Xe: a marking function that maps edges to corresponding dependency types.
[0079] It is worth mentioning that the control flow graph is generated first, and then the complete dependency graph DG is constructed by incrementally adding state dependency edges and type dependency edges.
[0080] Step 102: extract fragments from the contract dependency graph and generate variable method code context.
[0081] Further, step 102 may include the following sub-steps S21-S22:
[0082] Step S21, code slicing the contract dependency graph to generate variable code snippets;
[0083] Step S22: Perform call chain analysis on the contract dependency graph to generate method code snippets.
[0084] It should be noted that relevant code snippets are generated for variables and methods as code context; specifically, for variables: code slicing is performed based on the dependency graph DG, and code snippets related to the target variable are extracted to obtain variable code snippets; for methods: DG is searched to find the call chain where the target method is located, and code snippets are generated by combining related methods to obtain method code snippets.
[0085] Step 103: Generate multiple thought chain prompts based on the contract dependency graph.
[0086] It should be noted that based on the contract dependency graph, a series of intermediate reasoning steps are generated as thought chain prompts to guide the LLM model (large language model) for reasoning. Based on the templates in Table 1, corresponding thought chain prompts are generated for different optimization tasks.
[0087] Table 1: Thinking Chain Prompt Template
[0088]
[0089] Step 104: Use a large language model to optimize the smart contract decompiled code to be optimized according to the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets, and preset contract attribute reasoning candidate sets, and output the intermediate smart contract decompiled code.
[0090] It should be noted that before executing the code optimization step, the LLM is first provided with a candidate set of variable types and contract attributes, namely, a preset variable type reasoning candidate set and a preset contract attribute reasoning candidate set; wherein, the preset variable type reasoning candidate set is a collection of built-in types according to the Solidity document, and the preset contract attribute reasoning candidate set is a summary of attribute categories such as [Limit, Fee, Flag, Address, Asset, Router, Others] by analyzing representative smart contract data sets.
[0091] Further, step 104 may include the following sub-steps S41-S43:
[0092] Step S41, extracting data from the variable code snippet and the method code snippet, and outputting structural features and semantic information corresponding to the variable code snippet, and structural features and semantic information corresponding to the method code snippet;
[0093] Step S42: Using the structural features and semantic information corresponding to the variable code snippet and the structural features and semantic information corresponding to the method code snippet as constraints, a preset variable type reasoning candidate set and a preset contract attribute reasoning candidate set are used to perform large language model reasoning to generate code optimization suggestions;
[0094] Step S43: Optimize the decompiled code of the smart contract to be optimized using multiple thought chain prompts and code optimization suggestions, and output the intermediate smart contract decompiled code.
[0095] It should be noted that LLM optimization is the core step of the entire semantic enrichment process. In this step, SmartHalo combines the three types of prompts generated previously (code context, reasoning candidates, and thought chains) into complete prompts and inputs them into LLM; the specific prompt organization is as follows: First, the code context part contains code snippets related to the optimization target (such as variable setStorage). The second is the reasoning candidate part, which lists possible variable types or contract attributes. Finally, the thought chain part describes the dependency analysis steps in the reasoning process.
[0096] Specifically, first, in the code context analysis phase, SmartHalo receives input from the dependency graph and processes the variable and method code snippets separately. For variables, the system locates the dependencies related to the target variable through code slicing technology; for methods, it identifies the associations between methods by analyzing the call chain. The purpose of this phase is to extract the structural features and semantic information of the code, that is, to extract data from the variable code snippets and method code snippets respectively, and output the structural features and semantic information corresponding to the variable code snippets and method code snippets.
[0097] Secondly, in the candidate generation phase, the predefined variable type candidate set (from the Solidity document) and contract attribute candidate set are used to guide the LLM reasoning process. These candidate sets help LLM limit the scope of reasoning to a reasonable space and improve the accuracy of reasoning. The output of this phase is constrained optimization suggestions, that is, LLM reasoning is performed based on the structural features and semantic information (as constraints) corresponding to the variable code snippets and method code snippets, the predefined variable type candidate set and the contract attribute candidate set, and constrained optimization suggestions (code optimization suggestions) are generated.
[0098] Finally, in the optimization execution phase, the system uses the chain of thought prompts to guide LLM to optimize according to the reasoning steps of static analysis. The chain of thought prompts serve as a guideline for reasoning to ensure that the reasoning process of LLM conforms to the logic of static analysis. This phase directly outputs the optimized code, that is, based on the chain of thought prompts and constrained optimization suggestions, the decompiled code of the smart contract to be optimized is optimized according to the reasoning steps of static analysis, and the optimized code (intermediate smart contract decompiled code) is output.
[0099] Exemplarily, LLM optimization is the core step in the entire semantic enrichment process. In this step, SmartHalo will integrate three types of important prompt information into a complete input and provide it to LLM for processing. This is like giving LLM a work guide containing all the necessary information to help it complete the code optimization task. As shown in Table 2, for the example in Table 2, the complete prompt includes: 1. Code context: showing the code snippet related to the variable setStorage; 2. Type candidates: [bool, bytes32, ...uint256]; 3. Thinking chain: analyzing the derivation process from the return value type of the keccak256 function to the setStorage type. Specifically, suppose that the variable setStorage in a smart contract code needs to be optimized to determine its correct type. SmartHalo organizes the information in the following way: First, provide code context: This is like showing LLM a complete scene map to let it understand how this variable is used. For example:
[0100]
[0101] Then provide possible options: This is equivalent to giving LLM a list of choices, telling it "the type of the variable can only be one of these options". For example: it can be a simple type: like a number (uint256), text (string), yes / no (bool), etc.; it can also be a complex type: such as an address (address), byte data (byte32), etc.; or a mapping type (mapping): a data structure used to store key-value pairs.
[0102] Finally, provide thinking guidance: This is like giving LLM a solution idea, telling it how to analyze step by step. For example, first look at the keccak256 function, it always returns a bytes32 type of data; then see that this data is passed to the v0 variable; finally, find that setStorage uses v0 as an index, which means it should be a mapping type. Through such clear information organization, LLM can accurately understand the purpose and structure of the code, make choices within a reasonable range, analyze according to logical steps, and finally give correct optimization suggestions.
[0103] This process is like guiding a smart assistant to complete code analysis. By providing complete background information, options, and analysis methods, it ensures that it can draw accurate conclusions. This is also an important reason why SmartHalo can achieve good results in code optimization.
[0104] Table 2 Optimization Tips Examples
[0105]
[0106] Step 105: Use a preset program analysis and verification technology to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized, and determine the target smart contract decompiled code.
[0107] Preset program analysis and verification techniques include formal verification methods and violation rejection rules.
[0108] Further, step 105 may include the following sub-steps S51-S54:
[0109] Step S51: symbolically execute the decompiled code of the smart contract to be optimized and the decompiled code of the intermediate smart contract respectively, and generate a symbolic summary corresponding to the decompiled code of the smart contract to be optimized and a symbolic summary corresponding to the decompiled code of the intermediate smart contract;
[0110] Step S52: Use a formal verification method to determine whether the symbol digest corresponding to the decompiled code of the smart contract to be optimized and the symbol digest corresponding to the decompiled code of the intermediate smart contract are equivalent;
[0111] Step S53: If yes, determine whether the decompiled code of the intermediate smart contract meets the violation rejection rule;
[0112] Step S54: If it meets the requirements, the intermediate smart contract decompiled code is used as the target smart contract decompiled code.
[0113] It should be noted that after the code optimization is completed, it is also necessary to ensure that the optimized code maintains behavioral consistency and complies with static rules. This includes two checks: program behavior equivalence check based on symbolic execution and formal verification methods, that is, using symbolic execution and formal verification methods (formal verification methods) to verify the behavioral equivalence of the code before and after optimization. Specifically: (1) Perform symbolic execution on the original method (the decompiled code of the smart contract to be optimized) m and the optimized method (the decompiled code of the intermediate smart contract) m' to generate symbolic summaries s and s', that is, generate the symbolic summary s corresponding to the decompiled code of the smart contract to be optimized and the symbolic summary s' corresponding to the decompiled code of the intermediate smart contract. (2) Construct equivalence assertions (3) Use an SMT solver (such as Z3) to analyze whether the assertion Φ is satisfied. If Φ is satisfied, it means that methods m and m' are not equivalent in program behavior; otherwise, they are equivalent.
[0114] Furthermore, static rule violation checking is performed based on violation rejection rules: SmartHalo traverses the optimized code, and then uses violation rejection rules to identify and reject the wrong variable types predicted by LLM. Among them, the violation rejection rules (violation rejection rules) integrated by SmartHalo proposed in the present invention are included. Each violation rejection rule consists of two parts, including a specific premise and a conclusion. They are organized in the following form:
[0115] ;
[0116] Among them, π is the decompiled code of the intermediate smart contract, which represents the context containing the list of variable types assigned to expression patterns; in this form, e refers to the expression, and the present invention uses e1,...,en to represent different expressions; θ is the variable type, and the present invention uses θ1,..., θn to represent different variable types. The rules in this form are called judgments or assignments, and the goal of the present invention is to obtain the context π that assigns variable types to all variables in the code.
[0117] It is worth mentioning that if the symbol digest corresponding to the decompiled code of the smart contract to be optimized is not equivalent to the symbol digest corresponding to the decompiled code of the intermediate smart contract, or the decompiled code of the intermediate smart contract does not meet the violation rejection rule, it means that the verification process has found an error. The error information and verification suggestions are re-entered into the LLM model for iterative optimization until all optimization errors are corrected or the maximum number of iterations is reached.
[0118] As a comparison of technical effects, it can be combined with existing technologies for reference. The inheritance mechanism of smart contracts is different from that of traditional languages (such as C++ and Java). Smart contract inheritance involves embedding the code blocks of all base subcontracts (B1, B2, ..., Bn) directly into the inherited contract A without retaining explicit call information. This makes the traditional method boundary identification technology based on call sites ineffective in smart contracts. During the compilation process, a lot of type information is irreversibly optimized away. For example, information such as the return type of predefined functions and complex data structures is missing at the bytecode level. State variables in smart contracts are often used to record key attributes (such as assets, identities, etc.), which are clearly expressed in the source code through variable names and comments, but are completely lost at the bytecode level.
[0119] Existing code optimization solutions include Gigahorse, SigRec, DeepInfer, SmartDagger, and DIRTY. Among them, Gigahorse is a smart contract decompilation framework that converts EVM bytecode into high-level code similar to Solidity. The solution uses declarative rules and data flow analysis to recover program structures such as loops and functions. Gigahorse mainly identifies method boundaries by analyzing the pattern of repeated calls; SigRec is specifically used to recover the signatures of public functions in smart contracts. It uses predefined rules to infer the number and type of function parameters by analyzing the opcode sequence and stack operations in the bytecode. The core idea of SigRec is to identify common parameter types based on pattern matching; DeepInfer uses a deep learning method to infer function signatures. It converts bytecode into an intermediate representation and then uses graph neural networks and sequence models to predict the parameter types of functions. This method transforms the bytecode analysis problem into a machine learning task; DeepInfer uses a deep learning method to infer function signatures. It converts bytecode into an intermediate representation and then uses graph neural networks and sequence models to predict the parameter types of functions. This approach transforms the bytecode analysis problem into a machine learning task; SmartDagger is a cross-contract vulnerability detection framework that includes a contract property recovery component. This component uses static analysis to extract the usage patterns of state variables, and then predicts the properties of these variables (such as assets, addresses, etc.) through a neural network model. SmartDagger is characterized by the use of a large amount of real contract data for model training; DIRTY is a decompiler output enhancement framework that focuses on the recovery of variable types and names. It uses a Transformer-based model to analyze the abstract syntax tree of the decompiled code and predict the type and name of each variable. The innovation of DIRTY lies in the application of natural language processing technology to code analysis.
[0120] The above solutions represent different technical routes in the field of smart contract decompilation, including static analysis, heuristic rules, machine learning and other methods. Each method provides solutions to specific problems in the decompilation process, but none of them can fully solve key problems such as method boundary identification, variable type recovery and contract attribute inference; among them, these methods will have many defects, for example, inaccurate method boundary identification: existing decompilers (such as Gigahorse) have limitations in identifying method boundaries of smart contracts, especially for inherited methods, which leads to the omission of important methods or method scope identification errors, increasing the complexity of downstream tasks (such as method-level similarity comparison); inaccurate and incomplete variable type recovery: the variable types generated by the decompiler are often inconsistent with the static domain rules, such as ignoring predefined types. At the same time, although tools such as SigRec and DeepInfer can infer function parameter types, they cannot handle a wider range of variable type recovery problems. Although DIRTY attempts to recover variable types, it is prone to type errors that are inconsistent with the smart contract language rules due to the lack of consideration of static domain knowledge; lack of contract properties: the decompiler cannot recover key contract properties (such as assets, identities, etc.) explicitly stated in the source code, which are crucial for downstream tasks such as vulnerability detection; limited contract property inference capabilities: tools such as SmartDagger have made some progress in inferring contract properties, but their performance is heavily dependent on training data sets, and the effectiveness of these tools will significantly decrease when facing emerging or rare contract types; unable to recompile: the code output by the decompiler cannot usually be directly recompiled, limiting its usability. These defects seriously hinder reverse engineers from understanding program logic and have an adverse impact on downstream tasks such as vulnerability detection and component analysis; lack of comprehensive optimization methods: existing technologies often only provide solutions for a single problem (such as function signature recovery or variable type inference), and lack a comprehensive method that can fully optimize the decompiler output; separation of static analysis and machine learning methods: existing methods either rely on static analysis and heuristic rules (such as Gigahorse and SigRec), or rely entirely on machine learning models (such as DeepInfer and DIRTY). There is a lack of a solution that can effectively combine the advantages of both approaches.
[0121] In view of the above problems, the present invention provides a smart contract decompilation code optimization method, which can simultaneously solve key problems such as method boundary identification, variable type recovery and contract attribute inference, and combine the accuracy of static analysis with the flexibility of large language models to improve the quality and reliability of decompilation output; at the same time, a mechanism is designed to effectively extract and utilize the static domain knowledge of smart contracts to guide large language models to perform more accurate semantic recovery, and a set of strict correctness verification mechanisms are developed to ensure that the optimized code maintains behavioral consistency with the original decompilation output and eliminates reasoning errors that violate static domain rules; in addition, the readability and usability of the decompiled code can be improved, making it easier for analysts to understand and use, thereby supporting more effective downstream tasks such as program understanding, vulnerability detection and component analysis; by achieving these purposes, the present invention significantly improves the quality of smart contract decompilation and provides a more reliable foundation for security analysis and understanding of smart contracts.
[0122] In an embodiment of the present invention, the present invention provides a method for optimizing the decompiled code of a smart contract. First, the decompiled code of the smart contract to be optimized is obtained, and a contract dependency graph is constructed based on the decompiled code of the smart contract to be optimized. Then, a fragment is extracted from the contract dependency graph to generate a variable method code context. Based on the contract dependency graph, multiple thought chain prompts are generated. A large language model is used to optimize the decompiled code of the smart contract to be optimized according to the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets and preset contract attribute reasoning candidate sets, and an intermediate smart contract decompiled code is output. Finally, a preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the decompiled code of the smart contract to be optimized, and a target smart contract decompiled code is determined. Based on the above scheme, the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets and preset contract attribute reasoning candidate sets are combined and input into the large language model for code optimization, and then a consistency check is performed based on the preset program analysis and verification technology to determine the process of the target smart contract decompiled code. The present invention simultaneously considers the three key issues of method boundary identification, variable type recovery and contract attribute inference, and can provide a more comprehensive optimization scheme.
[0123] For better explanation, refer to Figure 2 , showing the overall framework diagram of the smart contract decompilation code optimization provided by the second embodiment of the present invention. It should be pointed out that this embodiment only briefly describes the general process of the smart contract decompilation code optimization method, and the specific implementation process of each step can be understood by referring to the relevant content in the aforementioned embodiment, which will not be described here. It can be understood that the present invention does not limit this.
[0124] The overall framework of smart contract decompilation code optimization proposed by the present invention is as follows: Figure 2 As shown in the figure, named SmartHalo, SmartHalo mainly consists of three core components: dependency-based semantic extraction module, LLM-based semantic enrichment module and correctness verification module. SmartHalo comprehensively solves key problems such as method boundary identification, variable type recovery and contract attribute inference by combining the advantages of static analysis (SA) and large language model (LLM). The following is the detailed technical solution of SmartHalo:
[0125] In the dependency-based semantic extraction module, this module is responsible for extracting key semantic information from the decompiled code, integrating three dependency relationships: type dependency, state dependency, and control flow dependency, using the triple Gc = (Nc, Ec, Xe) to represent the dependency graph, and constructing the complete dependency graph in an incremental manner.
[0126] In the LLM-based semantic enrichment module, the module uses a large language model (LLM) to perform semantic optimization on the decompiled code, performs code slicing of variables and call chain extraction of methods based on dependency graphs, and designs templates based on dependency types. It also converts static analysis steps into a reasoning process that can be understood by LLM, thereby using the dependency information extracted by static analysis to guide LLM reasoning, combining the output of LLM with static rules for verification, and outputting optimized decompiled code.
[0127] In the correctness verification module, this module ensures that the optimized code maintains behavioral consistency and complies with static rules, program behavioral equivalence checks based on symbolic execution and formal verification, and type violation checks based on static rules; and sets an iterative optimization strategy. If the optimized code does not meet any check, the verification results are fed back to LLM for re-optimization until all optimization errors are corrected or the maximum number of iterations is reached.
[0128] In an embodiment of the present invention, SmartHalo solves three key problems, namely, method boundary identification, variable type recovery, and contract attribute inference, by combining static analysis and a large language model. Compared with methods such as Gigahorse and SigRec that only focus on a single problem, SmartHalo provides a more comprehensive optimization solution. For example, in terms of method boundary identification, SmartHalo uses a combination of dependency graphs and LLMs to more accurately identify complex inherited methods, which is difficult to achieve with simple heuristic rule-based methods such as Gigahorse. SmartHalo's hybrid approach makes full use of the accuracy of static analysis and the flexibility of LLMs. By extracting static domain knowledge through dependency graphs and guiding LLMs with thinking chain prompts, SmartHalo can better handle emerging or rare contract patterns. This solves the problem of performance degradation in methods such as SmartDagger that rely heavily on training data when facing new contracts. At the same time, SmartHalo's correctness verification mechanism can effectively prevent the illusions produced by LLMs and improve the reliability of optimization results, which is an advantage that pure machine learning methods such as DIRTY do not have. In addition, SmartHalo not only improves the quality and reliability of decompiled output, but also enhances its adaptability when facing diverse and complex smart contracts, providing a more reliable foundation for downstream tasks such as vulnerability detection and component analysis.
[0129] See also Figure 3 , Figure 3 This is a structural block diagram of a smart contract decompilation code optimization system provided in Example 3 of the present invention.
[0130] The present invention provides a smart contract decompilation code optimization system, comprising:
[0131] The acquisition module 301 is used to obtain the decompiled code of the smart contract to be optimized, and construct a contract dependency graph based on the decompiled code of the smart contract to be optimized;
[0132] An extraction module 302 is used to extract fragments from the contract dependency graph and generate variable method code context;
[0133] A generating module 303, for generating a plurality of thought chain prompts based on the contract dependency graph;
[0134] The optimization module 304 is used to optimize the decompiled smart contract code to be optimized by using a large language model according to the variable method code context, multiple thought chain prompts, preset variable type reasoning candidate sets and preset contract attribute reasoning candidate sets, and output the intermediate smart contract decompiled code;
[0135] The checking module 305 is used to use a preset program analysis and verification technology to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized, and determine the target smart contract decompiled code.
[0136] Furthermore, the acquisition module 301 is specifically used for:
[0137] Identify the type dependency of the decompiled smart contract code to be optimized, and output multiple contract dependency data corresponding to the decompiled smart contract code to be optimized; the multiple contract dependency data include type dependency, state dependency and control flow dependency;
[0138] Construct a contract dependency graph based on type dependency, state dependency, and control flow dependency.
[0139] Furthermore, the extraction module 302 is specifically configured to:
[0140] Slice the contract dependency graph to generate variable code snippets;
[0141] Perform call chain analysis on the contract dependency graph and generate method code snippets.
[0142] Furthermore, the optimization module 304 is specifically used to:
[0143] Extract data from variable code snippets and method code snippets, and output structural features and semantic information corresponding to the variable code snippets, and structural features and semantic information corresponding to the method code snippets;
[0144] Using the structural features and semantic information corresponding to the variable code snippet and the structural features and semantic information corresponding to the method code snippet as constraints, a large language model is used to perform reasoning using the preset variable type reasoning candidate set and the preset contract attribute reasoning candidate set to generate code optimization suggestions;
[0145] Use multiple thought chain prompts and code optimization suggestions to optimize the decompiled smart contract code to be optimized, and output the intermediate smart contract decompiled code.
[0146] Furthermore, the preset program analysis and verification technology includes formal verification method and violation rejection rule; the inspection module 305 is specifically used for:
[0147] Symbolically execute the decompiled code of the smart contract to be optimized and the decompiled code of the intermediate smart contract respectively, and generate the symbolic summary corresponding to the decompiled code of the smart contract to be optimized and the symbolic summary corresponding to the decompiled code of the intermediate smart contract;
[0148] Use formal verification methods to determine whether the symbolic digest corresponding to the decompiled code of the smart contract to be optimized is equivalent to the symbolic digest corresponding to the decompiled code of the intermediate smart contract;
[0149] If so, determine whether the decompiled code of the intermediate smart contract meets the violation rejection rule;
[0150] If it matches, the intermediate smart contract decompiled code will be used as the target smart contract decompiled code.
[0151] Furthermore, the rejection rules are violated, specifically:
[0152] ;
[0153] Among them, π is the intermediate smart contract decompiled code, which represents the context containing a list that assigns variable types to expression patterns; e is the expression; θ is the variable type.
[0154] Those skilled in the art can clearly understand that, for the convenience and brevity of description, the specific working process of the above-described system and module can refer to the corresponding process in the aforementioned method embodiment, and will not be repeated here.
[0155] An embodiment of the present invention also provides a computer device, including a memory and a processor, wherein a computer program is stored in the memory; when the computer program is executed by the processor, the processor executes the steps of the smart contract decompilation code optimization method as described in any of the above embodiments.
[0156] An embodiment of the present invention also provides a computer-readable storage medium on which a computer program / instruction is stored. When the computer program / instruction is executed by a processor, the steps of the smart contract decompilation code optimization method as described in any of the above embodiments are implemented.
[0157] An embodiment of the present invention also provides a computer program product, including a computer program / instruction, which, when executed by a processor, implements the steps of the smart contract decompilation code optimization method as described in any of the above embodiments.
[0158] In the several embodiments provided in the present application, it should be understood that the disclosed systems and methods can be implemented in other ways. For example, the device embodiments described above are only schematic. For example, the division of units is only a logical function division. There may be other division methods in actual implementation. For example, multiple units or components can be combined or integrated into another system, or some features can be ignored or not executed. Another point is that the mutual coupling or direct coupling or communication connection shown or discussed can be through some interfaces, indirect coupling or communication connection of devices or units, which can be electrical, mechanical or other forms.
[0159] The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, that is, they may be located in one place or distributed on multiple network units. Some or all of the units may be selected according to actual needs to achieve the purpose of the solution of this embodiment.
[0160] As described above, the above embodiments are only used to illustrate the technical solutions of the present invention, rather than to limit the same. Although the present invention has been described in detail with reference to the aforementioned embodiments, those skilled in the art should understand that the technical solutions described in the aforementioned embodiments may still be modified, or some of the technical features thereof may be replaced by equivalents. However, these modifications or replacements do not deviate the essence of the corresponding technical solutions from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A smart contract decompilation code optimization method, characterized in that: include: Obtain the decompiled code of the smart contract to be optimized, and construct a contract dependency graph based on the decompiled code of the smart contract to be optimized; Extracting fragments from the contract dependency graph to generate variable method code context; Based on the contract dependency graph, generate multiple thought chain prompts; Using a large language model to optimize the decompiled smart contract code to be optimized according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set and the preset contract attribute reasoning candidate set, and outputting the intermediate smart contract decompiled code; A preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized, and the target smart contract decompiled code is determined.
2. The smart contract decompilation code optimization method according to claim 1, characterized in that: The decompiling code based on the smart contract to be optimized and constructing a contract dependency graph includes: Perform type dependency identification on the decompiled smart contract code to be optimized, and output multiple contract dependency data corresponding to the decompiled smart contract code to be optimized; the multiple contract dependency data include type dependency, state dependency and control flow dependency; A contract dependency graph is constructed according to the type dependency, the state dependency and the control flow dependency.
3. The smart contract decompilation code optimization method according to claim 1, characterized in that: The variable method code context includes variable code snippets and method code snippets; extracting snippets from the contract dependency graph to generate the variable method code context includes: Perform code slicing on the contract dependency graph to generate variable code snippets; Perform call chain analysis on the contract dependency graph to generate method code snippets.
4. The smart contract decompilation code optimization method according to claim 2, characterized in that: The method of using a large language model to optimize the decompiled smart contract code to be optimized according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set, and the preset contract attribute reasoning candidate set, and outputting the intermediate smart contract decompiled code includes: Performing data extraction on the variable code snippet and the method code snippet, and outputting structural features and semantic information corresponding to the variable code snippet, and structural features and semantic information corresponding to the method code snippet; Taking the structural features and semantic information corresponding to the variable code snippet and the structural features and semantic information corresponding to the method code snippet as constraints, the preset variable type inference candidate set and the preset contract attribute inference candidate set are used to perform large language model inference to generate code optimization suggestions; The decompiled code of the smart contract to be optimized is optimized using a plurality of the thought chain prompts and the code optimization suggestions, and an intermediate smart contract decompiled code is output.
5. The smart contract decompilation code optimization method according to claim 1, characterized in that: The preset program analysis and verification technology includes a formal verification method and a violation rejection rule; the preset program analysis and verification technology is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized, and determine the target smart contract decompiled code, including: Perform symbolic execution on the decompiled smart contract code to be optimized and the intermediate smart contract decompiled code respectively, and generate a symbolic digest corresponding to the decompiled smart contract code to be optimized and a symbolic digest corresponding to the intermediate smart contract decompiled code; Using a formal verification method to determine whether the symbol digest corresponding to the decompiled code of the smart contract to be optimized and the symbol digest corresponding to the decompiled code of the intermediate smart contract are equivalent; If so, determining whether the decompiled code of the intermediate smart contract complies with the violation rejection rule; If it meets the requirements, the intermediate smart contract decompiled code is used as the target smart contract decompiled code.
6. The smart contract decompilation code optimization method according to claim 5, characterized in that: The violation of the rejection rules is specifically: ; Among them, π is the intermediate smart contract decompiled code, which represents the context containing a list that assigns variable types to expression patterns; e is the expression; θ is the variable type.
7. A smart contract decompilation code optimization system, characterized in that: include: An acquisition module is used to acquire the decompiled code of the smart contract to be optimized, and to construct a contract dependency graph based on the decompiled code of the smart contract to be optimized; An extraction module, used to extract fragments from the contract dependency graph and generate variable method code context; A generation module, used for generating a plurality of thought chain prompts based on the contract dependency graph; An optimization module, configured to optimize the decompiled smart contract code to be optimized by using a large language model according to the variable method code context, the plurality of thought chain prompts, the preset variable type reasoning candidate set, and the preset contract attribute reasoning candidate set, and output an intermediate smart contract decompiled code; The checking module is used to perform a consistency check on the intermediate smart contract decompiled code according to the smart contract decompiled code to be optimized by using a preset program analysis and verification technology to determine the target smart contract decompiled code.
8. A computer device, characterized in that: It includes a memory and a processor, wherein a computer program is stored in the memory, and when the computer program is executed by the processor, the processor executes the steps of the smart contract decompilation code optimization method as described in any one of claims 1 to 6.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed, the smart contract decompilation code optimization method according to any one of claims 1 to 6 is implemented.
10. A computer program product, characterized in that The computer program product includes a computer program stored on a non-transitory computer-readable storage medium, and the computer program includes program instructions, wherein when the program instructions are executed by a computer, the computer is caused to execute the smart contract decompilation code optimization method as described in any one of claims 1-6.
Citation Information
Patent Citations
Intelligent contract optimization method and device based on source codes
CN112631656A
Smart contract optimization method and device and readable storage medium
CN115657945A
Intelligent contract vulnerability detection method, apparatus and device, and mobile storage medium
CN119150287A
Cited By
Code optimization method, electronic equipment, storage medium and program product
CN120540966A
Full-automatic code programming method and system based on large model
CN121541867A