Method and system for automatic detection and early warning of smart contract security vulnerabilities

By constructing the control flow graph and data flow graph of smart contracts, and combining zero-knowledge proofs and homomorphic encryption technology, the problems of incomplete vulnerability identification and insufficient privacy protection in existing smart contract detection methods are solved, achieving efficient and accurate vulnerability detection and privacy protection.

CN120951341BActive Publication Date: 2025-12-30JIANGSU YAOER LINGJIU TECHNOLOGY SERVICE CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202511486421.4
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-10-17
Publication Date
2025-12-30
Estimated Expiration
2045-10-17

AI Technical Summary

Technical Problem

Existing smart contract security detection methods lack comprehensive coverage of contract execution paths, making it difficult to identify complex logic vulnerabilities and new attack patterns. Furthermore, they lack effective verification mechanisms and privacy protection, leading to inaccurate vulnerability detection results and privacy leaks.

Method used

By constructing the control flow graph and data flow graph of smart contracts, extracting function call chains and state transition paths, using a satisfiability model checker and symbolic execution engine for dual verification analysis, combining zero-knowledge proofs and homomorphic encryption techniques for security analysis, generating vulnerability risk assessment reports and anonymizing them.

Benefits of technology

It enables comprehensive and accurate identification of potential security vulnerabilities in smart contracts, improves the accuracy and coverage of detection, reduces false positives and false negatives, protects contract privacy, and provides a reliable security protection mechanism.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120951341B_ABST
    Figure CN120951341B_ABST
Patent Text Reader

Abstract

The application provides a smart contract security vulnerability automatic detection and protection early warning method and system, relates to the technical field of vulnerability detection, and comprises the following steps: converting a smart contract code into an abstract syntax tree to construct a control flow graph and a data flow graph, extracting a function call chain to construct a running track graph, detecting a vulnerability by using a double verification analysis technology, generating a risk assessment report, and constructing a vulnerability verification network based on zero-knowledge proof. The application can significantly improve the accuracy of smart contract vulnerability detection, realize early warning of security risks of smart contracts, and guarantee the safe and stable operation of a blockchain system.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to vulnerability detection technology, and more particularly to a method and system for automatic detection, protection and early warning of smart contract security vulnerabilities. Background Technology

[0002] With the rapid development of blockchain technology, smart contracts, as its core component, have been widely applied in various fields such as finance, supply chain, and the Internet of Things. A smart contract is an automatically executing computer program; once deployed on a blockchain, its code is immutable, meaning that any security vulnerability can lead to severe economic losses. In recent years, security incidents caused by smart contract vulnerabilities have occurred frequently, such as the DAO attack and the Parity multi-signature wallet vulnerability. These incidents have caused hundreds of millions of dollars in losses and seriously affected the healthy development of the blockchain ecosystem.

[0003] Currently, smart contract security testing mainly relies on static analysis tools and manual auditing, but these methods face many challenges in practical applications. Traditional static analysis tools can typically only detect known types of vulnerabilities, and their ability to identify complex logical vulnerabilities and new attack patterns is limited, resulting in a large number of potential risks going undetected in a timely manner. Meanwhile, while manual auditing is highly accurate, it is inefficient, struggles to cope with the ever-increasing number of smart contracts, and is limited by the experience and knowledge level of auditors, making it prone to missed detections and misjudgments.

[0004] The main shortcomings of existing technologies include: First, existing detection methods lack comprehensive coverage of contract execution paths, making it difficult to discover vulnerabilities that only trigger under specific conditions, especially security issues involving complex state transitions; second, the reliability of detection results is insufficient, lacking an effective verification mechanism, making it difficult to distinguish between real vulnerabilities and false positives, increasing the burden on developers; and finally, existing detection systems generally lack privacy protection mechanisms, exposing sensitive information in contract code during the detection process, hindering enterprises and developers from adopting security detection services. Summary of the Invention

[0005] This invention provides a method and system for automatic detection, protection, and early warning of smart contract security vulnerabilities, which can solve the problems in the prior art.

[0006] A first aspect of this invention provides a method for automatic detection and early warning of smart contract security vulnerabilities, comprising:

[0007] Receive the smart contract code to be tested, convert the smart contract code into an abstract syntax tree, and construct the control flow graph and data flow graph of the smart contract based on the abstract syntax tree;

[0008] Based on the control flow graph and the data flow graph, extract the function call chain, variable access sequence and state transition path in the smart contract code to construct the contract execution trajectory graph;

[0009] The contract execution trajectory graph is subjected to dual verification analysis. The correctness of the contract state transition is verified by the satisfiability model checker to obtain the state transition violation points. The symbolic execution engine is used to conduct in-depth analysis of the state transition violation points. By simulating all the execution paths of the contract and combining the predefined formal security attribute rule set, the specific code fragment bundle that violates the security attribute is located.

[0010] Based on the specific code snippets and their corresponding security attribute rules, a vulnerability risk assessment report for the smart contract is generated.

[0011] Based on the vulnerability risk assessment report, a zero-knowledge proof vulnerability verification network is constructed. Each node in the vulnerability verification network receives vulnerability feature information of smart contracts, performs security analysis on the contracts after anonymizing them using homomorphic encryption technology, generates zero-knowledge proofs, and submits the zero-knowledge proofs to the distributed ledger.

[0012] Based on the vulnerability information in the vulnerability risk assessment report and the verification results recorded in the distributed ledger.

[0013] Converting the smart contract code into an abstract syntax tree, and constructing the control flow graph and data flow graph of the smart contract based on the abstract syntax tree, includes:

[0014] The smart contract source code is lexically analyzed by a lexical parser to generate a lexical token sequence. The lexical token sequence is then input into a syntax analyzer to construct an abstract syntax tree. The abstract syntax tree contains function definition nodes, variable declaration nodes, operation expression nodes, and control statement nodes. A hierarchical index structure of nodes is established in the abstract syntax tree.

[0015] The abstract syntax tree is traversed using a depth-first search algorithm to extract semantic feature vectors of nodes. These semantic feature vectors include opcode features, data type features, and scope features. An attention mechanism is used to calculate the semantic correlation between nodes, and a hierarchical dependency relationship between nodes is constructed based on the semantic correlation.

[0016] A control flow graph is constructed based on the abstract syntax tree and the hierarchical dependency relationship. The nodes of the control flow graph are set as basic code blocks. The execution order and jump relationship between the basic code blocks are analyzed. The execution order and jump relationship are used as directed edges of the control flow graph. A data flow graph is constructed using a data flow analysis method based on the dominance tree.

[0017] The smart contract source code is lexically analyzed by a lexical parser to generate a lexical token sequence. This lexical token sequence is then input into a syntax analyzer to construct an abstract syntax tree, including:

[0018] The source code of the smart contract is input into a lexical analyzer, which uses a finite state automaton for lexical analysis. The finite state automaton includes a lexical analysis state set, a character input set, and a state transition function.

[0019] The source code of the smart contract is scanned based on the finite state automaton to identify identifiers, operators and delimiters in the code and generate lexical token sequence information.

[0020] Features are extracted from the lexical token sequence to construct a token feature vector. The token feature vector includes contextual features, semantic dependency features, and positional embedding features. The association weights between tokens are calculated through a self-attention mechanism. The token feature vectors are then dynamically weighted and fused based on the association weights.

[0021] The token feature vector is input into a parser, which constructs a parser tree based on a predefined set of grammar rules. The parser tree reflects the hierarchical grammar structure of the code.

[0022] The syntax tree is semantically enhanced by using a graph attention network to extract structured features between nodes. The graph attention network transmits feature information between adjacent nodes through a message passing mechanism and adaptively adjusts the feature aggregation weights according to the semantic relevance of the nodes to generate a semantically enhanced abstract syntax tree.

[0023] The correctness of contract state transitions is verified using a satisfiability model checker to identify state transition violations. These violations are then analyzed in depth using a symbolic execution engine, including:

[0024] A state transition model for a smart contract is constructed by extracting the function call sequence and the set of state variables from the smart contract, and generating a state transition relationship based on the function call sequence and the set of state variables. The state transition relationship is then input into a satisfiability model checker, and a set of state variable constraints and a set of state transition path constraints are constructed based on the satisfiability model checker.

[0025] The state variable constraint set and the state transition path constraint set are solved and verified. The state transition path is verified in segments through an incremental verification strategy. The incremental verification strategy dynamically updates the constraints at each verification stage. When a state transition is found to violate a preset safety rule, the violation location is marked as a state transition violation point.

[0026] The state transition violation point is input into the symbolic execution engine, which constructs a fine-grained symbolic variable mapping relationship. The symbolic variable mapping relationship records the value constraints of the state variable on different execution paths. The complete execution path that triggers the violation state is determined through backtracking analysis.

[0027] Based on the analysis results of the symbolic execution engine, trigger paths and trigger conditions are generated, and in-depth analysis is performed on the state transition violation points based on the trigger paths and trigger conditions.

[0028] The state variable constraint set and the state transition path constraint set are solved and verified. The state transition path is verified in segments using an incremental verification strategy, including:

[0029] Based on depth information, the state transition path constraint set is divided into multiple verification segments. Each verification segment corresponds to a local constraint set, which includes the state variable constraints and state transition constraints of the corresponding verification segment.

[0030] Incremental verification is performed on each verification segment to verify whether the constraints of the current verification segment are satisfied. The state information is updated based on the verification results. The incremental verification passes the verification results and the state information to the next verification segment, so that the subsequent verification segments can be analyzed based on the results of the previous verification segments.

[0031] Extract the solution results of the verification segment. When the constraints can be satisfied, output the verification pass information and result data. When the constraints cannot be satisfied, output the conflict information.

[0032] The conflict information is processed using constraint propagation rules. Based on the conflict information, a new value domain for the state variables is determined. The new value domain is then applied to the constraint solving process of the subsequent verification segment to achieve dynamic optimization of the verification process and output the final constraint verification result.

[0033] After anonymizing the contract using homomorphic encryption, a security analysis is performed to generate zero-knowledge proofs, including:

[0034] Extract state variables and function call information from smart contract code, and construct a contract analysis model based on the state variables and function call information;

[0035] Homomorphic encryption is performed on the contract analysis model to convert the state variables into ciphertext while maintaining the operational relationships between the state variables. Based on the homomorphic encryption feature, the smart contract code is anonymized.

[0036] Security analysis is performed on the anonymized smart contract code to extract security vulnerability information; homomorphic encryption is used to encrypt and calculate the security vulnerability information, and the correctness of the analysis results is verified while maintaining the data encryption state; zero-knowledge proof is generated based on the verification results.

[0037] A second aspect of the present invention provides an automatic detection and protection early warning system for smart contract security vulnerabilities, comprising:

[0038] The first unit is used to receive the smart contract code to be tested, convert the smart contract code into an abstract syntax tree, and construct the control flow graph and data flow graph of the smart contract based on the abstract syntax tree;

[0039] The second unit is used to extract the function call chain, variable access sequence and state transition path in the smart contract code based on the control flow graph and the data flow graph, and to construct the contract execution trajectory graph.

[0040] The third unit is used to perform dual verification analysis on the contract execution trajectory diagram. It verifies the correctness of the contract state transition through the satisfiability model checker, obtains the state transition violation points, and uses the symbolic execution engine to conduct in-depth analysis of the state transition violation points. By simulating all the execution paths of the contract and combining the predefined formal security attribute rule set, it locates the specific code fragment bundle that violates the security attributes.

[0041] The fourth unit is used to generate a vulnerability risk assessment report for the smart contract based on the specific code fragment bundle and its corresponding security attribute rules.

[0042] The fifth unit is used to construct a zero-knowledge proof vulnerability verification network based on the vulnerability risk assessment report. Each node in the vulnerability verification network receives vulnerability feature information of smart contracts, performs security analysis on the contracts after anonymizing them using homomorphic encryption technology, generates zero-knowledge proofs, and submits the zero-knowledge proofs to the distributed ledger.

[0043] The sixth unit is used to assess the vulnerability information in the vulnerability risk assessment report and the verification results recorded in the distributed ledger.

[0044] A third aspect of the present invention provides an electronic device, comprising:

[0045] processor;

[0046] Memory used to store processor-executable instructions;

[0047] The processor is configured to invoke instructions stored in the memory to execute the aforementioned method.

[0048] A fourth aspect of the present invention provides a computer-readable storage medium having stored thereon computer program instructions that, when executed by a processor, implement the aforementioned method.

[0049] The beneficial effects of this application are as follows:

[0050] The automatic detection and protection early warning method for smart contract security vulnerabilities provided by this invention can comprehensively and accurately identify potential security vulnerabilities in smart contracts by constructing a contract execution trajectory diagram and performing dual verification analysis, thereby improving the accuracy and coverage of vulnerability detection and effectively reducing false positives and false negatives.

[0051] This method combines state transition verification and symbolic execution analysis techniques, enabling in-depth analysis of the execution logic and state changes of smart contracts, accurately locating code fragments that violate security attributes. It can not only discover common vulnerabilities but also detect complex logical defects and new security threats, providing developers with a comprehensive and detailed vulnerability risk assessment report.

[0052] By introducing zero-knowledge proofs and homomorphic encryption technology to build a distributed vulnerability verification network, the privacy of smart contracts is protected while the vulnerability verification results are made public and transparent. This solves the contradiction between privacy protection and result credibility in traditional vulnerability detection methods and provides a security protection mechanism for the blockchain ecosystem that is both privacy-protecting and trustworthy. Attached Figure Description

[0053] Figure 1 This is a flowchart illustrating the automatic detection and protection early warning method for smart contract security vulnerabilities according to an embodiment of the present invention;

[0054] Figure 2 This is a flowchart illustrating the lexical analysis and abstract syntax tree construction process for smart contracts in this invention.

[0055] Figure 3 This is a flowchart illustrating the verification process for the correctness of smart contract state transitions in an embodiment of the present invention. Detailed Implementation

[0056] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0057] The technical solution of the present invention will be described in detail below with reference to specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments.

[0058] Figure 1 This is a flowchart illustrating the automatic detection and protection early warning method for smart contract security vulnerabilities according to an embodiment of the present invention. Figure 1 As shown, the method includes:

[0059] Receive the smart contract code to be tested, convert the smart contract code into an abstract syntax tree, and construct the control flow graph and data flow graph of the smart contract based on the abstract syntax tree;

[0060] Based on the control flow graph and the data flow graph, extract the function call chain, variable access sequence and state transition path in the smart contract code to construct the contract execution trajectory graph;

[0061] The contract execution trajectory graph is subjected to dual verification analysis. The correctness of the contract state transition is verified by the satisfiability model checker to obtain the state transition violation points. The symbolic execution engine is used to conduct in-depth analysis of the state transition violation points. By simulating all the execution paths of the contract and combining the predefined formal security attribute rule set, the specific code fragment bundle that violates the security attribute is located.

[0062] Based on the specific code snippets and their corresponding security attribute rules, a vulnerability risk assessment report for the smart contract is generated.

[0063] Based on the vulnerability risk assessment report, a zero-knowledge proof vulnerability verification network is constructed. Each node in the vulnerability verification network receives vulnerability feature information of smart contracts, performs security analysis on the contracts after anonymizing them using homomorphic encryption technology, generates zero-knowledge proofs, and submits the zero-knowledge proofs to the distributed ledger.

[0064] Based on the vulnerability information in the vulnerability risk assessment report and the verification results recorded in the distributed ledger.

[0065] In one optional implementation, converting the smart contract code into an abstract syntax tree, and constructing the control flow graph and data flow graph of the smart contract based on the abstract syntax tree includes:

[0066] The smart contract source code is lexically analyzed by a lexical parser to generate a lexical token sequence. The lexical token sequence is then input into a syntax analyzer to construct an abstract syntax tree. The abstract syntax tree contains function definition nodes, variable declaration nodes, operation expression nodes, and control statement nodes. A hierarchical index structure of nodes is established in the abstract syntax tree.

[0067] The abstract syntax tree is traversed using a depth-first search algorithm to extract semantic feature vectors of nodes. These semantic feature vectors include opcode features, data type features, and scope features. An attention mechanism is used to calculate the semantic correlation between nodes, and a hierarchical dependency relationship between nodes is constructed based on the semantic correlation.

[0068] A control flow graph is constructed based on the abstract syntax tree and the hierarchical dependency relationship. The nodes of the control flow graph are set as basic code blocks. The execution order and jump relationship between the basic code blocks are analyzed. The execution order and jump relationship are used as directed edges of the control flow graph. A data flow graph is constructed using a data flow analysis method based on the dominance tree.

[0069] The source code of a smart contract undergoes lexical analysis using a lexical analyzer. The lexical analyzer scans the source code character stream and identifies lexical units such as keywords, identifiers, constants, operators, and delimiters.

[0070] During the generation of the lexical token sequence, the parser maintains the current recognition state and the lexical unit buffer. When encountering delimiters such as spaces, tabs, or newlines, it determines whether the current buffer content constitutes a complete lexical unit. If so, it generates the corresponding type of lexical token and adds it to the lexical token sequence; otherwise, it continues reading the next character. For comment content, the parser recognizes single-line and multi-line comment markers and ignores the text inside the comment. After lexical analysis is completed, a lexical token sequence containing type and position information is formed.

[0071] After the lexical token sequence is input into the parser, the parser constructs an abstract syntax tree based on predefined grammar rules. These grammar rules define the grammatical structure of a programming language, such as function definitions, variable declarations, expressions, and control statements. The parsing employs recursive descent parsing, implementing corresponding parsing functions for different grammatical structures. The parsing process starts at the program entry point and recursively processes various grammatical structures to form a tree-like representation.

[0072] The Abstract Syntax Tree (ABS) contains various types of nodes, including function definition nodes, variable declaration nodes, operation expression nodes, and control statement nodes. Each node contains type information, position information, and references to its child nodes. To improve subsequent analysis efficiency, a hierarchical index structure is established for the nodes in the ABS. This hierarchical index structure is implemented using a hash table, where the key is a combination of node type and position information, and the value is a node reference. This index structure allows for quick location of nodes of a specific type or position, improving tree traversal efficiency.

[0073] The constructed abstract syntax tree is traversed using a depth-first search algorithm to extract semantic feature vectors from the nodes. These semantic feature vectors contain opcode features, data type features, and scope features. Opcode features describe the type of operation performed by the node, such as assignment, addition, subtraction, and multiplication; data type features describe the data type of the operation, such as integers, addresses, and boolean values; and scope features describe the scope of the node, such as global scope, function scope, and block scope.

[0074] In the feature extraction implementation, a feature mapping table is designed to map different types of nodes to their corresponding feature representations. For example, for an assignment expression node, its opcode is extracted as "assignment", its data type is the left-hand variable type, and its scope is the identifier of the current function or block. The feature vector uses fixed-length encoding, with different positions representing different feature dimensions, facilitating subsequent calculations and processing.

[0075] The semantic association between nodes is calculated using an attention mechanism. This mechanism calculates the degree of association between node pairs based on their feature vectors; a higher degree of association indicates a stronger semantic dependency between nodes. Specifically, a query matrix, a key matrix, and a value matrix are defined, and an attention score is calculated by multiplying the feature vectors by these matrices. This attention score, after normalization, is then used as the semantic association between nodes.

[0076] Hierarchical dependencies between nodes are constructed based on semantic relevance. Dependencies are represented as a directed graph structure, where nodes are abstract syntax tree nodes, edges represent dependencies, and edge weights are semantic relevance. Dependencies are categorized into two types: data dependencies and control dependencies. Data dependencies indicate that one node uses variables defined by another node; control dependencies indicate that the execution condition of one node depends on the execution result of another node.

[0077] The control flow graph is constructed based on an abstract syntax tree and hierarchical dependencies. Nodes in the control flow graph are defined as basic code blocks, each of which is a continuous, branchless sequence of code. Basic code blocks are divided using entry and exit point identifiers. Entry points include the start of a function, the first statement after a conditional statement, the start of a loop, etc.; exit points include conditional jumps, unconditional jumps, function returns, etc.

[0078] The execution order and jump relationships between basic code blocks are represented as directed edges in the control flow graph. Execution order edges represent sequential execution relationships, such as sequential execution within a statement block; jump relationship edges represent conditional jumps or unconditional jumps, such as true / false branches of conditional statements, and continuation or exit branches of loops. For each basic code block, the type of its last statement is analyzed to determine the subsequent basic code blocks to be executed, and the corresponding edge relationships are established.

[0079] The data flow graph is constructed using a data flow analysis method based on dominance trees. A dominance relationship is defined as follows: if a node must be traversed from the program entry point to another node, then that node dominates that node. The dominance tree is a tree-like representation of dominance relationships, where each node's parent node is the node that directly dominates it. Based on the dominance tree, the dominance front of each node is calculated. The dominance front refers to the set of nodes that are not dominated by any node but whose predecessor nodes have at least one node that is dominated by that node.

[0080] During data flow analysis, the definition and usage of variables are tracked. For each basic code block, the variables defined and used within the block are recorded. The definition point of a variable is the left-hand side of an assignment statement; the usage point of a variable is the location in an expression that references that variable. Based on the relationship between variable definition and usage, data flow edges are established, pointing from the variable's definition point to its usage point.

[0081] The abstract syntax tree constructed using the above method contains function definition nodes, conditional statement nodes, assignment expression nodes, and return statement nodes. The control flow graph contains four basic code blocks: entry block, conditional statement block, true conditional execution block, and false conditional execution block, as well as the jump relationships between them. The data flow graph reflects the definition and usage relationships of the variables "Balance [Sender]" and "Balance [Receiver]", and the usage of the "Amount" parameter in different statements.

[0082] The aforementioned technologies enable the transformation of smart contract code into structured abstract syntax trees, control flow graphs, and data flow graphs, laying the foundation for subsequent security analysis and vulnerability detection.

[0083] In one optional implementation, the smart contract source code is lexically analyzed by a lexical parser to generate a lexical token sequence, and the lexical token sequence is then input into a syntax analyzer to construct an abstract syntax tree, including:

[0084] The source code of the smart contract is input into a lexical analyzer, which uses a finite state automaton for lexical analysis. The finite state automaton includes a lexical analysis state set, a character input set, and a state transition function.

[0085] The source code of the smart contract is scanned based on the finite state automaton to identify identifiers, operators and delimiters in the code and generate lexical token sequence information.

[0086] Features are extracted from the lexical token sequence to construct a token feature vector. The token feature vector includes contextual features, semantic dependency features, and positional embedding features. The association weights between tokens are calculated through a self-attention mechanism. The token feature vectors are then dynamically weighted and fused based on the association weights.

[0087] The token feature vector is input into a parser, which constructs a parser tree based on a predefined set of grammar rules. The parser tree reflects the hierarchical grammar structure of the code.

[0088] The syntax tree is semantically enhanced by using a graph attention network to extract structured features between nodes. The graph attention network transmits feature information between adjacent nodes through a message passing mechanism and adaptively adjusts the feature aggregation weights according to the semantic relevance of the nodes to generate a semantically enhanced abstract syntax tree.

[0089] like Figure 2 As shown, the method further includes:

[0090] In the smart contract source code input lexical parser stage, the lexical parser uses a finite state automaton for lexical analysis. The finite state automaton consists of a lexical analysis state set, a character input set, and a state transition function. The lexical analysis state set includes multiple states such as the initial state, identifier recognition state, number recognition state, and string recognition state. The character input set includes letters, numbers, underscores, whitespace characters, and special symbols. The state transition function defines the rules for transitioning from one state to another when a specific input character is received.

[0091] Taking function declarations in smart contracts as an example, when the parser reads the keyword "function," the state machine transitions from the initial state to the keyword recognition state; subsequently, when reading the function name, the state machine transitions to the identifier recognition state; and when reading the left parenthesis, it transitions to the parameter list recognition state. In the specific implementation, a state transition table is constructed, where each row represents the current state, each column represents the input character, and the table entry content is the target state. For example, if the current state is the initial state and the input character is a letter, the target state is the identifier recognition state; if the current state is the identifier recognition state and the input character is a letter, number, or underscore, the state remains unchanged.

[0092] During the scanning of smart contract source code, the lexical parser reads the source code character by character, updates the current state according to the state transition function, and maintains a buffer to store the lexical units being processed. When a complete lexical unit is identified, a corresponding lexical token is generated and added to the lexical token sequence. Each lexical token contains type, value, and position information. The position information records the line number and column number of the token in the source code, facilitating subsequent error location.

[0093] In the lexical token sequence feature extraction stage, a token feature vector is constructed, which includes context association features, semantic dependency features, and position embedding features. Context association features capture the relationship between the current token and surrounding tokens, and are extracted through the sliding window technique. For example, when the window size is five, for each token, the information of the two tokens before and after it is considered. Semantic dependency features describe the semantic roles of tokens, such as variable declarations, function calls, expressions, etc. Position embedding features encode the relative positions of tokens in the source code, retaining structural information.

[0094] In the specific implementation of feature extraction, a basic feature vector is defined for each token type (keywords, identifiers, operators, etc.). Then, the association weights between tokens are calculated through the self-attention mechanism. The self-attention mechanism calculates the correlation between different tokens through the interaction of query vectors, key vectors, and value vectors. The association weights reflect the degree of semantic dependency between tokens, and the larger the value, the stronger the dependency. Based on the association weights, the token feature vectors are dynamically weighted and fused to generate a fused feature representation.

[0095] Taking the conditional statement in a smart contract as an example: "If (balance ≥ threshold) { execute transfer();}", the self-attention mechanism can capture the comparison relationship between "balance" and "threshold", as well as the control dependency relationship between the conditional judgment result and the "execute transfer" function call. Through dynamic weighted fusion, the feature association between semantically related tokens is enhanced, making the feature representation more abundant.

[0096] After the token feature vector is input into the parser, the parser constructs a parse tree based on a predefined set of grammar rules. The set of grammar rules is represented by context-free grammar and includes non-terminals, terminals, production rules, and a start symbol. Non-terminals include grammar units such as programs, declarations, statements, expressions, etc.; terminals correspond to lexical tokens; production rules define how non-terminals are composed of other symbols; the start symbol is the program.

[0097] Recursive descent analysis is used for syntax analysis, and corresponding analysis functions are implemented for each non-terminal. During the analysis process, the parser continuously reads lexical tokens and recursively constructs a parse tree according to the currently analyzed non-terminal and production rules. For example, for the analysis of the expression "A + B × C", it is first recognized as an addition expression, with the left operand being "A" and the right operand being "B × C"; further analyzing the right operand, it is recognized as a multiplication expression, and a complete syntax tree is constructed.

[0098] In the semantic enhancement stage of the parse tree, a graph attention network is used to extract structured features between nodes. The graph attention network treats the parse tree as a graph structure, with nodes as syntactic units and edges as syntactic relations. Feature information is exchanged between adjacent nodes through a message-passing mechanism. Each node aggregates information from its neighbors and performs weighted fusion based on attention weights. Attention weights are calculated based on the semantic relevance of nodes; nodes with higher relevance contribute more to feature aggregation.

[0099] After the above processing, the smart contract source code is transformed into an abstract syntax tree with rich semantic information, providing a solid foundation for subsequent contract analysis and security testing. This abstract syntax tree not only preserves the structural information of the source code but also incorporates semantic-level dependencies, enabling more accurate vulnerability detection and security analysis.

[0100] In one optional implementation, the correctness of contract state transitions is verified using a satisfiability model checker to identify state transition violations. A symbolic execution engine is then used to perform in-depth analysis of these violations, including:

[0101] A state transition model for a smart contract is constructed by extracting the function call sequence and the set of state variables from the smart contract, and generating a state transition relationship based on the function call sequence and the set of state variables. The state transition relationship is then input into a satisfiability model checker, and a set of state variable constraints and a set of state transition path constraints are constructed based on the satisfiability model checker.

[0102] The state variable constraint set and the state transition path constraint set are solved and verified. The state transition path is verified in segments through an incremental verification strategy. The incremental verification strategy dynamically updates the constraints at each verification stage. When a state transition is found to violate a preset safety rule, the violation location is marked as a state transition violation point.

[0103] The state transition violation point is input into the symbolic execution engine, which constructs a fine-grained symbolic variable mapping relationship. The symbolic variable mapping relationship records the value constraints of the state variable on different execution paths. The complete execution path that triggers the violation state is determined through backtracking analysis.

[0104] Based on the analysis results of the symbolic execution engine, trigger paths and trigger conditions are generated, and in-depth analysis is performed on the state transition violation points based on the trigger paths and trigger conditions.

[0105] like Figure 3 As shown, the method further includes:

[0106] Extract all function definitions from the contract, including public, internal, and private functions. Taking a token trading contract as an example, the contract includes transfer, withdrawal, and authorization functions. For each function, analyze its input parameters, execution logic, and return value to construct a function call graph. For instance, the transfer function calls an internal transfer function, which in turn modifies the user balance mapping table.

[0107] The extraction of the state variable set was accomplished through static analysis. For the aforementioned token contract, state variables include user balance mapping tables, authorized quota mapping tables, and the total contract supply, among others. For each state variable, its data type, access modifier, and initial value are recorded. For example, the balance table is a mapping from address to value, its access modifier is private, and its initial value is set according to the contract constructor.

[0108] During the state transition relationship generation process, rules for transitioning from one state to another are established. A state is defined as a combination of the values ​​of all state variables in the contract. For example, in a transfer operation, the state transition is represented by the change from (sender's balance is 100, receiver's balance is 50) to (sender's balance is 70, receiver's balance is 80). Each function call corresponds to a set of state transition paths. By analyzing the conditional branches and loop structures in the functions, all execution paths are determined, and a state transition description is generated for each path.

[0109] After the state transition relation is input into the satisfiability model checker, it is transformed into a logical constraint expression. The set of state variable constraints describes the legal range of variable values. For example, a user's balance cannot be negative, and the authorized amount cannot exceed the sender's balance. The set of state transition path constraints describes the transition conditions from the initial state to the target state. For example, the condition for a successful transfer is that the sender's balance is greater than or equal to the transfer amount.

[0110] The constraint-solving verification employs an incremental strategy, decomposing long paths into multiple shorter path segments for verification. Each verification stage dynamically updates the constraints, using the results of the previous stage as input for the next. For example, when verifying a composite operation of transfer-authorization-third-party transfer, the correctness of the transfer operation is verified first, using the resulting state as the initial state for the authorization operation, and so on. When a state transition violation of security rules is detected, such as a decrease in balance without a corresponding transfer record, or a change in authorized limits without an authorized operation, that location is marked as a state transition violation point.

[0111] A token contract contains a batch transfer function called `Batch Transfer(address array, recipient list, numerical amount)`. This function iterates through the recipient array and transfers the same amount to each recipient. When the validator analyzes this function, it constructs the constraint: Sender balance = Number of recipients × Transfer amount. If the number of recipients is too large, causing product overflow, constraint solving will reveal a violation: the sender's balance is insufficient, but the transfer operation completes successfully. This location is marked as a state transition violation point, recording the violating function call (batch transfer), the violating variable operation (integer overflow), and the violating execution path.

[0112] After state transition violations are input into the symbolic execution engine, they undergo more granular analysis. The symbolic execution engine represents program variables as symbolic values ​​rather than concrete values, tracking the range of values ​​for each variable during execution. The symbolic variable mapping records the constraints of state variables on different paths. For example, for a batch transfer function, a symbolic representation of the sender's balance and a symbolic representation of the expression receiver array length × amount are constructed, tracking the relationship between these two expressions during execution.

[0113] The symbolic execution engine uses backtracking analysis to determine the complete path that triggers the violation. Starting from the violation point, it analyzes the execution conditions in reverse to construct path constraints. For integer overflow problems, the path constraints include: the result of calculating the receiver array length × amount is less than the amount (overflow condition) and the sender's balance check passes (bypassing the balance check condition). Solving these constraints yields the specific triggering conditions: for example, the receiver array length is greater than 2. 256 / Value of the amount.

[0114] The generation of trigger paths and trigger conditions is a key output of deep analysis. A trigger path describes the complete call sequence from the contract entry point to the violation point, including function call parameters and return values. Trigger conditions describe the specific input values ​​or state conditions required to activate the vulnerability. For example, for the integer overflow vulnerability mentioned above, the trigger condition is: when the receiver array length is X (a specific value, such as 2...). 255 When the amount of a single transfer is Y (e.g., 2), the product calculation will overflow, causing the balance check to fail.

[0115] The in-depth analysis phase also considers the combinatorial exploitability of different vulnerabilities. For example, it analyzes whether a state transition violation can be combined with other vulnerabilities (such as reentrancy attacks) to create a more serious security threat. In the specific implementation, a vulnerability association graph is established, where nodes represent various violations and edges represent exploitation relationships. Potential attack chains are identified through graph traversal algorithms.

[0116] In a decentralized exchange contract, state transition analysis revealed a reentrancy risk in the withdrawal function, which was marked as a violation. Symbolic execution engine analysis showed that the function did not lock the user's balance before the transfer operation. Backtracking analysis generated a trigger path: the user calls the withdrawal function, the contract executes an external transfer, and the withdrawal function is called again before the transfer is completed. The trigger condition is: the attacking contract recursively calls the original contract's withdrawal function in its token receiving function. In-depth analysis further revealed that this vulnerability can be combined with a price manipulation vulnerability to form an attack chain of "flash loan attack - reentrant withdrawal - price manipulation".

[0117] The above methods enable comprehensive verification of smart contract state transitions and in-depth analysis of violations, providing contract developers with accurate vulnerability location and remediation suggestions.

[0118] In one optional implementation, the state variable constraint set and the state transition path constraint set are solved and verified. The state transition path is verified in segments using an incremental verification strategy, including:

[0119] Based on depth information, the state transition path constraint set is divided into multiple verification segments. Each verification segment corresponds to a local constraint set, which includes the state variable constraints and state transition constraints of the corresponding verification segment.

[0120] Incremental verification is performed on each verification segment to verify whether the constraints of the current verification segment are satisfied. The state information is updated based on the verification results. The incremental verification passes the verification results and the state information to the next verification segment, so that the subsequent verification segments can be analyzed based on the results of the previous verification segments.

[0121] Extract the solution results of the verification segment. When the constraints can be satisfied, output the verification pass information and result data. When the constraints cannot be satisfied, output the conflict information.

[0122] The conflict information is processed using constraint propagation rules. Based on the conflict information, a new value domain for the state variables is determined. The new value domain is then applied to the constraint solving process of the subsequent verification segment to achieve dynamic optimization of the verification process and output the final constraint verification result.

[0123] When solving and verifying the set of state variable constraints and the set of state transition path constraints, an incremental verification strategy is adopted to perform segmented verification of the state transition path. Based on depth information, the set of state transition path constraints is divided into multiple verification segments, each corresponding to a local constraint set. This local constraint set contains the state variable constraints and state transition constraints of the corresponding verification segment. In this embodiment, depth information refers to the number of transition steps from the initial state to the current state in the state transition path. For example, in a state transition path with 10 state nodes, it can be divided into 3 verification segments based on depth information: depth 0-3 is the first verification segment, depth 4-6 is the second verification segment, and depth 7-9 is the third verification segment.

[0124] When dividing the verification segments, the system analyzes the complexity and constraint characteristics of the state transition path. For an intelligent device control system, its state variables include temperature T, humidity H, and pressure P, with values ​​ranging from T∈[0,100], H∈[0,100], and P∈[0,50], respectively. The state transition path can be represented as the process of reaching the target state S5 (T=75, H=60, P=30) from the initial state S0 (T=25, H=40, P=10) after multiple operations. The system divides the entire path into several verification segments based on the depth information of these state nodes.

[0125] Incremental verification is performed on each verification segment to verify the constraint satisfaction of the current verification segment and update the state information based on the verification results. Incremental verification passes the verification results and state information to the next verification segment, enabling subsequent verification segments to analyze based on the results of previous verification segments. In actual execution, the system first verifies the constraint set of the first verification segment (e.g., depth 0-3). Assume the first verification segment contains the constraints "T must increase by 5-10 degrees in each step" and "H must remain within the range of 30-50". The system checks whether these constraints are satisfied through the constraint solver and identifies the variable values ​​that satisfy the constraints.

[0126] After validating the first segment, the system uses the obtained state information (e.g., T=55, H=45, P=15) as the input state for the second validation segment. The second validation segment contains the constraints "P must increase by 5-8 units at each step" and "The sum of T and H must not exceed 130". Based on the results of the first segment, the system continues to validate the constraints of the second segment, avoiding repeated validation of the entire path and improving validation efficiency.

[0127] The system extracts the solution results from the verification segment. When constraints are satisfied, it outputs verification pass information and result data; when constraints are not satisfied, it outputs conflict information. For example, when verifying the third verification segment, if the constraint "P cannot exceed 25" conflicts with the previously passed state value P=28, the system will output conflict information, indicating the conflicting constraint and state variable. Specifically, the system will generate a conflict report, including the conflicting variable P, its current value 28, the conflicting constraint "P≤25", and the depth information of the conflict (e.g., depth 8).

[0128] The system utilizes constraint propagation rules to handle conflict information, determines a new domain for state variables based on this information, and applies this new domain to the constraint solving process in subsequent verification segments. This achieves dynamic optimization of the verification process and outputs the final constraint verification results. When handling conflicts, the system analyzes the root cause and dynamically adjusts the domain of constraints or state variables. Continuing the example above, when a conflict in the P value is detected, the system performs the following actions: it backtracks to the second verification segment, adjusts the P growth constraint from "increase by 5-8 units per step" to "increase by 3-5 units per step," and then re-verifies the second and third verification segments.

[0129] During constraint propagation, the system employs domain reduction techniques to improve solution efficiency. For example, if the constraint "T+H≤130" is found to be difficult to satisfy under certain conditions, the system analyzes known values ​​of T and H. For instance, if T=70, it dynamically reduces the range of H from [0,100] to [0,60], avoiding the exploration of unnecessary solution spaces. Furthermore, the system utilizes learned conflict clauses to avoid repeatedly encountering the same conflict patterns. For example, once it learns that "the constraint T+H≤130 cannot be satisfied when T>65 and H>50," it will directly avoid this combination of variables in subsequent verifications.

[0130] Through this incremental verification and dynamic optimization approach, the system can efficiently handle complex state transition path verification problems. In a large system with 100 state nodes and 20 state variables, traditional holistic verification methods would take several hours to complete, while this method reduces the verification time to just a few minutes. Furthermore, the system can provide more precise conflict localization and resolution suggestions, such as "relaxing the temperature control constraint at depth 5-7 by 2 degrees can resolve the constraint conflict," helping developers quickly identify and resolve problems.

[0131] Once verification is complete, the system generates a detailed verification report, including the constraint satisfaction status of each verification segment, the evolution trajectory of state variables, and any conflicts discovered and their solutions. This information can be used for system optimization and problem diagnosis, improving the reliability and robustness of the entire state transition system.

[0132] In one optional implementation, after anonymizing the contract using homomorphic encryption, a security analysis is performed to generate a zero-knowledge proof, including:

[0133] Extract state variables and function call information from smart contract code, and construct a contract analysis model based on the state variables and function call information;

[0134] Homomorphic encryption is performed on the contract analysis model to convert the state variables into ciphertext while maintaining the operational relationships between the state variables. Based on the homomorphic encryption feature, the smart contract code is anonymized.

[0135] Security analysis is performed on the anonymized smart contract code to extract security vulnerability information; homomorphic encryption is used to encrypt and calculate the security vulnerability information, and the correctness of the analysis results is verified while maintaining the data encryption state; zero-knowledge proof is generated based on the verification results.

[0136] Extracting state variables and function call information from smart contract code. Taking a funds management smart contract as an example, this contract contains an account balance mapping table (user addresses mapped to balances), a transfer function, and a withdrawal function. The system uses an abstract syntax tree parser to parse the contract code, identifying the state variable "balance table" and its data type, while extracting the call dependencies between the "transfer" and "withdrawal" functions. For example, the "withdrawal" function depends on read and modify operations on the "balance table" state variable. In this way, a contract analysis model containing nodes and edges is formed, where nodes represent state variables and functions, and edges represent the call and access relationships between them.

[0137] For the constructed contract analysis model, homomorphic encryption is implemented. A partially homomorphic encryption scheme is used, which supports addition or multiplication operations in the encrypted state. Specifically, a key pair (public key, private key) is generated for each state variable. Taking the "balance sheet" mapping as an example, the balance value corresponding to each account address is encrypted to obtain the ciphertext form of that value. When an addition operation is needed, such as increasing the account balance, the homomorphic encryption property can be utilized to directly perform ciphertext addition on the ciphertext, resulting in a new ciphertext result. This result is equivalent to adding the original value and the increased value and then encrypting it again.

[0138] Function calls in encrypted state are processed using a secure multi-party computation protocol. For example, when executing the "transfer" function to transfer money from address A to address B, in encrypted state, the following is performed: A's encrypted balance is reduced by the encrypted transfer amount, and B's encrypted balance is increased by the encrypted transfer amount. This operation does not require decrypting the original value, thus ensuring data privacy.

[0139] For security analysis of anonymized smart contract code, the system implements multiple vulnerability detection algorithms. For reentrancy vulnerability detection, the system analyzes the function call sequence and the order of state variable modifications. Taking the "withdrawal" function as an example, it checks whether the balance status is updated before the transfer operation. If the balance is updated only after the transfer operation, it is marked as a potential reentrancy vulnerability. In encrypted form, this detection can be achieved by analyzing the function execution order without knowing the specific balance value.

[0140] Integer overflow vulnerability detection is based on symbolic execution in encrypted state. For example, for the statement "user balance plus transfer amount", the system constructs a symbolic constraint "the encrypted balance after adding the amount is greater than the balance before encryption", and verifies whether this constraint always holds true through homomorphic encryption. If there is a case where this constraint is not satisfied, it is marked as an integer overflow vulnerability.

[0141] The encrypted computation of security vulnerability information and the generation of zero-knowledge proofs employ a zero-knowledge proof protocol. Taking a reentrancy attack vulnerability as an example, the system constructs a proof that the prover knows there exists an execution path in the contract such that the state variable is not updated before the transfer operation is completed, and that this path can be called repeatedly. This proof is encoded as a series of cryptographic commitments and responses, forming a zero-knowledge proof. In the specific implementation, a concise, non-interactive zero-knowledge proof technique is used to compile the vulnerability detection logic into an arithmetic circuit, and then generate the proof. For example, for a reentrancy vulnerability in the "withdrawal" function, a circuit is constructed to represent the condition "the state variable is not updated before the execution of the external call".

[0142] The proof generation process does not reveal sensitive information of the original contract; it only proves the existence of the vulnerability. For example, for an integer overflow vulnerability, a zero-knowledge proof only indicates that "there is an input that causes the operation to overflow," without revealing the specific overflow value or triggering condition.

[0143] The generated zero-knowledge proof is verified by a verification function that includes a verification key and public inputs (such as the hash of the contract address). The verification result is a boolean value indicating whether the proof is valid. For example, in the event of a detected reentrancy vulnerability, the generated proof can be verified by a verifier (such as another node) without the verifier needing to know the detailed implementation of the original contract.

[0144] A smart contract contains a withdrawal function "Withdraw (Amount)". This function first checks if the user's balance is sufficient, then executes the transfer operation, and finally updates the user's balance. The system extracts the state variable "User Balance Table" and the function "Withdraw" to construct a contract analysis model. The "User Balance" value is homomorphically encrypted to obtain the encrypted balance value. Security analysis reveals a reentrancy vulnerability in this function (the transfer operation is executed before the state update). The system generates a zero-knowledge proof proving that "there exists an execution path that causes an external call to be executed before the state variable is updated". This proof is submitted to the distributed ledger, and other nodes can verify its validity without knowing the specific balance value or complete code of the original contract.

[0145] To further enhance security, the system employs a distributed computing architecture during processing. Once the contract code is submitted, the system distributes encryption and security analysis tasks to multiple computing nodes. Each node processes only a subset of state variables or functions, thereby reducing the risk of information leakage. For example, one node handles the encryption of the balance state variable, another analyzes the execution path of the transfer function, and a third node integrates the analysis results and generates zero-knowledge proofs. Intermediate results are exchanged between nodes via a secure multi-party computation protocol, ensuring that raw data is not leaked during collaborative analysis.

[0146] By employing the above technologies, it is possible to effectively detect security vulnerabilities and generate verifiable zero-knowledge proofs while protecting the privacy of smart contracts, thus providing a new technical approach for the security auditing of smart contracts.

[0147] A second aspect of the present invention provides an automatic detection and protection early warning system for smart contract security vulnerabilities, comprising:

[0148] The first unit is used to receive the smart contract code to be tested, convert the smart contract code into an abstract syntax tree, and construct the control flow graph and data flow graph of the smart contract based on the abstract syntax tree;

[0149] The second unit is used to extract the function call chain, variable access sequence and state transition path in the smart contract code based on the control flow graph and the data flow graph, and to construct the contract execution trajectory graph.

[0150] The third unit is used to perform dual verification analysis on the contract execution trajectory diagram. It verifies the correctness of the contract state transition through the satisfiability model checker, obtains the state transition violation points, and uses the symbolic execution engine to conduct in-depth analysis of the state transition violation points. By simulating all the execution paths of the contract and combining the predefined formal security attribute rule set, it locates the specific code fragment bundle that violates the security attributes.

[0151] The fourth unit is used to generate a vulnerability risk assessment report for the smart contract based on the specific code fragment bundle and its corresponding security attribute rules.

[0152] The fifth unit is used to construct a zero-knowledge proof vulnerability verification network based on the vulnerability risk assessment report. Each node in the vulnerability verification network receives vulnerability feature information of smart contracts, performs security analysis on the contracts after anonymizing them using homomorphic encryption technology, generates zero-knowledge proofs, and submits the zero-knowledge proofs to the distributed ledger.

[0153] The sixth unit is used to assess the vulnerability information in the vulnerability risk assessment report and the verification results recorded in the distributed ledger.

[0154] A third aspect of the present invention provides an electronic device, comprising:

[0155] processor;

[0156] Memory used to store processor-executable instructions;

[0157] The processor is configured to invoke instructions stored in the memory to execute the aforementioned method.

[0158] A fourth aspect of the present invention provides a computer-readable storage medium having stored thereon computer program instructions that, when executed by a processor, implement the aforementioned method.

[0159] This invention can be a method, apparatus, system, and / or computer program product. The computer program product may include a computer-readable storage medium having computer-readable program instructions loaded thereon for performing various aspects of the invention.

[0160] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; 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 or all of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of the present invention.

Claims

1. A method for automatically detecting and preventing security vulnerabilities of smart contracts, characterized in that, The method comprises the following steps: receiving a smart contract code to be detected, converting the smart contract code into an abstract syntax tree, and constructing a control flow graph and a data flow graph of the smart contract based on the abstract syntax tree; based on the control flow graph and the data flow graph, extracting a function call chain, a variable access sequence and a state transition path in the smart contract code, and constructing a contract running trajectory graph; performing double verification analysis on the contract running trajectory graph, verifying the correctness of the contract state transition through a satisfiability model checker, obtaining a state transition violation point, and performing in-depth analysis on the state transition violation point by using a symbolic execution engine, simulating all execution paths of the contract, combining a pre-defined formal security attribute rule set, and locating a specific code fragment bundle that violates the security attribute; generating a vulnerability risk assessment report of the smart contract according to the specific code fragment bundle and the corresponding security attribute rule; constructing a zero-knowledge proof vulnerability verification network based on the vulnerability risk assessment report, each node in the vulnerability verification network receives vulnerability feature information of the smart contract, performs security analysis on the contract after anonymization processing through homomorphic encryption technology, generates a zero-knowledge proof, and submits the zero-knowledge proof to a distributed ledger; outputting the vulnerability information in the vulnerability risk assessment report and the verification result recorded in the distributed ledger.

2. The method of claim 1, wherein, The method for converting the smart contract code into an abstract syntax tree and constructing a control flow graph and a data flow graph of the smart contract based on the abstract syntax tree comprises the following steps: performing lexical analysis on the smart contract code by using a lexical analyzer to generate a lexical token sequence, inputting the lexical token sequence into a syntax analyzer to construct an abstract syntax tree, the abstract syntax tree comprises function definition nodes, variable declaration nodes, operation expression nodes and control statement nodes, and a hierarchical index structure of nodes is established in the abstract syntax tree; traversing the abstract syntax tree based on a depth-first search algorithm to extract a semantic feature vector of the nodes, the semantic feature vector comprises opcode features, data type features and scope features, calculating the semantic correlation between nodes by using an attention mechanism, and constructing a hierarchical dependency relationship of the nodes according to the semantic correlation; constructing a control flow graph based on the abstract syntax tree and the hierarchical dependency relationship, setting nodes of the control flow graph as basic code blocks, analyzing the execution order and the jump relationship between the basic code blocks, taking the execution order and the jump relationship as directed edges of the control flow graph, and constructing a data flow graph by using a data flow analysis method based on a dominance tree.

3. The method of claim 2, wherein, The method for performing lexical analysis on the smart contract code by using a lexical analyzer to generate a lexical token sequence, and inputting the lexical token sequence into a syntax analyzer to construct an abstract syntax tree comprises the following steps: inputting the smart contract code into a lexical analyzer, the lexical analyzer performs lexical analysis by using a finite state automaton, the finite state automaton comprises a lexical analysis state set, a character input set and a state transition function; scanning the smart contract code based on the finite state automaton, identifying identifiers, operators and delimiters in the code, and generating a lexical token sequence; The token sequence is subjected to feature extraction, and a token feature vector is constructed, which includes context-related features, semantic dependency features and position embedding features, the correlation weight between tokens is calculated through a self-attention mechanism, and the token feature vector is dynamically weighted and fused based on the correlation weight; The token feature vector is input into a syntax analyzer, the syntax analyzer constructs a syntax analysis tree based on a predefined syntax rule set, and the syntax analysis tree reflects the syntax structure hierarchy of the code; The syntax analysis tree is subjected to semantic enhancement, a graph attention network is used to extract structured features between nodes, the graph attention network transmits feature information between adjacent nodes through a message passing mechanism, adaptively adjusts the feature aggregation weight according to the semantic correlation of the nodes, and generates a semantic-enhanced abstract syntax tree.

4. The method of claim 1, wherein, The correctness of the contract state transition is verified by a satisfiability model checker, and state transition violation points are obtained, and the state transition violation points are analyzed in depth by a symbolic execution engine, including: A state transition model of the smart contract is constructed, a function call sequence and a state variable set in the smart contract are extracted, a state transition relationship is generated based on the function call sequence and the state variable set, the state transition relationship is input into a satisfiability model checker, and a state variable constraint set and a state transition path constraint set are constructed according to the satisfiability model checker; The state variable constraint set and the state transition path constraint set are solved and verified, the state transition path is verified in segments through an incremental verification strategy, the incremental verification strategy dynamically updates the constraint condition at each verification stage, and when it is found that the state transition violates the preset safety rules, the violation position is marked as a state transition violation point; The state transition violation point is input into the symbolic execution engine, the symbolic execution engine constructs a fine-grained symbolic variable mapping relationship, the symbolic variable mapping relationship records the value constraint of the state variable on different execution paths, and the complete execution path triggering the violation state is determined through backtracking analysis; Based on the analysis result of the symbolic execution engine, a triggering path and a triggering condition are generated, and the state transition violation point is analyzed in depth based on the triggering path and the triggering condition.

5. The method of claim 4, wherein, The state variable constraint set and the state transition path constraint set are solved and verified, and the state transition path is verified in segments through an incremental verification strategy, including: The state transition path constraint set is divided into multiple verification segments based on depth information, each verification segment corresponds to a local constraint set, and the local constraint set includes state variable constraints and state transition constraints of the corresponding verification segment; Incremental verification is performed on each verification segment to verify the constraint satisfaction of the current verification segment, state information is updated based on the verification result, the incremental verification transmits the verification result and the state information to the next verification segment, so that the subsequent verification segment can analyze based on the result of the previous verification segment; The solving result of the verification segment is extracted, and when the constraint is satisfiable, verification pass information and result data are output, and when the constraint is not satisfiable, conflict information is output. The conflict information is processed by using a constraint propagation rule, a new value range of a state variable is determined based on the conflict information, the new value range is applied to a constraint solving process of a subsequent verification section, dynamic optimization of the verification process is realized, and a final constraint verification result is output.

6. The method of claim 1, wherein, The contract is anonymized by homomorphic encryption technology, and then security analysis is performed to generate zero-knowledge proof, including: State variables and function call information in the smart contract code are extracted, and a contract analysis model is constructed based on the state variables and the function call information; Homomorphic encryption processing is performed on the contract analysis model, the state variables are converted into ciphertext form while maintaining the operation relationship between the state variables, and anonymization processing of the smart contract code is realized based on the homomorphic encryption characteristics; Security vulnerability information is extracted by performing security analysis on the anonymized smart contract code; the security vulnerability information is encrypted and calculated by using homomorphic encryption operation, the correctness of the analysis result is verified while maintaining the data encryption state, and zero-knowledge proof is generated based on the verification result.

7. The system for automatic detection and early warning of security vulnerabilities in smart contracts, for implementing the method according to any of the preceding claims 1-6, characterized in that, It includes: A first unit is configured to receive a smart contract code to be detected, convert the smart contract code into an abstract syntax tree, and construct a control flow graph and a data flow graph of the smart contract based on the abstract syntax tree; A second unit is configured to extract a function call chain, a variable access sequence, and a state transition path in the smart contract code based on the control flow graph and the data flow graph, and construct a contract running track graph; A third unit is configured to perform double verification analysis on the contract running track graph, perform correctness verification on contract state transition by using a satisfiability model checker, obtain state transition violation points, perform in-depth analysis on the state transition violation points by using a symbolic execution engine, simulate all execution paths of the contract, combine a pre-defined formal security attribute rule set, and locate specific code segment bundles that violate security attributes; A fourth unit is configured to generate a vulnerability risk assessment report of the smart contract according to the specific code segment bundles and corresponding security attribute rules; A fifth unit is configured to construct a vulnerability verification network of zero-knowledge proof based on the vulnerability risk assessment report, each node in the vulnerability verification network receives vulnerability feature information of the smart contract, performs security analysis on the contract after anonymization by using homomorphic encryption technology, generates zero-knowledge proof, and submits the zero-knowledge proof to a distributed ledger; A sixth unit is configured to output vulnerability information in the vulnerability risk assessment report and verification results recorded in the distributed ledger.

8. An electronic device, comprising: It includes: A processor; A memory for storing processor-executable instructions; The processor is configured to call the instructions stored in the memory to execute the method of any one of claims 1 to 6.

9. A computer-readable storage medium having stored thereon computer program instructions, wherein, The computer program instructions are executed by the processor to realize the method of any one of claims 1 to 6.

Citation Information

Patent Citations

  • Smart contract re-entry vulnerability detection method, system and device and storage medium

    CN117614681A

  • Intelligent contract upgrading vulnerability detection method

    CN117951711A