Enhanced intelligent contract vulnerability detection method based on unified contract graph
By using a unified contract graph approach, AST pruning, multi-dimensional semantic integration, and graph encoding comparison learning, the problems of semantic fragmentation and noise interference in smart contract vulnerability detection are solved, achieving high-precision and efficient vulnerability detection applicable to smart contracts of different versions and scenarios.
Patent Information
- Application Number
- CN202511597042.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-04
- Publication Date
- 2026-01-20
AI Technical Summary
Existing smart contract vulnerability detection technologies suffer from semantic fragmentation, noise interference, and difficulty in balancing accuracy and efficiency. In particular, they suffer from high false alarm rates and long detection times when detecting vulnerabilities in complex logic, making them unable to meet the needs of large-scale contract auditing.
An enhanced smart contract vulnerability detection method based on a unified contract graph is adopted. The unified unpacking and pruning module prunes the AST, the unified graph semantic fusion module integrates multi-dimensional semantic relationships, and the vulnerability semantic alignment is achieved through graph encoding and contrastive learning modules, including a hierarchical pruning strategy, a Siamese pairwise graph encoder, and temperature-scale cosine contrastive learning.
It significantly improves detection accuracy and efficiency, increases F1 score, reduces false alarm rate, enhances model robustness and generalization ability, adapts to smart contracts of different versions and scenarios, and meets the real-time requirements of large-scale contract auditing.
Smart Images

Figure CN121365403A_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The present application relates to the field of blockchain security technology, in particular to the field of smart contract vulnerability detection technology, and more particularly to an enhanced smart contract vulnerability detection method based on a unified contract graph, which is suitable for Ethereum, Polygon and other blockchain platforms developed based on the Solidity language. BACKGROUND
[0002] A smart contract is a piece of code that implements the core logic of a decentralized application (DApp) in a blockchain system, has the characteristic of "code is law", and can automatically execute asset transfer, right confirmation, condition triggering and other operations. It has been widely used in decentralized finance (DeFi), non-fungible token (NFT) trading, supply chain traceability and other fields, and manages hundreds of billions of dollars of digital assets worldwide. However, the non-tamperable nature of smart contracts also makes it difficult to fix vulnerabilities once they are deployed, and many major security incidents in history have been caused by contract vulnerabilities.
[0003] Existing smart contract vulnerability detection techniques can be divided into four categories, each with obvious limitations:
[0004] 1. Static analysis technology: representative tools are SmartCheck and Slither, which detect vulnerabilities by matching code patterns (such as "call.value () statement without ReentrancyGuard modifier") using pre-set rules. This type of technology does not need to execute the contract, and the detection speed is fast, but it relies on manual rule writing, has insufficient coverage for complex logic vulnerabilities (such as hidden re-entry paths), has a false positive rate of up to 30-50%, and is difficult to adapt to syntax changes caused by Solidity language version updates (such as built-in overflow checks introduced in version 0.8.0).
[0005] 2. Dynamic analysis and symbolic execution technology: representative tools are Oyente and Mythril, which detect vulnerabilities by simulating contract execution paths and traversing possible input value combinations to detect vulnerability trigger conditions. This type of technology can find some logic vulnerabilities, but has the problem of "path explosion" — when the contract contains multiple layers of loops or complex conditional judgments, the number of execution paths grows exponentially, and the detection time can take hours or even days, which cannot meet the needs of large-scale contract auditing (such as hundreds of thousands of contracts on blockchain browsers).
[0006] 3. Formal verification techniques: Representative tools are Securify, CertiK, which convert contract code into mathematical models (such as finite state machines) to prove whether the code meets security properties (such as "balance after transfer is not less than zero") through logical reasoning. Such techniques have high detection accuracy and low false positive rate, but the modeling process is complex and requires professional mathematical knowledge, and is sensitive to contract size - when the number of contract code lines exceeds 1000, the verification time increases significantly, and the scalability is poor.
[0007] 4. Deep learning techniques: In recent years, researchers have attempted to apply deep learning to contract vulnerability detection, which can be divided into sequence-based methods and graph-based methods. Sequence-based methods (such as converting code into Token sequence input CNN / LSTM) cannot capture structured information (such as cross-function variable dependencies) of code; graph-based methods (such as DR-GCN, MANDO) introduce graph neural networks (GNNs) to model AST, control flow graphs, and other structures, but there are three major problems:
[0008] Semantic fragmentation: Using only a single graph structure (such as AST or CFG) cannot integrate multi-dimensional semantics (such as the association between data flow and state evolution);
[0009] Noise node interference: AST contains a large number of non-semantic nodes (such as parenthesis nodes, expression wrapping nodes), increasing the model's learning burden and reducing detection accuracy;
[0010] Insufficient semantic alignment: Different contract graph structures differ greatly (such as different function definition orders), making it difficult for the model to learn a unified vulnerability semantic representation and reducing generalization ability. SUMMARY
[0011] The present application aims to overcome the defects of existing smart contract vulnerability detection techniques, such as semantic fragmentation, noise interference, and the difficulty of balancing precision and efficiency, and provides an enhanced smart contract vulnerability detection method based on a unified contract graph. The present application proposes a unified framework integrating "structure simplification - multi-semantics fusion - cross-graph contrast learning", which optimizes the graph construction and representation learning process to achieve high-precision and high-efficiency detection of smart contract vulnerabilities.
[0012] The technical solution adopted by the present application to achieve the above-mentioned purpose is:
[0013] An enhanced smart contract vulnerability detection method based on a unified contract graph, comprising the following steps:
[0014] The unified hull trimming module adopts a hierarchical pruning strategy to perform pruning operations on the abstract syntax tree (AST) of the smart contract under global safety constraints, generating a contract graph structure;
[0015] The unified graph semantic fusion module integrates four semantic relationships of syntax structure, control flow, data flow and state slot chain based on the pruned AST to generate a contract graph;
[0016] The graph encoding and alignment module encodes the contract graph through a Siamese pair graph encoder, processes the encoded contract graph by combining a temperature scale cosine contrast learning method, and realizes the alignment of vulnerability semantics in a shared latent space.
[0017] The hierarchical pruning strategy includes three stages, which are:
[0018] The field-level pruning stage deletes redundant container fields according to the set rules and only retains core fields;
[0019] The node-level pruning stage deletes non-semantic nodes according to the set rules and directly mounts the core semantic nodes contained in the non-semantic nodes to the parent nodes;
[0020] The structure-level pruning stage aligns and rearranges the depths of the statement blocks according to the set rules so that nodes with the same semantics are at similar levels.
[0021] The rules set in the field-level pruning stage are:
[0022] Rule F1: When the parent node type is ParameterList, delete the redundant fields typeDescriptions, src and documentation, and retain the core fields parameters (variable declaration array) and id;
[0023] Rule F2: When the parent node type is VariableDeclarationStatement, delete the redundant fields src and documentation, and retain the core fields declarations (variable declaration array) and scope;
[0024] Rule F3: When the parent node type is ForStatement, delete the redundant fields src and documentation, and retain the core fields initialization (initialization statement), condition (condition expression) and update (update statement);
[0025] Rule F4: When the parent node type is FunctionCall, delete the redundant fields src and documentation, and retain the core fields arguments (argument array) and expression (function expression).
[0026] The rules set in the node-level pruning stage are:
[0027] Rule S1: When the node to be deleted is of type ExpressionStatement, and the core child node is of type UnaryOperation, Assignment, FunctionCall or UpdateExpression, delete the ExpressionStatement node, and the core child node directly becomes a child node of the parent node.
[0028] Rule S2: When the node to be deleted is of type VariableDeclarationStatement, and the core child node is of type VariableDeclaratio, delete the VariableDeclarationStatement node, and the VariableDeclaration node directly becomes a child node of the parent node.
[0029] Rule S3: When the node to be deleted is of type Block, and the core child node is of type ExpressionStatement, IfStatement, ForStatement, if the Block node contains only a single ExpressionStatement child node, delete the Block node, and the core child node of the ExpressionStatement is hung under the parent node of the Block; if the Block node contains multiple child nodes, the Block node is retained.
[0030] The rules set in the structure-level pruning stage are:
[0031] Rule N1: When the target node is of type Block, if the parent node of the Block node is of type FunctionDefinition (function definition), and the number of child nodes contained in the Block is ≤ 5, delete the Block node, and the child nodes directly become child nodes of the FunctionDefinition; if the number of child nodes is > 5, the Block node is retained.
[0032] Rule N2: When the target node is of type IfStatement, if the “trueBody” or “falseBody” of the IfStatement is a single Statement node and is not a Block, wrap it into a Block node; if it is a Block node, it remains unchanged.
[0033] Rule N3: When the target node type is ForStatement, wrap the "initialization", "condition" and "update" statements of the ForStatement into Block nodes.
[0034] The global safety constraints are:
[0035] Constraint M1: Perform the flattening operation on the AST only when the child node has a grandchild node.
[0036] Constraint M2: Perform the flattening operation on ForStatement.initialization and FunctionCall.arguments only when the source node src field matches with no spaces.
[0037] Constraint M3: Keep the state variable related nodes and the non-flattened state of the function call expression node call.expr.
[0038] The unified graph semantic fusion module performs the following steps:
[0039] Syntax structure relationship: preserve the connection relationship of the core syntax nodes of the pruned AST;
[0040] Control flow relationship: capture the execution order between statements;
[0041] Data flow relationship: model the dependency relationship of variables and track the definition, reading and modification process of variables;
[0042] State slot chain relationship: link multiple read or write operations of the same state variable in the source code order into a causal chain for revealing the evolution process of the state variable.
[0043] The contract graph is encoded by the Siamese pair graph encoder, including the following steps:
[0044] (1) Map the node and edge features of the contract graph into continuous vectors:
[0045] Let the contract graph be G = (V, E) , where V is the node set, E is the edge set, and each node ∈ V is associated with features , and each edge (i,j) ∈ E is associated with features or discrete edge types , and the mapping process is:
[0046] ;
[0047] ;
[0048] wherein, MLP node and MLP edge are multi-layer perceptrons for nodes and edges respectively, Embed edge is an embedding layer for edge types, is the initial embedding vector of node i, reflecting the representation of the original features of the node after mapping, is the embedding vector of edge (i, j), reflecting the relationship features between node i and node j;
[0049] (2) Perform T rounds of message passing through the gated graph neural network:
[0050] ;
[0051] ;
[0052] wherein, (·) is a linear transformation combined with a ReLU activation function, N( i ) is the neighbor set of node i , GRU is a gated recurrent unit, is the message vector transmitted from neighbor node j to target node i in the t-th round of message passing, reflecting the local semantic interaction between the two nodes, is the comprehensive message representation vector obtained by aggregating all neighbor nodes' incoming messages in the t-th round, used to update the node's own state;
[0053] (3) After completing T rounds of iteration, generate a graph-level embedding vector through GlobalAttention pooling operation:
[0054] ;
[0055] ;
[0056] wherein, is the node attention weight, w is a learnable parameter, σ is a sigmoid activation function, z is the graph-level embedding vector, is the final node representation vector of node i after T rounds of message passing and state updating.
[0057] The combined temperature scale cosine contrast learning method processes the encoded contract graph, including the following steps:
[0058] (1) using a pair of contract graphs G A and G B By encoding the generated normalized embedding vectors, the cosine similarity of the two embedding vectors is calculated:
[0059] ;
[0060] ;
[0061] ;
[0062] wherein, , are the embedding vectors of the normalized contract graphs A and B respectively, z A , z B are the graph-level embedding vectors extracted by the Siamese graph encoder from the contract graphs A and B respectively, used to represent the overall semantic features of the corresponding contract graphs, z A =f θ ( G A ), z B =f θ ( G B ), f θ is the Siamese encoder, and s is the cosine similarity;
[0063] (2) The combined temperature scale cosine contrast learning model is optimized by a binary cross-entropy loss function with a temperature scale, which pulls the embedding vectors of samples of the same vulnerability type closer together and pushes the embedding vectors of samples of different vulnerability types further apart. The binary cross-entropy loss function with a temperature scale is:
[0064] ;
[0065] wherein, is a temperature parameter used to control the scaling of the similarity score, y is the sample pair label, y∈{0,1}, 1 represents the same vulnerability type, and 0 represents the different vulnerability type, is a binary cross-entropy loss function with Sigmoid, used to measure the error between the predicted similarity and the true label.
[0066] An enhanced intelligent contract vulnerability detection system based on unified contract graphs, comprising:
[0067] A unified shell pruning module is used to adopt a hierarchical pruning strategy to perform pruning operations on the abstract syntax tree (AST) of the smart contract under global security constraints, generating a contract graph structure;
[0068] A unified graph semantic fusion module is configured to integrate four semantic relationships of syntax structure, control flow, data flow and state slot chain based on the pruned AST, and generate a contract graph;
[0069] A graph encoding and alignment module is configured to encode the contract graph through a Siamese pair-wise graph encoder, process the encoded contract graph by combining a temperature scale cosine contrast learning method, and realize alignment of vulnerability semantics in a shared latent space.
[0070] The present application has the following advantages and benefits:
[0071] 1. The detection accuracy is greatly improved: through the UDP module to remove noise nodes, the UGSF module to fuse multi-dimensional semantics, and the PGE+TSCC module to realize semantic alignment, the experiments on the messi. and solidfi datasets show that the F1 scores of the method for reentrant vulnerability and timestamp-dependent vulnerability reach 87.70% and 82.32% respectively, which is 10.53%-11.50% higher than the existing optimal method DR-GCN, and the false positive rate and the false negative rate are significantly reduced.
[0072] 2. Strong robustness and generalization ability: the unified contract graph construction method effectively solves the semantic fragmentation problem, and the contrast learning mechanism enhances the model's ability to identify different vulnerability types, which can adapt to diversified scenarios such as real contracts and artificially injected vulnerability contracts, and has good compatibility for different versions of smart contracts.
[0073] 3. High deployment efficiency: the pruning operation of the UDP module reduces the complexity of the graph structure, the calculation overhead in the graph construction and preprocessing stage is low, and it can run efficiently on CPU; the contrast learning and graph encoding modules support GPU acceleration, and can be integrated with GPU engines such as TensorRT, realizing end-to-end optimization, meeting the real-time requirements of large-scale contract auditing.
[0074] 4. Strong scalability: the method framework adopts modular design, each module works independently and can be upgraded flexibly. By extending the semantic relationship type (such as adding permission control relationship) and optimizing the model structure, it can adapt to more types of smart contract vulnerability detection such as integer overflow and permission defects, and has wide application prospects. BRIEF DESCRIPTION OF DRAWINGS
[0075] Figure 1 Figure 1 is a schematic diagram of the overall architecture of UCGVulDetector;
[0076] Figure 2 Figure 3 is a schematic diagram of syntax-level pruning of the UDP module;
[0077] Figure 3 Figure 5 is a schematic diagram of semantic fusion of the UGSF module. DETAILED DESCRIPTION
[0078] The application will be further described in detail below in combination with the accompanying drawings and examples.
[0079] An enhanced smart contract vulnerability detection method based on a unified contract graph of the application achieves the following objectives:
[0080] 1. Improved detection accuracy: F1 score is improved by more than 10% compared to the existing optimal method, and the false positive rate is reduced to less than 15%;
[0081] 2. Enhanced generalization ability: It can adapt to different Solidity versions, different business scenarios of contracts, and has certain recognition ability for unobserved vulnerability types;
[0082] 3. Improve deployment efficiency: CPU single contract detection time ≤100ms, support GPU acceleration, meet the needs of large-scale contract audit;
[0083] 4. Reduce the threshold for use: No need to manually write rules or modeling, realize end-to-end automatic detection, suitable for non-professional security personnel to use.
[0084] As shown in Figure 1 The core technical solution of the application is a "three-module collaborative architecture", namely a unified de-shelling pruning module (UDP), a unified graph semantic fusion module (UGSF), and a pair coding and contrast learning module (PGE+TSCC). The detailed design of each module is as follows:
[0085] 1. Unified de-shelling pruning module (UDP)
[0086] As shown in Figure 2 The core function of the UDP module is to perform "de-redundancy, semantic preservation" simplification processing on the original AST, solving the noise node interference problem in the existing graph-based method. Its design is based on the concept of "layered pruning + global constraints", which specifically includes three pruning stages and three global safety constraints:
[0087] (1) Pruning stage design
[0088] Stage 1: Field-level pruning (JSON layer processing)
[0089] When the original AST is stored in JSON format, some nodes contain redundant container fields (such as the "parameters" field of the ParameterList node, which contains auxiliary information such as "typeDescriptions", "src", and the like in addition to variable declarations), which are meaningless for vulnerability detection and increase data processing overhead. In this stage, according to the rules shown in Table 1, the redundant container fields are deleted, and only the core fields (such as variable name, type, line number) are retained.
[0090] Table 1 Field-level pruning rule table Rule ID Parent Type (PTYPE) Redundant field to be deleted Core field to be reserved F1 ParameterList typeDescriptions, src, documentation parameters (array of variable declaration), id F2 VariableDeclarationStatement src, documentation declarations (array of variable declaration), scope F3 ForStatement src, documentation initialization (initialization statement), condition (condition expression), update (update statement) F4 FunctionCall src, documentation arguments (array of parameter), expression (function expression)
[0091] Stage 2: Node-level pruning (syntax layer processing)
[0092] There are a large number of non-semantic wrapper nodes in the original AST (such as the ExpressionStatement node, which is only used to wrap expressions and has no actual semantics), which will increase the complexity of the graph and cause the model to learn irrelevant features. In this stage, according to the rules shown in Table 2, non-semantic nodes are deleted, and the core semantic nodes (such as FunctionCall, BinaryOperation) contained in them are directly mounted under the parent node to simplify the graph structure.
[0093] Table 2 Node-level pruning rule table
[0094] Rule ID Parent Type (PTYPE) Core child Type (CTYPE) Processing method S1 ExpressionStatement UnaryOperation, Assignment, FunctionCall, UpdateExpression Delete the ExpressionStatement node, and the core child node directly as a child node of the parent node S2 VariableDeclarationStatement VariableDeclaration Delete the VariableDeclarationStatement node, and the VariableDeclaration node directly as a child node of the parent node S3 Block ExpressionStatement, IfStatement, ForStatement If the Block node contains only a single ExpressionStatement child node, delete the Block node, and the core child node of ExpressionStatement is hung under the parent node of Block; if it contains multiple child nodes, keep the Block node
[0095] Taking the "require statement AST" shown in Figure 2 as an example, the original AST contains ExpressionStatement (wrapper node) and Arguments (container node), and after node-level pruning, these two nodes are deleted, and FunctionCall (require) and BinaryOperation (>=) are directly connected, reducing the number of graph nodes by 40% and retaining the core semantics.
[0096] Stage 3: Structure-level pruning (hierarchy alignment processing)
[0097] The AST hierarchy structures of different contracts differ greatly (such as some contracts nesting conditional judgment statements in Block, and some contracts directly as function body sub-nodes), making it difficult for the model to learn uniform structural features. In this stage, according to the rules shown in Table 3, the depth of the statement block is aligned and rearranged to ensure that nodes with the same semantics are at similar levels.
[0098] Table 3 Structure-level pruning rule table
[0099] Rule ID Target node type (PTYPE) Processing rule Purpose N1 Block If the parent node of the Block node is FunctionDefinition (function definition), and the number of child nodes contained in the Block is ≤ 5, delete the Block node, and the child nodes directly as the child nodes of FunctionDefinition; if the number of child nodes is > 5, keep the Block node Uniform the hierarchy of function body N2 IfStatement If the "trueBody” or "falseBody” of an IfStatement is a single Statement node (not a Block), wrap it into a Block node; if it is already a Block node, leave it as is Uniform the hierarchy of conditional branches N3 ForStatement Wrap the "initialization”, "condition”, and "update” statements of a ForStatement into Block nodes (if they are single Statement nodes) Uniform the hierarchy of loop statements
[0100] (2) Global safety constraints
[0101] To avoid excessive pruning leading to semantic loss, the UDP module sets three global safety constraints to control the pruning degree of each stage:
[0102] Constraint M1: Perform flattening operations (e.g., delete Block nodes) only when the child node has a grandchild node. For example, if the child node of a Block node is a single ExpressionStatement (without a grandchild node), do not delete the Block node to prevent losing statement boundary information.
[0103] Constraint M2: For field-level pruning of F3 (ForStatement.initialization) and F4 (FunctionCall.arguments), the "source node src field has no spaces" condition must be met (src field records the node's position in the source code, format "line: column - line: column", no spaces indicate complete position information) to avoid mistakenly deleting fields containing valid parameters.
[0104] Constraint M3: Maintain the non-flattened state of state variable-related nodes and function call expression nodes (call.expr). State variables (e.g., mapping type variables) are key objects for vulnerability detection (e.g., reentrant vulnerabilities often involve reading and writing state variables), and function call expression nodes contain function names, parameters, and other core information. Preserving their hierarchical structure ensures semantic integrity.
[0105] 2. Unified graph semantic fusion module (UGSF)
[0106] As shown in Figure 3 , the core function of the UGSF module is to build a unified heterogeneous graph that integrates multi-dimensional semantics, addressing the semantic fragmentation problem in existing methods. Based on the simplified AST output by UDP, the module integrates four types of semantic relationships as follows:
[0107] Syntax structure relationship: Preserve the connection relationship of core syntax nodes after pruning, reflecting the basic organizational form of contract code and serving as the basic skeleton of the heterogeneous graph.
[0108] Control flow relationship (CFG): Capture the execution order between statements, such as the jump relationship from if (a>0) to require (b[msg.sender]>=a) and b[msg.sender]-=a, and clearly define the execution path of the contract code.
[0109] Data flow graph (DFG): modeling the dependency of variables, tracking the definition, reading, and modification process of variables. For example, the read-write connection of variable a established by require(b[msg.sender] >= a) and msg.sender.transfer(a) clearly presents the passing path of variables.
[0110] State slot chain (SSC): linking multiple read / write operations of the same state variable into a causal chain in the source code order, revealing the evolution process of state variables. For example, the read operation of b[msg.sender] in the require statement and the update operation in b[msg.sender] -= a are connected by SSC, enabling the model to capture the causal association of state changes.
[0111] By integrating the above four semantic relationships, the UGSF module unifies structural information and semantic information into a heterogeneous graph, achieving comprehensive vulnerability-aware representation learning and providing rich semantic support for subsequent graph encoding.
[0112] 3. Graph encoding and alignment module (PGE+TSCC)
[0113] The core function of the PGE+TSCC module is to achieve deep alignment of vulnerability semantics through graph encoding and contrastive learning, solving the problem of weak semantic alignment in existing methods. Specifically, it includes two parts: contract graph embedding and pairwise similarity learning:
[0114] (1) Contract graph embedding
[0115] Let the contract graph be G=(V,E) where V is the node set, E is the edge set. Each node v_i∈ V is associated with a feature x_i, and each edge (i,j)∈E is associated with a feature x ij or discrete edge type a ij . First, map discrete / sparse input to continuous vector:
[0116]
[0117]
[0118] where MLP node and MLP edge are the multi-layer perceptron of nodes and edges, Embed edge respectively, and
[0119] Subsequently, T rounds of message passing are performed based on gated graph neural networks (GGNNs) to avoid cross-graph interactions:
[0120]
[0121]
[0122] Where φ(·) is a linear transformation combined with the ReLU activation function, N( i ) is a node i The neighbor set, GRU is a gated cyclic unit used to update the node representation.
[0123] After T iterations, GlobalAttention pooling is used to generate a graph-level representation:
[0124]
[0125] Where, α i For node attention weights, w For learnable parameters, σ The sigmoid activation function is used. z This is a graph-level embedding vector.
[0126] (2) Pairwise similarity learning
[0127] The contract graph pairs are encoded using a Siamese encoder with shared parameters, given a pair of contract graphs. G A and G B Generate normalized embedding vectors and calculate cosine similarity:
[0128]
[0129] Among them, z A =f θ ( G A ), z B =f θ ( G B ), f θ is the Siamese encoder, and s is the cosine similarity.
[0130] The model is optimized using a temperature-scale binary cross-entropy loss function:
[0131]
[0132] in, τ This is a temperature parameter used to control the scaling of the similarity score. yThe label of the sample is (1 represents the same vulnerability type, and 0 represents different vulnerability types). Through the loss function, the model can pull the embedding vectors of samples of the same vulnerability type closer, and push the embedding vectors of samples of different types farther apart, thereby enhancing the discriminability of the graph representation.
[0133] The vulnerability types that can be detected by the present application include re-entrant attack vulnerabilities and timestamp-dependent vulnerabilities. By extending the semantic relationship types and the model feature dimensions, the present application can be adapted to detect other high-risk vulnerabilities of smart contracts such as integer overflow.
[0134] The graph construction and preprocessing phase (UDP pruning and UGSF fusion) of the present application can be efficiently run on a CPU. The contrast learning and graph encoding modules can be accelerated on a GPU, and support integration with GPU engines such as TensorRT, thereby realizing end-to-end inference optimization.
[0135] A smart contract vulnerability detection method, comprising the following steps:
[0136] S1: Obtain the source code of the target smart contract, and parse and generate an original abstract syntax tree (AST);
[0137] S2: Perform hierarchical pruning on the original AST through the UDP module, and sequentially complete field-level, node-level and structure-level pruning to generate a simplified AST;
[0138] S3: Use the UGSF module to construct a heterogeneous graph based on the simplified AST, and integrate the syntax structure, control flow, data flow and state slot chain relationship;
[0139] S4: Input the heterogeneous graph into the PGE+TSCC module, generate a graph-level embedding vector through the PGE, and realize vulnerability semantic alignment with the help of the TSCC;
[0140] S5: Determine whether the smart contract has a vulnerability and the specific vulnerability type according to the similarity of the embedding vector, and output the detection result.
[0141] Embodiment
[0142] In order to make the technical solutions of the present application easier to implement, the following describes the specific implementation steps from five aspects of hardware environment, data set preparation, module implementation, model training and testing, and deployment application:
[0143] (I) Hardware environment configuration
[0144] The framework of the present application can be deployed in different hardware environments to meet the needs of different scenarios. The specific configurations are as follows:
[0145] Environment type CPU RAM GPU Operating system Software dependencies Applicable scenarios Basic environment Intel i5-12400 / AMD Ryzen 5 5600 8GB DDR4 None Ubuntu 20.04 LTS / Windows 10 Professional Python 3.8, PyTorch 1.12, DGL 0.9.1, solc 0.8.0 Small-scale contract auditing (≤100 copies / day), development and testing Standard environment Intel i7-12700K / AMD Ryzen 75800X 16GB DDR4 NVIDIA RTX3060 (12GB) Ubuntu 20.04 LTS Python 3.8, PyTorch 1.12, DGL 0.9.1, solc 0.4.0-0.8.0, TensorRT 8.4 Medium-scale contract auditing (100-1000 copies / day), enterprise internal auditing High-performance environment Intel i9-13900K / AMD Ryzen 97950X 32GB DDR5 NVIDIA RTX3090 (24GB) × 2 Ubuntu 22.04 LTS Python 3.8, PyTorch 1.12 (distributed training), DGL 0.9.1, solc 0.4.0-0.8.0, TensorRT 8.4 Large-scale contract auditing (>1000 copies / day), real-time auditing of blockchain platforms
[0146] (II) Data set preparation
[0147] The data set used by the present application is the fusion data set of "messi. + solidifi", which ensures sample diversity and label accuracy. The specific construction steps are as follows:
[0148] Data source 1: messi-q data set
[0149] Extract the smart contracts deployed from 2018 to 2023 from the Ethereum main network through the Etherscan API, and filter the conditions:
[0150] Support Solidity language, code line number ≥ 50 lines (exclude empty contracts or test contracts);
[0151] Contains at least one function (excludes contracts that only declare variables);
[0152] Has transaction records (ensures that the contract has been actually used);
[0153] A total of 40,932 contracts are extracted, cross-verified by manual audit and existing tools (SmartCheck, DR-GCN), labeled vulnerability types, and finally 4871 valid samples are retained (including 2563 vulnerability contracts and 2308 benign contracts).
[0154] Data source 2: solidfi data set
[0155] This data set is a publicly available smart contract vulnerability detection benchmark, containing 343 manually injected vulnerability contracts, with vulnerability types including reentrant attack, timestamp dependency, integer overflow, etc.
[0156] All contracts are labeled with vulnerability location and trigger condition, with label accuracy of 100%, which can be used for model performance verification.
[0157] Data collection and division
[0158] Merge the above two data sets, and finally get 5214 contract samples, including:
[0159] Reentrancy vulnerability samples: 2879 (2536 from Ethereum real contracts, 343 from Messi-Q data set);
[0160] Timestamp dependency vulnerability samples: 2335 (all from Ethereum real contracts);
[0161] Divide into training set (3650) and test set (1564) according to the ratio of 7:3, the ratio of positive samples (vulnerability contracts) and negative samples (benign contracts) in the training set is 1:1, and the test set maintains the original sample distribution.
[0162] (Three) module implementation steps
[0163] 1. Implementation of unified de-shelling pruning module (UDP)
[0164] Parse the smart contract source code, generate the original AST through the Solidity compiler, and save it in JSON format;
[0165] Perform pruning operations in the order of field level, node level, and structure level, delete redundant container fields, non-semantic wrapper nodes, and align statement block depth according to the rules and constraints of Tables 1-4;
[0166] Output the pruned AST, verify the semantic integrity through manual review and automated testing, and ensure that the core semantic information is not lost.
[0167] 2. Implementation of unified graph semantic fusion module (UGSF)
[0168] Based on the simplified AST, extract the syntax structure relationship and construct the basic graph skeleton;
[0169] Analyze the execution logic of the contract code, generate a control flow graph (CFG) through a control flow analysis algorithm, and clarify the execution order between statements;
[0170] Use the Def-Use Chain analysis method to construct a data flow graph (DFG) and model the dependency relationship of variables;
[0171] Identify all read / write operations of the same state variable, construct a state slot chain (SSC) in the order of source code line numbers, and add state dependency edges;
[0172] Integrate the above four kinds of semantic edges, assign a unique type identifier to each edge, generate a unified heterogeneous graph, and store it in a graph data format (such as DGLGraph) for subsequent processing.
[0173] 3. Implementation of graph encoding and alignment module (PGE+TSCC)
[0174] Node and edge feature mapping: map the type, attribute, and other discrete features of AST nodes into 256-dimensional continuous vectors through node MLP; map edge types and features into 128-dimensional continuous vectors through edge MLP or embedding layer, as shown in formulas (1) and (2).
[0175] Graph neural network message passing: set T=5 rounds of message passing, calculate neighbor messages and update node representations according to formulas (3) and (4) in each iteration, and ensure that nodes can capture global context information.
[0176] Graph-level embedding generation: The GlobalAttention pooling operation is adopted to calculate the node attention weights and aggregate the graph-level embedding vectors according to formula (5), highlighting the importance of vulnerability-related nodes.
[0177] Pairwise contrastive learning: Positive sample pairs (same vulnerability type) and negative sample pairs (different vulnerability types) are constructed in the training set. Embedding vectors are generated by a Siamese encoder with shared parameters, cosine similarity is calculated, and model parameters are optimized according to the loss function of formula (7). Iterative training is performed until the model converges.
[0178] (4) Model training and testing process
[0179] Model initialization: The parameters of the graph encoder, MLP layer, GRU unit and other components are initialized. The weights are initialized with a normal distribution of Xavier to ensure the stability of the training.
[0180] Training process: Set the batch size to 32, the number of training rounds to 100, use the Adam optimizer, the initial learning rate to 0.001, and the learning rate to 0.5 of the original every 20 rounds. Perform batch training on the training set, update the model parameters through backpropagation, and minimize the contrastive loss function.
[0181] Testing process: Input the contract graph in the test set into the trained model to generate graph-level embedding vectors, and output the vulnerability type prediction results through the fully connected layer. Calculate the accuracy (Acc), precision (Prec), recall (Rec) and F1 score to evaluate the detection performance of the model.
[0182] Result analysis: Compare the performance indicators of the present method with existing methods (such as SmartCheck, Slither, DR-GCN) to verify the advantages of the present method. Through ablation experiments, analyze the contribution of UDP and UGSF modules to the performance of the model to ensure the effectiveness of the design of each module.
Claims
1. A unified contract graph-based enhanced smart contract vulnerability detection method, characterized in that, The method comprises the following steps: The unified shell pruning module adopts a hierarchical pruning strategy to perform pruning operation on an abstract syntax tree (AST) of the smart contract under global safety constraints, and generates a contract graph structure; The unified graph semantic fusion module integrates four semantic relationships of the syntax structure, control flow, data flow and state slot chain of the pruned AST, and generates a contract graph; The graph encoding and alignment module encodes the contract graph through a Siamese pair graph encoder, processes the encoded contract graph through a temperature scale cosine contrast learning method, and realizes alignment of vulnerability semantics in a shared latent space.
2. The method of claim 1, wherein the method is based on a unified contract graph. The hierarchical pruning strategy comprises three stages, which are: In the field-level pruning stage, redundant container fields are deleted according to a set rule, and only core fields are reserved; In the node-level pruning stage, non-semantic nodes are deleted according to a set rule, and core semantic nodes contained in the non-semantic nodes are directly mounted under parent nodes; In the structure-level pruning stage, the depth of a statement block is aligned and rearranged according to a set rule, so that nodes with the same semantics are in similar levels.
3. The method of claim 2, wherein the method further comprises: The rule set in the field-level pruning stage is: Rule F1: When the type of the parent node is ParameterList, delete the redundant fields typeDescriptions, src and documentation, and reserve the core fields parameters (variable declaration array) and id; Rule F2: When the type of the parent node is VariableDeclarationStatement, delete the redundant fields src and documentation, and reserve the core fields declarations (variable declaration array) and scope; Rule F3: When the type of the parent node is ForStatement, delete the redundant fields src and documentation, and reserve the core fields initialization (initialization statement), condition (condition expression) and update (update statement); Rule F4: When the type of the parent node is FunctionCall, delete the redundant fields src and documentation, and reserve the core fields arguments (argument array) and expression (function expression).
4. The method of claim 2, wherein the method further comprises: The rule set in the node-level pruning stage is: Rule S1: When the type of the node to be deleted is ExpressionStatement, and the type of the core child node is UnaryOperation, Assignment, FunctionCall or UpdateExpression, delete the ExpressionStatement node, and directly take the core child node as the child node of the parent node; Rule S2: When the node to be deleted is of type VariableDeclarationStatement and the core child node is of type VariableDeclaratio, delete the VariableDeclarationStatement node and make the VariableDeclaration node a direct child of the parent node. Rule S3: When the node to be deleted is of type Block and the core child nodes are of type ExpressionStatement, IfStatement, or ForStatement, if the Block node contains only a single ExpressionStatement child node, delete the Block node and make the core child node of the ExpressionStatement a child of the parent node of the Block. If the Block node contains multiple child nodes, retain the Block node.
5. The method of claim 2, wherein the method further comprises: The rules set in the structural-level pruning phase are: Rule N1: When the target node is of type Block, if the parent node of the Block is of type FunctionDefinition and the Block contains no more than five child nodes, delete the Block node and make the child nodes direct children of the FunctionDefinition. If the number of child nodes is greater than five, retain the Block node. Rule N2: When the target node is of type IfStatement, if the "trueBody" or "falseBody" of the IfStatement is a single Statement node and is not a Block, wrap it in a Block node. If it is a Block node, leave it unchanged. Rule N3: When the target node is of type ForStatement, wrap the "initialization", "condition", and "update" statements of the ForStatement in Block nodes.
6. The method of claim 1, wherein the method is based on a unified contract graph. The global safety constraints are: Constraint M1: Perform the flattening operation on the AST only when there are grandchild nodes in the child nodes. Constraint M2: Perform the flattening operation on ForStatement.initialization and FunctionCall.arguments only when the src field has no space matches. Constraint M3: Maintain the non-flattened state of state variable-related nodes and the call.expr of function call expression nodes.
7. The method of claim 1, wherein the method is based on a unified contract graph. The unified graph semantic fusion module performs the following steps: Syntax structure relationship: retain the connection relationship of the core syntax nodes of the pruned AST. Control flow relationship: capture the execution order between statements. Data flow relationship: model the dependency relationship of variables and track the definition, reading, and modification process of variables. State slot chain relationship: link multiple read or write operations of the same state variable in source code order as a causal chain for revealing the evolution process of the state variable. 8.The method of claim 1, wherein, The contract graph is encoded by the Siamese pair graph encoder, including the following steps: (1) Map the node and edge features of the contract graph into continuous vectors: Let the contract graph be G=(V,E) where V is a set of nodes, E is a set of edges, each node ∈ V is associated with a feature , each edge (i,j) ∈ E is associated with a feature or a discrete edge type and the mapping process is: ; ; wherein, MLP node and MLP edge is a multi-layer perceptron for nodes and edges, respectively, Embed edge is an embedding layer for edge types, is an initial embedding vector for node i, reflecting the representation of the original features of the node after mapping, is an embedding vector for edge (i,j), reflecting the relationship features between node i and node j; (2) Perform T rounds of message passing through the gated graph neural network: ; ; wherein, (·) is a linear transformation combined with a ReLU activation function, N( i ) is a neighbor set of node i GRU is a Gated Recurrent Unit, is the message vector transmitted from neighbor node j to target node i in the t-th round of message passing, reflecting the local semantic interaction between the two nodes, is the comprehensive message representation vector obtained by aggregating all incoming messages from its neighbor nodes in the t-th round, used to update the state of the node itself; (3) After completing T rounds of iteration, generate a graph-level embedding vector through the GlobalAttention pooling operation: ; ; where, is the node attention weight, w is the learnable parameter, σ is the sigmoid activation function, z is the graph-level embedding vector, is the final node representation vector of node i after T rounds of message passing and state updating. 9.The method of claim 1, wherein, The contract graph after encoding is processed by the temperature scale cosine contrast learning method, including the following steps: (1) using a pair of contract graphs G A and G B The cosine similarity of the two embedding vectors is computed by encoding the generated normalized embedding vectors: ; ; ; wherein, , are the embedding vectors of the normalized contract graphs A and B respectively, z A , z B are the graph-level embedding vectors of the contract graphs A and B respectively extracted by the Siamese graph encoder, used to represent the overall semantic features of the corresponding contract graphs, z A = f θ ( G A ), z B = f θ ( G B ), f θ is the Siamese encoder, and s is the cosine similarity. (2) The cosine contrast learning model combined with the temperature scale is optimized by a binary cross-entropy loss function of the temperature scale, so as to bring the sample embedding vectors of the same vulnerability type closer and push the sample embedding vectors of different vulnerability types away, and the binary cross-entropy loss function of the temperature scale is as follows: L = - 1 N å i = 1 N [log ( 1 + exp ( - y i t i ) ) ] ; wherein, is a temperature parameter for controlling the scaling of the similarity score, y is a sample pair label, y e {0, 1}, 1 indicates same vulnerability type, 0 indicates different vulnerability type, is a binary cross-entropy loss function with Sigmoid, used to measure the error between the predicted similarity and the true label. 10.A system for enhanced smart contract vulnerability detection based on a unified contract graph, the system comprising: including: A unified hull pruning module is configured to adopt a hierarchical pruning strategy to perform pruning operation on an abstract syntax tree (AST) of the smart contract under global safety constraints, and generate a contract graph structure. A unified graph semantic fusion module is configured to integrate four semantic relationships of the syntax structure, control flow, data flow and state slot chain of the pruned AST, and generate a contract graph. A graph encoding and alignment module is configured to encode the contract graph by the Siamese pair graph encoder, and process the encoded contract graph by the temperature scale cosine contrast learning method, so as to realize the alignment of vulnerability semantics in the shared latent space.