A smart contract code completion method and device based on a graph neural network
By constructing a code representation graph and training a gated graph neural network model through a smart contract code completion method based on graph neural networks, the problem of existing IDEs being unable to provide targeted and secure code completion is solved, thereby improving the robustness and security of smart contracts.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- SUN YAT SEN UNIV
- Filing Date
- 2021-12-30
- Publication Date
- 2026-06-16
AI Technical Summary
Existing smart contract integrated development environments (IDEs) cannot provide targeted and secure code completion features, cannot handle contextual dependencies and data dependencies, and pose potential security vulnerabilities.
By employing a graph neural network-based approach, a code representation graph of smart contract source code is constructed. Combined with industry security practices, a gated graph neural network model is trained to perform code completion prediction and generate a list of complement words.
It achieves highly targeted and secure code completion, which can quickly predict the completion words of smart contracts, improve the robustness and security of smart contracts, and reduce the risk of potential losses.
Smart Images

Figure CN114296787B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of Ethereum technology, and in particular to a method and apparatus for smart contract code completion based on graph neural networks. Background Technology
[0002] In recent years, Ethereum technology, with its decentralized, immutable, transparent, and secure characteristics, has become the cornerstone for realizing the Internet of Value. Smart contracts deployed on Ethereum also possess decentralized and immutable features. Smart contracts have gained widespread attention and have been applied in many fields, covering financial products, online games, real estate, transportation, and logistics.
[0003] Because all smart contracts deployed on Ethereum are freely accessible through public methods, any functional defects or vulnerabilities within a smart contract could lead to catastrophic losses. However, most existing smart contract integrated development environments (IDEs) are simply extensions added to traditional IDE tools. Their code completion features only support fuzzy matching-based auto-completion, failing to handle contextual relevance and data dependencies, and unable to obtain deep semantic connections to provide more targeted content.
[0004] Besides failing to provide more targeted content, existing smart contract IDEs lack consideration for code security when providing code completion features. Vulnerabilities hidden in the source code of smart contracts may be exploited, causing huge losses. Summary of the Invention
[0005] The purpose of this invention is to provide a method and apparatus for completing smart contract code based on graph neural networks, so as to solve the technical problem that existing technologies cannot complete smart contract code in a targeted and secure manner.
[0006] The objective of this invention can be achieved through the following technical solutions:
[0007] A smart contract code completion method based on graph neural networks includes the following steps:
[0008] Construct multiple smart contract source code datasets based on the version numbers of the smart contract source code;
[0009] Construct corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices;
[0010] Construct a code completion model based on a gated graph neural network, and train the code completion model using the code representation graph to obtain the trained code completion model;
[0011] The code representation graph corresponding to the smart contract to be completed is embedded into the trained code completion model to perform code completion prediction and obtain a list of words to be completed.
[0012] Optionally, multiple smart contract source code datasets can be constructed based on the version number of the smart contract source code, including:
[0013] Obtain the source code of smart contracts on Ethereum, use Ethereum security analysis tools to detect the source code to obtain secure smart contracts, and divide the smart contracts into multiple smart contract source code datasets according to the version number of the source code.
[0014] Optionally, constructing corresponding code representation diagrams based on the semantic information of smart contract source code in each dataset and industry security practices includes:
[0015] Parse the source code of each smart contract in each dataset into the corresponding abstract syntax tree;
[0016] The nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code.
[0017] Code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph.
[0018] Optionally, the semantic edge includes at least:
[0019] Control flow edges and data flow edges, wherein the control flow edges represent control flow information in the smart contract source code, and the data flow edges represent data flow information in the smart contract source code.
[0020] Optionally, the control flow edge includes at least the following control flow types:
[0021] The statements include if, while, do while, for, assert, and require.
[0022] Optionally, selecting code snippets that conform to industry security practices from the abstract syntax tree, and adding feature edges between nodes in the code snippets in the code representation graph includes:
[0023] Based on industry security practices related to smart contract execution, code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges indicating compliance with industry security practices are added between nodes contained in the code snippets in the code representation graph.
[0024] The present invention also provides a smart contract code completion device based on graph neural networks, comprising:
[0025] The dataset building module is used to build multiple smart contract source code datasets based on the version number of the smart contract source code;
[0026] The code representation graph construction module is used to construct corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices;
[0027] The code completion model training module is used to construct a code completion model based on a gated graph neural network, and to train the code completion model using the code representation graph to obtain the trained code completion model.
[0028] The code completion prediction module is used to embed the code representation graph corresponding to the smart contract to be completed into the trained code completion model to perform code completion prediction and obtain a list of words to be completed.
[0029] Optionally, the dataset construction module constructs multiple smart contract source code datasets based on the version number of the smart contract source code, including:
[0030] The dataset construction module obtains the source code of smart contracts on Ethereum, uses Ethereum security analysis tools to detect the source code of smart contracts to obtain secure smart contracts, and divides the smart contracts into multiple smart contract source code datasets according to the version number of the source code.
[0031] Optionally, the code representation graph construction module constructs corresponding code representation graphs based on the semantic information of the smart contract source code in each dataset and industry security practices, including:
[0032] The code representation graph construction module parses the source code of each smart contract in each dataset into a corresponding abstract syntax tree;
[0033] The nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code.
[0034] Code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph.
[0035] Optionally, the code representation graph construction module filters code snippets that conform to industry security practices from the abstract syntax tree, and adds feature edges between nodes in the code snippets in the code representation graph, including:
[0036] The code representation graph construction module selects code snippets that conform to industry security practices from the abstract syntax tree based on industry security practices related to smart contract execution, and adds feature edges representing compliance with industry security practices between nodes contained in the code snippets in the code representation graph.
[0037] This invention provides a method and apparatus for smart contract code completion based on graph neural networks. The method includes the following steps: constructing multiple smart contract source code datasets based on the version number of the smart contract source code; constructing corresponding code representation graphs based on the semantic information of the smart contract source code in each dataset and industry security practices; constructing a code completion model based on a gated graph neural network, and training the code completion model using the code representation graphs to obtain a trained code completion model; embedding the code representation graph corresponding to the smart contract to be completed into the trained code completion model, and performing code completion prediction to obtain a list of words to be completed.
[0038] In view of this, the beneficial effects of this invention are:
[0039] This invention divides smart contracts into multiple datasets based on their source code version numbers. This allows the code completion model to learn the syntactic features of different versions of smart contract source code, providing developers with a list of words to complete based on their current version. When constructing the code representation graph based on the semantic information of the smart contract source code in each dataset, the semantic information in the source code is taken into consideration. This allows the code completion model to better understand the semantic information in the source code and quickly predict the code words used to complete the smart contract. Furthermore, the construction of the code representation graph incorporates industry security practices, adding best practices to the code completion model. This allows it to learn code with good programming structure and improve the security of the predicted code word list for smart contracts. Attached Figure Description
[0040] Figure 1 This is a flowchart illustrating the smart contract code completion method of the present invention;
[0041] Figure 2 This is a flowchart illustrating an embodiment of the smart contract code completion method of the present invention;
[0042] Figure 3(a) is an example diagram of the Abstract Syntax Tree (AST) obtained by converting the source code of the smart contract in an embodiment of the present invention;
[0043] Figure 3(b) is the control flow graph (CFG) obtained by converting the source code of the smart contract in an embodiment of the present invention.
[0044] Figure 3(c) is a data flow diagram (DFG) obtained by converting the source code of the smart contract in an embodiment of the present invention.
[0045] Figure 4 This is a schematic diagram illustrating the best security practice mode in the smart contract code completion method of the present invention;
[0046] Figure 5(a) is a code representation diagram in the smart contract code completion method of the present invention;
[0047] Figure 5(b) is a schematic diagram of the node status in the smart contract code completion method of the present invention;
[0048] Figure 5(c) is a schematic diagram of the adjacency matrix in the smart contract code completion method of the present invention;
[0049] Figure 6 This is a schematic diagram of the aggregation and update operations in the smart contract code completion method of the present invention;
[0050] Figure 7 This is a schematic diagram of the smart contract code completion device of the present invention. Detailed Implementation
[0051] Terminology Explanation:
[0052] Abstract Syntax Tree (AST): In computer science, an abstract syntax tree, or syntax tree, is a tree-like representation of the abstract syntactic structure of source code, specifically the source code of a programming language. Each node in the tree represents a structure within the source code. The syntax is described as abstract because it doesn't represent every detail of the actual syntax.
[0053] Control Flow Graph (CFG): A control flow graph, also called a control flow diagram, is an abstract representation of a process or program. It is an abstract data structure used in compilers and maintained internally by the compiler. It represents all paths that a program will traverse during execution. It uses a graph to represent the possible flow of execution of all basic blocks within a process, and can also reflect the real-time execution process of a process.
[0054] Data Flow Graph (DFG): A data flow graph is a widely used tool in program analysis, where nodes represent program variables and edges represent the dependencies between these variables. Unlike abstract syntax trees (ASTs), for the same source code, the data flow is the same under different abstract syntax trees. This code structure provides crucial semantic information for code understanding.
[0055] Context Dependency: Context can be understood as the runtime environment. The meaning of a word depends on the embedded context to be realized. The phenomenon that a word cannot be understood on its own reflects a linguistic attribute of the word.
[0056] SWC Registry: The SWC Registry is an essential knowledge base for Ethereum security professionals and developers. It is a classification and test case set of Ethereum smart contract security vulnerabilities provided by SmartContractSecurity, containing descriptions and consequences of 37 common security issues in Ethereum Solidity smart contract development.
[0057] Gas: Cryptocurrency transactions generally incur transaction fees, which are paid directly as a fee in Ethereum. While Ethereum transaction fees appear similar, requiring the payment of a certain amount of Ethereum, the internal operation utilizes a concept called Gas. Ethereum uses smart contracts, and transactions execute commands step-by-step according to the smart contract's rules. Each command execution incurs a certain cost, measured in Gas. Furthermore, different commands consume different amounts of Gas.
[0058] Graph embedding is a process of mapping graph data (typically high-dimensional dense matrices) to low-dimensional dense vectors, effectively addressing the problem of inefficiently inputting graph data into machine learning algorithms. Graph embedding transforms attribute graphs into vectors or sets of vectors. Embedding should capture the graph's topology, vertex-to-vertex relationships, and other relevant information about the graph, subgraphs, and vertices.
[0059] To facilitate understanding of the present invention, a more complete description will be given below with reference to the accompanying drawings. Preferred embodiments of the invention are shown in the drawings. However, the invention can be implemented in many different forms and is not limited to the embodiments described herein. Rather, these embodiments are provided so that this disclosure will be thorough and complete.
[0060] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains. The terminology used herein in the specification of this invention is for the purpose of describing particular embodiments only and is not intended to be limiting of the invention. The term "and / or" as used herein includes any and all combinations of one or more of the associated listed items.
[0061] This invention provides a method and apparatus for completing smart contract code based on graph neural networks, in order to solve the technical problem that existing technologies cannot complete smart contract code in a targeted and secure manner.
[0062] Nick Szabo first proposed the concept of smart contracts in 1993. He envisioned introducing real-world concepts such as contracts and agreements into the digital realm to constrain the behavior of parties involved in digital finance and punish violators. Therefore, the conditions defined in a smart contract and its execution should be traceable and irreversible. This minimizes the need for trusted intermediaries and reduces the risk of malicious intent or accidental actions, ensuring the reliability of any business transactions implicit in the smart contract. However, due to the lack of digital systems and technologies capable of supporting smart contracts at the time, the working theory of smart contracts remained unrealized for a long time.
[0063] Ethereum technology is a distributed ledger technology that combines data blocks sequentially into a chain-like data structure, using cryptography to ensure immutability and unforgeability. It relies on cryptographic algorithms to guarantee the secure transfer of value, hash chains and timestamp mechanisms to ensure data traceability and immutability, and consensus algorithms to guarantee the consistency of block data among nodes. With its distributed, transparent, and secure characteristics, Ethereum technology enables convenient, fast, and low-cost value exchange over the internet, forming the cornerstone of the value internet. It allows for trusted transactions without intermediaries in a mutually distrustful environment, representing a novel application model of computer technologies such as distributed storage, peer-to-peer transmission, consensus mechanisms, and cryptographic algorithms.
[0064] Ethereum's decentralized and immutable nature ensures that smart contracts deployed on it possess the same characteristics. This guarantees that contract execution is difficult to maliciously tamper with, making the execution results authoritative and trustworthy. Through Ethereum technology, people can effectively implement these constraints of smart contracts without relying on external forces. The concept of smart contracts is also gradually shifting towards the understanding of computer programs running on Ethereum; essentially, it is a piece of code that can be executed based on pre-defined triggers. This code is typically written in high-level Turing-complete programming languages such as Solidity, Serpent, and Vyper.
[0065] Ethereum, the first widely adopted smart contract application platform, boasts a robust ecosystem and broad applicability across various industries, representing an upgrade to the internet. By establishing a foundational layer of ultimate abstraction—the Ethereum language—built into Ethereum itself, anyone can create smart contracts and decentralized applications, defining their own ownership rules, transaction methods, and state transition functions. Due to the expressive power offered by high-level programming languages and the security guarantees of the underlying consensus protocol, smart contracts have gained widespread attention and are applied in numerous fields, including financial products, online games, real estate, transportation, and logistics.
[0066] Integrated Development Environments (IDEs) are a fundamental paradigm for modern software engineers because they provide a suite of services that accelerate software development. Currently, there are relatively few tools to assist with smart contract development. The most popular IDE is Remix, the open-source online IDE officially recommended by Ethereum. It allows users to compile, test, and deploy Ethereum smart contracts within a web browser using the Solidity language. EthFiddle is an online debugging tool that supports online editing and testing of Solidity code snippets. Traditional IDEs support building smart contract development environments by installing extensions, such as IntelliJ IDEA, JetBrains IDE, Eclipse, Atom, and Visual Studio Code.
[0067] Code completion is one of the most useful features in IDEs. It suggests the next possible code marker based on existing code in context, such as a method call or object field. According to research by Murphy, Kersten, and Findlater, Eclipse IDE users use Eclipse's code completion as much as they use common editing commands (such as copy and paste) because it reduces the amount of typing required and eliminates spelling errors. Code completion has become an important research topic for accelerating modern software development. Most existing smart contract IDEs are constructed by adding extensions to traditional IDE tools; therefore, their code completion functions only support fuzzy matching-based auto-completion, unable to handle contextual relevance and data dependencies, and unable to obtain deep semantic connections to provide more targeted content.
[0068] Besides failing to provide more targeted content, existing smart contract IDEs lack consideration for code security when offering code completion features. Because all smart contracts deployed on Ethereum are freely accessible through their public methods, any functional defects or vulnerabilities within a contract can lead to catastrophic losses. For example, the infamous DAO attack in 2016 resulted in the theft of $60 million worth of Ether due to a code vulnerability. In July 2017, the Ethereum wallet Parity was hacked, resulting in the theft of 153,000 Ether (approximately $32 million), and in November of the same year, another security vulnerability was exposed, leading to the freezing of hundreds of millions of dollars worth of Ethereum. Although there has been much research on smart contract vulnerability detection, the problem is that smart contracts are immutable. Once deployed, due to the design of the consensus protocol, no patches can be applied to the original smart contract, and hidden vulnerabilities can be exploited, leading to unpredictable losses. While deploying a new smart contract can remedy the situation, it cannot undo the damage already done, and the process is far more complex and may incur higher transaction costs. Improving the robustness of smart contracts is an urgent practical problem that should be addressed not only in the testing phase of smart contracts but also in the development process.
[0069] Please see Figure 1 This invention provides an embodiment of a smart contract code completion method based on graph neural networks, comprising the following steps:
[0070] S100: Construct multiple smart contract source code datasets based on the version number of the smart contract source code;
[0071] S200: Construct corresponding code representation diagrams based on the semantic information of smart contract source code in each dataset and industry security practices;
[0072] S300: Construct a code completion model based on a gated graph neural network, and train the code completion model using the code representation graph to obtain the trained code completion model;
[0073] S400: Embed the code representation graph corresponding to the smart contract to be completed into the trained code completion model, and perform code completion prediction to obtain a list of words to be completed.
[0074] In step S100, multiple smart contract source code datasets are constructed based on the version numbers of the smart contract source code. In this embodiment, the source code of a smart contract on Ethereum is obtained, and the source code is tested using Ethereum security analysis tools to obtain secure smart contracts. The smart contracts are then divided into multiple smart contract source code datasets based on their version numbers.
[0075] Specifically, the process begins by obtaining publicly available smart contract source code data from the Ethereum platform (Etherscan), and then using popular Ethereum security analysis tools such as Mythril and Securify to examine this smart contract source code data and filter out secure smart contracts.
[0076] It's worth noting that Mythril is an Ethereum-recommended smart contract security analysis tool that uses symbolic execution to detect various security vulnerabilities in smart contract source code. It's integrated into IDEs such as Remix and Truffle. Securify, developed by ChainSecurity, is a security analysis tool that supports 38 vulnerabilities and implements novel context-dependent static analysis. However, it can only analyze smart contract source code written in Solidity version 0.5.8 or higher.
[0077] It's worth noting that each major version of Solidity introduces upgrades that are incompatible with previous versions, resulting in significant syntax differences between versions. For example, the recently updated version 0.8 integrates SafeMath and new error handling. SafeMath is a set of application programming interfaces (APIs) developed by Openzeppelin to help mitigate the risk of arithmetic overflows. In version 0.8, users don't need to do anything to activate Solidity's integrated SafeMath. For example, simply writing `a+b` will automatically roll back the transaction in case of an overflow. Therefore, after obtaining secure smart contract source code data, it's necessary to divide the smart contract source code dataset according to the Solidity major version number used by the smart contract (0.5, 0.6, 0.7, and 0.8), resulting in multiple smart contract source code datasets, each corresponding to a specific Solidity major version number.
[0078] In step S200, a corresponding code representation graph is constructed based on the semantic information of the smart contract source code in each dataset and industry security practices. Specifically, the source code of each smart contract in each dataset is parsed into a corresponding abstract syntax tree; the nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code; code fragments that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between the nodes in the code fragments in the code representation graph.
[0079] In a preferred embodiment, code snippets conforming to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph, including:
[0080] Based on industry security practices related to smart contract execution, code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges indicating compliance with industry security practices are added between nodes contained in the code snippets in the code representation graph.
[0081] With the remarkable success of graph neural networks, they have been extensively studied in various fields such as graph classification, program analysis, and graph embedding. Existing research shows that program source code can be converted into symbolic graph representations, which can preserve the semantic relationships between program elements, such as data dependencies and control dependencies.
[0082] This embodiment constructs a code representation graph from the semantics and semantic information in the smart contract source code, and uses a graph-based learning method to capture and reason about the program's control, data, and calling dependencies, so that the smart contract source code can be well understood in the code completion model.
[0083] Commonly used code representation graph structures include: Abstract Syntax Tree (AST), Control Flow Graph (CFG), and Data Flow Graph (DFG). Every programming language has a context-free syntax tree (AST), which can be used to parse source code into an AST. An AST is an intermediate table in the compilation process; the syntax information of functions is stored in a tree. CFG and DFG are abstract representations of a program. CFG graphically represents the possible execution paths of all basic blocks in a process, reflecting the real-time execution of a process. Nodes in a DFG graph represent variables, and edges indicate where the values of these variables come from, describing the data flow process in the program from the perspective of data transmission and processing.
[0084] In order to reduce the accuracy loss caused by redundant statements such as comments and blank lines in the code when constructing the code representation graph, this embodiment uses the Solidity-parser-antlr parser to parse the smart contract source code into the Abstract Syntax Tree (AST) format.
[0085] It's worth noting that Solidity-parser-antlr is a Solidity parser built on a robust ALTLR4 grammar. An Abstract Syntax Tree (AST) is a tree where each non-leaf node corresponds to a non-terminal structure in a context-free grammar, such as for and if statements; each leaf node corresponds to a terminal structure in a context-free grammar, such as variable names and operators.
[0086] For example, the following source code:
[0087]
[0088] The abstract syntax tree (AST), control flow graph (CFG), and data flow graph (DFG) obtained from the above source code conversion are shown in Figures 3(a), 3(b), and 3(c), respectively.
[0089] AST (Abstract Syntax Tree) uses a tree representation of the source code abstract syntax structure. Since it relies on the tree structure, using AST alone to construct a code representation graph is insufficient to fully depict the rich semantics between nodes. In this embodiment, nodes in the AST are extracted as nodes in the code representation graph, and various types of semantic edges are added to represent different types of control flow and data flow. This allows the code representation graph model to better describe the semantic relationships between codes, enabling the code completion model to understand the true meaning of "semantics."
[0090] It's worth noting that this embodiment doesn't directly use a control flow graph because control flow graphs typically have fewer edges than those in an AST. For graph neural networks, fewer edges mean less information transmitted between nodes and fewer node state updates, which is detrimental to the semantic learning of the code completion model. Furthermore, most nodes in a control flow graph are statement expressions rather than single identifiers, making it easy to lose semantic information within the nodes. The reason for not directly using a data flow graph is to maintain consistency with the data structure of the control flow information.
[0091] When constructing the code representation graph of smart contract source code, the following types of edges can be constructed in this embodiment:
[0092] 1) Child: Based on the AST, each child node is linked from a non-terminal AST node as the starting endpoint.
[0093] 2) Parent: Connects to its parent node starting from a non-root node.
[0094] 3) NextSib: Connects a node to its next sibling node (in order of arrangement in the AST from left to right). This is because the code representation graph does not consider the order of nodes, so it is necessary to provide the order of the child nodes.
[0095] In addition to the edges representing sequential structures mentioned above, several semantic edges containing semantic information were also constructed. The advantage of doing so is that in the subsequent training of the code completion model, the semantic information is explicitly exposed as a structured input, which helps the code completion model understand the semantic information of the smart contract source code.
[0096] 4) NextToken: Starting from one terminal node in the AST and ending at the next terminal node. That is, the NextToken edge connects the identifier token to the next token in the corresponding source code.
[0097] 5) NextUsed: Connects the variable node to its next use. For example, if a variable is declared as "int x;" on one line and used as "x=1;" on the third line, this indicates useful data flow information in the AST.
[0098] 6) LastRead: Connects the variable node to the last time it was read. It can be said to be more granular than NextUsed. Here it specifically refers to the reading of values. For example, if variable x has "if(x>y)" in the fifth line and "x=1" in the sixth line, then the x node will have a LastRead edge for both times.
[0099] 7) ComputedFrom: Represents an assignment statement, such as "x=y+z", then there is a ComputedFrom edge between node x and nodes y and z respectively.
[0100] Furthermore, the code representation graph in this embodiment also includes control flow edges to capture the control semantics of the code. Specifically, control flow edges are constructed for conditional statements or security handle statements. To represent the control flow information in the smart contract source code, this embodiment mainly focuses on the following six basic control flow types: if statement, while statement, do while statement, for loop, assert statement, and require statement. Other control flow structures are ignored because they rarely appear in Solidity programs. The constructed control flow edges representing control flow information are as follows:
[0101] In an if statement, there must be at least an if condition and an if clause that is true. At most, in addition to an else clause, there may be several else if conditions and else if clauses that are true. The edges corresponding to the if statement are:
[0102] 8) Condition: Points from the node of the if condition clause or else if condition to the next node in the clause. For example, in "if (x>y)", there is a Condition edge between the if node and the x node, and there is a Condition edge between x and the node.
[0103] 9) CondTrue: Points from a node in an if condition to the next node in the clause where the else if condition is true. For example, if (x>y) a=b, then there is a ConTrue edge between node a and node b.
[0104] 10) CondFalse: Points from the node in the else clause to the next node in the clause.
[0105] Within a while statement, there exists a while condition expression and a statement executed after the expression is true. The edges corresponding to the while statement are:
[0106] 11) WhileCond: Points from the node in the while conditional clause to the next node in the clause.
[0107] 12) WhileExec: Within the executed statement, the node points to the next node within the executed statement.
[0108] The Do while statement is similar to the while statement, with a statement to be executed first and a while condition expression. The WhileCond edge has already been constructed, and the other corresponding one is Do.
[0109] 13) Do: The node within the executed statement points to the node within the scope of the next executed statement.
[0110] In a for statement, there are control parts, such as initialization, test conditions, and iteration statements, as well as statements to be executed, which create two types of edges:
[0111] 14) ForControl: The nodes of the initialization, test conditions and iteration statements in the control section are connected by ForControl edges in the order from left to right in the AST.
[0112] 15) ForExec: The nodes within the executed statement in the for statement are connected by ForExec edges in the order from left to right in the AST.
[0113] The Assert() and Require() statements are functions used to determine whether a condition is met; therefore, the corresponding edges are:
[0114] 16) Assert: Points from a node inside the Assert() function to the next node inside the function.
[0115] 17) Require: Points from the node inside the Require() function to the next node inside the function.
[0116] 18) BestPractice: Used to connect nodes in code that follow industry best practices for Solidity development. See below for a detailed definition.
[0117] Since Ethereum security analysis and detection tools are not foolproof, in this embodiment, the smart contract source code that has undergone security analysis and detection during the preprocessing stage cannot be guaranteed to be completely free of security vulnerabilities. For some deeply hidden vulnerabilities or those with complex test cases, Mythril may have difficulty detecting them. Furthermore, even smart contracts that are currently free of security vulnerabilities may not necessarily have a secure and reliable programming structure.
[0118] Currently, there are common or widely used typical security design patterns in smart contract programming. These patterns address typical problems and security vulnerabilities related to smart contract execution. For example, some best security practices summarized in the industry include: the "Checks-Effects-Interactions" pattern, the "fail-safe" pattern, contract minimization, contract modularity, and "disabling tx.origin for authentication," etc. These patterns describe solutions to typical security problems and can be applied to mitigate typical attack scenarios.
[0119] Analysis of existing smart contracts shows that major platforms primarily focus on financial contracts. That is, the source code of most smart contracts defines how assets are moved. Therefore, correctly executing smart contracts is crucial. However, smart contracts have several specific operating rules. One of these rules is that the more complex the source code of a smart contract, the more money is required to execute it. Therefore, to save budgets, smart contract source code is usually short and concise, but this sacrifices some security performance. Thus, writing high-performance and secure smart contracts in Ethereum is a challenging task.
[0120] The code completion model in this embodiment is based on graph neural networks. It integrates expert knowledge with industry best practices to perform security verification on smart contracts in the dataset, and marks code blocks that conform to best practice patterns. This allows the code completion model to learn these best practice programming methods and obtain more accurate and detailed domain knowledge.
[0121] The Check-Effects-Interaction pattern, an industry best practice for security, describes how smart contract code should be structured to avoid side effects and harmful execution behavior. It defines a sequence of operations: first, all prerequisites should be checked; then, the smart contract's state should be changed; and finally, interaction with other smart contracts should be allowed. Checking prerequisites typically uses the `assert()` and `require()` functions; therefore, the code representation graph can be constructed using `assert` and `require` edges. Updating the smart contract's state can be represented using `ComputedFrom` edges. This embodiment focuses on monetary transactions with other smart contracts, specifically the `call()`, `send()`, and `transfer()` functions. However, the `address.call()` function is not recommended in the industry because it forwards all remaining Gas by default, giving the called smart contract more room for potentially malicious operations. In this embodiment, `address.send()` and `address.transfer()` are preferred for transfers because these functions limit the amount of Gas forwarded. Therefore, this operation can be identified simply by using the identifiers "send" and "transfer" from the send() and transfer() functions for keyword matching.
[0122] Code representation diagram conforming to best security practices as follows Figure 4 As shown in the diagram, the AST obtained from the transformation of the smart contract source code is matched and filtered to select code snippets that conform to the best security practice model. The code snippets that conform to the best security practice model are shown below:
[0123]
[0124] When constructing the code representation graph, a BestPractice edge is constructed between the nodes of this type of code fragment as a feature edge that conforms to industry best security practices.
[0125] It is worth noting that if a piece of code conforms to the Check-Effects-Interaction pattern, then all nodes in that piece of code will have BestPractice edges added between each pair of nodes in the order of program execution.
[0126] This embodiment uses the Check-Effects-Interaction pattern to avoid static condition vulnerabilities, such as reentrancy vulnerabilities and transaction order dependencies. If changing the execution order of the program affects the result, it constitutes a race condition.
[0127] In step S300, a code completion model based on a gated graph neural network is constructed, and the code completion model is trained using the code representation graph to obtain the trained code completion model.
[0128] In this embodiment, a code completion model based on a gated graph neural network is constructed. The code representation graph is embedded into the code completion model, and the code completion model is trained using the code representation graph until a well-trained code completion model is obtained.
[0129] The key idea behind Graph Neural Networks (GNNs) is to embed node representations from local domains through domain aggregation. Graph Neural Networks are well-suited for learning code representation graphs because they are designed to automatically extract features from the rich node connections in graph data, effectively handling the discontinuous features of graph data.
[0130] Techniques based on different aggregation domain information include graph convolutional neural networks, gated graph neural networks (GGNNs), and their variants. GGNNs employ gated recurrent units (GRUs) as recursive functions, reducing recursion to a fixed number of steps. GGNNs introduce a learnable parameter w for different types of edges, enabling them to handle various graphs that traditional GNNs cannot, making them more suitable for data, semantics, and graph structures. Therefore, in this embodiment, a gated graph neural network can be used to learn the embeddings of a code representation graph.
[0131] Please refer to Figures 5(a), 5(b), and 5(c). Given an embedding graph G = (V, E, A), where V is a set of nodes and E = (E1, ..., E2), ... k Let be a list of directed edges representing graph G, where k is the number of edge types, A is an N×N adjacency matrix of graph G, where N represents the number of nodes, and B, C, B', and C' represent the edge types. In Figure 5(b), different colors represent different edge types, and edges of the same color are of the same type. Solid arrows represent outgoing edges, and dashed arrows represent incoming edges.
[0132] In this embodiment, to ensure that each node in the code representation graph can simultaneously receive messages from both the predecessor and successor nodes during the message propagation phase, the adjacency matrix of the code representation graph is defined by considering both the outgoing and incoming adjacency matrices A=[A (out) A (in) ], where the in-direction adjacency matrix A (in) This represents the forward propagation of a message, with the outgoing adjacency matrix A.(out) This indicates the reverse propagation of the message.
[0133] In this embodiment, the embedded graph G maps the adjacency matrix of the code representation graph G to a low-dimensional vector or vector set. The gated graph neural network GGNN uses vectors. Label the state vector of node v∈V The initial representation of .
[0134] In this embodiment, the gated graph neural network (GGNN) includes two key operations on nodes at each layer: aggregation and update. Aggregation aggregates information from neighboring nodes, while update updates the node's state representation. The aggregation function AGG() can be one of {MEAN(), MAX(), SUM(), CONCAT()}, used to aggregate information from different edge types and calculate the node's embedded state vector for the next time step.
[0135] It is worth noting that MEAN() means to calculate the average, MAX() means to calculate the maximum value, SUM() means to calculate the sum, and CONCAT() means to concatenate each vector in order, similar to concatenation in strings.
[0136] In this embodiment, in order to accommodate more semantic information when constructing the code representation graph, the summation function SUM() is selected as the aggregation function, and the update operation is selected as the gated recurrent unit (GRU).
[0137] During the initialization operation, Copy it to the first dimension of matrix A, filling empty values with 0. Let T be the total time step of the aggregation operation. At each time step t≤T, all nodes rely on the type and direction of the edges to transmit information. Let p represent the p-th matrix. By definition, the number of adjacency matrices is equal to the edge type, meaning the elements in the matrix are:
[0138]
[0139] in It's weight. Let j be the deviation, and j be the node number, where 1 ≤ j ≤ N.
[0140] The remaining steps involve the gated loop unit merging information from the node containing all types of information and the node state obtained from the previous time step. To obtain the node state of the current node :
[0141]
[0142] The aggregation function AGG() is the summation function SUM(). The GRU propagation calculation process is omitted and is performed in each iteration. Continuously updated, such as Figure 6 As shown.
[0143] Final node state representation of node set V :
[0144]
[0145] The generated final state can be used as input for any prediction layer, such as for node, connection, and graph-level predictions. In this embodiment, node-level predictions need to be performed to determine the next codeword. Therefore, the node set V is ultimately represented as being mapped into the node space, and a probability distribution for the next node is generated through a softmax layer. The calculation formula is as follows, where, and The parameter is used as the next token. The nodes in the probability distribution are sorted in descending order of probability value to form a list of predicted NextTokens, which is the list of supplementary words used to complete the smart contract.
[0146]
[0147] It is worth noting that in this embodiment, the softmax layer generates the probability distribution of the next node. For example, the vector output by the original graph neural network is:
[0148] ,
[0149] The new output obtained after passing through the softmax layer is:
[0150] ,
[0151] The probability of the result being 3 is 0.88, the probability of the result being 1 is 0.12, and the probability of the result being -3 is 0.
[0152] In this embodiment, The operation is to obtain the final representation of the node set V. Mapping to the node space is similar to calculating y from the given x in y=kx+b. The resulting y is a series of nodes (3,1,-3). This series of nodes is then put into a softmax layer to obtain the probability distribution of this series of nodes becoming the next node (0.88,0.12,0).
[0153] In step S400, the code representation graph corresponding to the smart contract to be completed is embedded into the trained code completion model, and code completion prediction is performed to obtain a list of words to be completed.
[0154] Based on the method of generating code representation graphs, a corresponding code representation graph is constructed according to the semantic information of the source code of the smart contract to be completed and industry security practices. The code representation graph corresponding to the source code of the smart contract to be completed is embedded into the trained code completion model to obtain a list of words to complete the smart contract. The smart contract to be completed can be completed based on the list of words.
[0155] The smart contract code completion method based on graph neural networks provided in this embodiment divides smart contracts into multiple datasets according to the version number of the smart contract source code. This allows the code completion model to learn the syntactic features of different versions of smart contract source code and provide developers with a list of words to complete based on the version they are currently using. When constructing the code representation graph based on the semantic information of the smart contract source code in each dataset, the semantic information in the source code is taken into consideration. The code completion model can better predict the code words used to complete the smart contract by better understanding the semantic information in the source code. When constructing the code representation graph of the smart contract source code, industry security practices are incorporated into the code completion model. Best security practices are added to the code completion model, which can learn code with good programming structure and improve the security of predicted code words for smart contracts.
[0156] Please see Figure 2 In this embodiment, a method combining graph neural networks and expert knowledge is used for code completion of smart contracts. Specifically, program analysis methods are used to represent the source code into a code graph, using the abstract syntax tree generated from the source code as nodes, and control flow, data flow, and industry best practices as semantic edges. The code representation graph of the smart contract to be completed is embedded into a gated graph neural network, and node regression prediction of the NextToken table is performed for code completion.
[0157] This embodiment focuses on different solidity versions of smart contract source code, forming a more intelligent and user-friendly development environment. By dividing the smart contract source code dataset according to solidity version number in the early stage of model training, the code completion model can learn the syntactic features of each solidity version in a targeted manner, and provide developers with a list of words to complete that match the version they are currently using.
[0158] In this embodiment, the algorithm is designed from the perspective of the essence of smart contracts and software engineering, so that the model can well describe the relationships between entities, that is, enable the model to understand the true meaning of "semantics". This is reflected in the use of graphs for program representation. In addition to using ASTs as nodes in the graph, semantic edges for data flow and control flow are also considered for adding to the graph.
[0159] Security is a crucial indicator for smart contracts, and the development environment needs targeted support. This embodiment takes into account the security of smart contracts. By incorporating industry best security practices into the learning model, the code completion model learns well-structured code snippets in a targeted manner. Therefore, the list of words to be completed provided to developers during code completion can guide them to program according to standardized paradigms, resulting in smart contracts with higher security.
[0160] Please see Figure 7 The present invention also provides an embodiment of a smart contract code completion device based on graph neural networks, comprising:
[0161] Dataset construction module 11 is used to construct multiple smart contract source code datasets based on the version number of the smart contract source code;
[0162] Code representation graph construction module 22 is used to construct corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices;
[0163] The code completion model training module 33 is used to construct a code completion model based on a gated graph neural network, and to train the code completion model using the code representation graph to obtain the trained code completion model.
[0164] The code completion prediction module 44 is used to embed the code representation graph corresponding to the smart contract to be completed into the trained code completion model to perform code completion prediction and obtain a list of words to be completed.
[0165] In a preferred implementation, the dataset construction module constructs multiple smart contract source code datasets based on the version number of the smart contract source code, including:
[0166] The dataset construction module obtains the source code of smart contracts on Ethereum, uses Ethereum security analysis tools to detect the source code of smart contracts to obtain secure smart contracts, and divides the smart contracts into multiple smart contract source code datasets according to the version number of the source code.
[0167] In a preferred embodiment, the code representation graph construction module constructs corresponding code representation graphs based on the semantic information of the smart contract source code in each dataset and industry security practices, including:
[0168] The code representation graph construction module parses the source code of each smart contract in each dataset into a corresponding abstract syntax tree;
[0169] The nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code.
[0170] Code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph.
[0171] In a preferred embodiment, the code representation graph construction module filters code snippets that conform to industry security practices from the abstract syntax tree, and adds feature edges between nodes in the code snippets in the code representation graph, including:
[0172] The code representation graph construction module selects code snippets that conform to industry security practices from the abstract syntax tree based on industry security practices related to smart contract execution, and adds feature edges representing compliance with industry security practices between nodes contained in the code snippets in the code representation graph.
[0173] The smart contract code completion device based on graph neural networks provided in this embodiment divides smart contracts into multiple datasets according to the version number of the smart contract source code. This allows the code completion model to learn the syntactic features of different versions of smart contract source code and provide developers with a list of words to complete based on the version they are currently using. When constructing the code representation graph based on the semantic information of the smart contract source code in each dataset, the semantic information in the source code is taken into consideration. The code completion model can better predict the code words used to complete the smart contract by better understanding the semantic information in the source code. When constructing the code representation graph of the smart contract source code, industry security practices are incorporated into the code completion model. Best security practices are added to the code completion model, which can learn code with good programming structure and improve the security of the predicted code word list for smart contracts.
[0174] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working processes of the systems, devices, and units described above can be referred to the corresponding processes in the foregoing method embodiments, and will not be repeated here.
[0175] In the embodiments provided in this application, it should be understood that the disclosed systems, apparatuses, and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be an indirect coupling or communication connection between devices or units through some interfaces, and may be electrical, mechanical, or other forms.
[0176] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0177] Furthermore, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0178] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.
[0179] The above embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A method for smart contract code completion based on a graph neural network, characterized in that, Includes the following steps: Construct multiple smart contract source code datasets based on the version numbers of the smart contract source code; Construct corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices; Construct a code completion model based on a gated graph neural network, and train the code completion model using the code representation graph to obtain the trained code completion model; The code representation graph corresponding to the smart contract to be completed is embedded into the trained code completion model to perform code completion prediction and obtain a list of words to be completed; Multiple smart contract source code datasets were constructed based on the version numbers of the smart contract source code, including: Obtain the source code of smart contracts on Ethereum, use Ethereum security analysis tools to detect the source code of the smart contracts to obtain secure smart contracts, and divide the smart contracts into multiple smart contract source code datasets according to the version number of the smart contract source code; Based on the semantic information of the smart contract source code in each dataset and industry security practices, corresponding code representation diagrams are constructed, including: Parse the source code of each smart contract in each dataset into the corresponding abstract syntax tree; The nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code. Code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph.
2. The graph neural network-based smart contract code completion method of claim 1, wherein, The semantic edge includes at least: Control flow edges and data flow edges, wherein the control flow edges represent control flow information in the smart contract source code, and the data flow edges represent data flow information in the smart contract source code.
3. The graph neural network-based smart contract code completion method of claim 2, wherein, The control flow edge includes at least the following control flow types: The statements include if, while, do while, for, assert, and require.
4. The graph neural network-based smart contract code completion method of claim 1, wherein, From the abstract syntax tree, code snippets conforming to industry security practices are selected, and feature edges are added between nodes in the code snippets in the code representation graph, including: Based on industry security practices related to smart contract execution, code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges indicating compliance with industry security practices are added between nodes contained in the code snippets in the code representation graph.
5. An intelligent contract code completion apparatus based on a graph neural network, characterized in that, include: The dataset building module is used to build multiple smart contract source code datasets based on the version number of the smart contract source code; The code representation graph construction module is used to construct corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices; The code completion model training module is used to construct a code completion model based on a gated graph neural network, and to train the code completion model using the code representation graph to obtain the trained code completion model. The code completion prediction module is used to embed the code representation graph corresponding to the smart contract to be completed into the trained code completion model to perform code completion prediction and obtain a list of words to be completed. The dataset construction module builds multiple smart contract source code datasets based on the version number of the smart contract source code, including: The dataset construction module obtains the source code of smart contracts on Ethereum, uses Ethereum security analysis tools to detect the source code of smart contracts to obtain secure smart contracts, and divides the smart contracts into multiple smart contract source code datasets according to the version number of the smart contract source code. The code representation graph construction module constructs corresponding code representation graphs based on the semantic information of smart contract source code in each dataset and industry security practices, including: The code representation graph construction module parses the source code of each smart contract in each dataset into a corresponding abstract syntax tree; The nodes in the abstract syntax tree are used as nodes in the code representation graph, and various types of semantic edges are added to the code representation graph based on the semantic information of the smart contract source code. Code snippets that conform to industry security practices are selected from the abstract syntax tree, and feature edges are added between nodes in the code snippets in the code representation graph. 6.The graph neural network-based smart contract code completion apparatus of claim 5, wherein, The code representation graph construction module selects code snippets that conform to industry security practices from the abstract syntax tree, and adds feature edges between nodes in the code snippets in the code representation graph, including: The code representation graph construction module selects code snippets that conform to industry security practices from the abstract syntax tree based on industry security practices related to smart contract execution, and adds feature edges representing compliance with industry security practices between nodes contained in the code snippets in the code representation graph.