Intelligent contract security analysis method and system based on neighbor contrast learning
By constructing a multi-dimensional information contract graph and learning from neighbor comparisons, combined with a dynamic edge semantic correction mechanism, the problem of sparse and noisy graph structure in smart contract analysis is solved, achieving more accurate vulnerability detection and stronger robustness.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-06
- Publication Date
- 2026-03-10
AI Technical Summary
Existing smart contract analysis methods based on GAT struggle to accurately target critical vulnerability paths when dealing with sparse, noisy graph structures. They lack explicit alignment and constraints on node semantic information and have insufficient edge weight modeling, resulting in inadequate accuracy, robustness, and generalization ability in vulnerability detection models.
By constructing a contract graph that integrates multi-dimensional information, introducing a neighbor contrastive learning and dynamic edge semantic correction mechanism, key nodes, ordinary nodes and backoff nodes are explicitly distinguished. A contract graph of control flow, data flow and backoff edges is constructed, and feature aggregation and classification are performed through neighbor contrastive learning and graph attention network. Finally, a multilayer perceptron is used for classification.
It achieves accurate capture of key vulnerability information, improves the model's discrimination ability and generalization, can more accurately detect vulnerabilities in smart contracts, and enhances robustness and insensitivity to noise.
Smart Images

Figure CN121637500A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of smart contract security analysis technology, and in particular to a smart contract security analysis method and system based on neighbor comparison learning. Background Technology
[0002] In the field of smart contract security analysis, graph neural network (GNN) based methods have become the mainstream technical approach. These methods abstract contract code into control flow graphs, data flow graphs, or abstract syntax trees, and automatically capture vulnerability patterns by learning the features of nodes and edges in the graph. Among them, graph attention networks (GAT) improve upon the homogenization problem of traditional graph convolutional networks in aggregating neighbor information by introducing an attention mechanism, enabling differentiated feature fusion based on the importance of neighbor nodes.
[0003] However, existing smart contract analysis solutions based on GAT still have several core shortcomings that urgently need to be addressed: First, due to the complexity and diversity of smart contract code, its corresponding graph structure often exhibits high sparsity and contains a large number of noisy edges and redundant nodes unrelated to vulnerabilities. The attention mechanism of traditional GAT relies heavily on the topology of the graph itself. In this sparse and noisy environment, it is prone to feature drift, making it difficult to accurately focus on the truly critical vulnerability triggering path.
[0004] Secondly, existing methods generally lack explicit alignment and constraint mechanisms for node semantic information. They rely solely on graph structure for feature propagation, ignoring the deep semantic relationships between code units, resulting in insufficient semantic understanding of the code and an inability to fully utilize the implicit relationships in the graph.
[0005] Finally, edge weights in traditional GAT are usually static or calculated solely from node features, failing to fully consider the rich semantic information carried by the edges themselves (such as edge type and execution order) and the influence of the global code context. This makes it difficult for the model to dynamically identify and amplify the critical paths that play a decisive role in vulnerability propagation.
[0006] The aforementioned issues collectively hinder further improvements in the accuracy, robustness, and generalization ability of vulnerability detection models. Summary of the Invention
[0007] The purpose of this section is to outline some aspects of embodiments of the present invention and to briefly describe some preferred embodiments. Simplifications or omissions may be made in this section, as well as in the abstract and title of this application, to avoid obscuring the purpose of these documents; however, such simplifications or omissions should not be construed as limiting the scope of the invention.
[0008] Therefore, to solve the above-mentioned technical problems, this invention provides the following technical solution: a smart contract security analysis method based on neighbor comparison learning. Its core lies in constructing a contract graph that integrates multi-dimensional information and introducing neighbor comparison learning and dynamic edge semantic correction mechanisms to achieve more accurate and robust vulnerability detection. The method includes the following steps: Step S1: Perform function-level slicing and parsing on the input smart contract source code, dividing it into clear sets of functions to form the basic units for subsequent analysis.
[0009] Step S2: Based on preset vulnerability identification rules, traverse the function set to accurately identify and mark critical nodes, ordinary nodes, and fallback nodes. Among them, critical nodes are directly associated with potential vulnerability triggering conditions; ordinary nodes, although they do not directly trigger vulnerabilities, have control flow or data flow dependencies with critical nodes, forming an important context for vulnerability propagation paths; fallback nodes are specifically used to model security risk paths under special transfer calls such as call.value.
[0010] Step S3: Transform the above nodes into an Abstract Syntax Tree (AST) structure, and based on the defined node features and edge types, construct a contract graph that can fully preserve the contract syntax and deep semantic relationships. This graph includes control flow edges, data flow edges, and backoff edges, thereby comprehensively capturing the static structure and dynamic execution logic of the contract code.
[0011] Step S4: To address the inherent sparsity and noise interference of the contract graph constructed in Step S3, and to fully utilize the rich semantic features of the edges in the graph, this invention first dynamically updates the neighbor set of each node based on semantic feature similarity and graph topological distance. Subsequently, a graph attention network (GAT) incorporating a dynamic edge semantic correction mechanism is used to aggregate the updated neighbor features. Finally, a classification model is constructed using a multilayer perceptron (MLP). The core of this step is to achieve consistent alignment of node embeddings at both the semantic and structural levels.
[0012] Step S5: The classification model is trained using a total loss function that combines neighbor contrastive learning loss and classification loss. Neighbor contrastive learning constructs positive and negative sample pairs to specifically optimize the model's ability to discriminate and generalize sparse graph data; the classification loss aims to minimize the difference between the model's prediction and the true label. Both work together to drive the model to achieve high-precision smart contract vulnerability detection.
[0013] As a preferred embodiment of the smart contract security analysis method and system based on neighbor comparison learning described in this invention, the preset identification rules in step S2 specifically cover code patterns highly correlated with common vulnerability patterns. For example, fund transfer calls, external call instructions, time-dependent logic, or complex loop structures in function nodes; balance modifications, time condition judgments, highly complex loops, or external interaction operations in statement nodes; and fund status variables, timestamp variables, or shared state variables in variable nodes. The introduction of fallback nodes aims to accurately capture potential risk paths that do not explicitly define fallback functions but involve external transfer calls.
[0014] As a preferred embodiment of the smart contract security analysis method and system based on neighbor comparison learning described in this invention, in step S3, to accurately model the contract graph, all nodes contain the features ID, TYPE, CALLER, and ASTEmb. Edge construction follows strict semantic rules: control flow edges are established when there are explicit control dependencies such as while, for, or function call order; data flow edges are established when there are data dependencies such as variable assignment or reading; and backoff edges are established from the calling node to a dedicated backoff node when an external call instruction such as call.value is detected. Each edge records the starting node, ending node, order, and type attributes, thus fully preserving the dynamic relationships of the contract execution path.
[0015] As a preferred embodiment of the smart contract security analysis method and system based on neighbor comparison learning described in this invention, step S4, updating the neighbor node set, is a crucial step. The process includes: calculating the semantic feature similarity between nodes and including nodes with similarity higher than a preset threshold as semantic neighbors; simultaneously, calculating the graph topological distance (e.g., shortest path) between nodes and including nodes with distance lower than a preset threshold as structural neighbors. Furthermore, the dynamic edge semantic correction mechanism proposed in this invention generates a dynamic edge weight by integrating edge feature encoding, node similarity, and global graph context aggregation information. This weight is used to correct the original attention weights in the graph attention network, thereby achieving differentiated aggregation of neighbors of different importance.
[0016] As a preferred embodiment of the smart contract security analysis method and system based on neighbor comparison learning described in this invention, wherein: in step S4, the optimization of the graph attention network further includes: adopting a grouping normalization strategy based on edge type differentiation and hierarchical aggregation to distinguish the importance of different semantic relationships when aggregating neighbor features, thereby effectively reducing noise interference.
[0017] As a preferred embodiment of the smart contract security analysis method and system based on neighbor comparison learning described in this invention, in step S4, the classification task is completed by a multilayer perceptron. This model takes the feature representation optimized and aggregated by a graph attention network as input, and through a series of learnable linear transformation layers and nonlinear activation functions, finally maps to a classification output, intuitively indicating whether the target contract has security vulnerabilities.
[0018] As a preferred embodiment of the smart contract security analysis method and system based on neighbor contrastive learning described in this invention, in step S5, the total loss function for model training is designed as a weighted sum of the neighbor contrastive learning loss and the classification loss. This design allows the model to focus on accurate classification while also strengthening its ability to capture the inherent patterns of the graph structure through contrastive learning strategies. Specifically, the neighbor contrastive learning loss is calculated based on positive and negative sample pairs constructed from semantic and structural neighbors, aiming to improve the model's generalization performance on sparse graph data; while the classification loss uses the standard binary cross-entropy loss to directly optimize the model's classification accuracy.
[0019] As a preferred embodiment of the smart contract security analysis method and system based on neighbor contrastive learning described in this invention, the neighbor contrastive learning loss can be further decomposed into semantic neighbor loss and structural neighbor loss. The calculation of each loss term is achieved in the feature representation space by maximizing the similarity of positive sample pairs while minimizing the similarity of negative sample pairs. This process typically introduces a temperature coefficient to adjust the intensity of contrastive learning, thereby making fuller use of the implicit semantic relationships in the graph structure and effectively reducing interference from noisy nodes and edges.
[0020] The present invention also provides a system for implementing the above method, characterized in that it comprises: The graph construction module is responsible for executing steps S1 to S3, completing the transformation from smart contract source code to a contract graph structure rich in syntactic and semantic relationships.
[0021] The graph neural network module is responsible for executing step S4. Its core function is to complete the deep aggregation of node features and the construction of a classification model through neighbor updates, dynamic edge semantic correction, and an optimized graph attention network.
[0022] The neighbor comparison learning module is responsible for performing the neighbor comparison loss calculation in step S5. Through carefully constructed positive and negative sample pairs, it improves the model's robustness and discriminative ability to sparse and noisy graph representations.
[0023] The vulnerability detection module, as the system's output interface, automatically analyzes the input smart contracts based on a trained classification model and outputs the final vulnerability classification results.
[0024] The beneficial effects of this invention are: 1. This invention addresses the issues of sparse graph structures and noise interference by introducing a multi-layered, fine-grained graph construction and feature extraction strategy, achieving accurate capture of key vulnerability information. This invention explicitly distinguishes between key nodes, ordinary nodes, and fallback nodes through preset rules, and constructs a contract graph that integrates the Abstract Syntax Tree (AST) and multiple semantic relationships (control flow, data flow, fallback). This refined graph construction method highlights the core logic related to vulnerabilities from the source, filters out irrelevant noise, and provides high-quality, high-information-density input for subsequent model learning, thereby more accurately capturing key structural information in the contract code.
[0025] 2. This invention addresses the problems of data sparsity and the lack of explicit feature alignment mechanisms by proposing a semantic and structural dual-neighbor contrastive learning strategy, effectively improving the model's discriminative ability and generalization. The neighbor contrastive learning module of this invention defines a node's "neighbors" from two orthogonal and complementary dimensions: semantic similarity and graph topology. By constructing a semantic neighbor set and a structural neighbor set for each node, and then constructing positive and negative sample pairs for contrastive learning, it explicitly aligns semantically similar nodes and distances semantically unrelated nodes in the embedding space. This mechanism not only alleviates feature degradation caused by data sparsity but also forces the model to fully explore and utilize the implicit semantic relationships in the graph, thereby learning more discriminative and noise-insensitive robust feature representations.
[0026] 3. This invention addresses the shortcomings of traditional GAT edge weight modeling by designing a dynamic edge semantic correction mechanism, achieving adaptive enhancement of critical vulnerability paths. This invention deeply integrates the dynamic edge semantic correction mechanism into the attention calculation of traditional GAT. This mechanism uses a dedicated edge semantic scoring network to generate a dynamic, semantically aware weight correction factor for each edge, integrating edge features, node similarity, and global graph context information. This allows the model to transcend the limitations of local topology, adaptively correcting and amplifying the attention weights based on the true semantic importance of edges, thus ensuring that critical edges in the vulnerability propagation path dominate feature aggregation. This technique forms a deep synergy with the aforementioned two-neighbor contrastive learning strategy: contrastive learning provides a semantically consistent structured context for edge weight correction, while dynamic edge weight correction ensures that the features aggregated under the guidance of contrastive learning are more accurate and robust. Together, they form a mutually reinforcing organic whole. Attached Figure Description
[0027] To more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings used in the description of the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort. Wherein: Figure 1 This is a schematic diagram of the overall structure of the present invention.
[0028] Figure 2 This is a schematic diagram of the experimental method and model structure of the present invention.
[0029] Figure 3 This is a schematic diagram of the graph construction structure of the present invention.
[0030] Figure 4 This is a schematic diagram of the graph neural network structure that combines neighbor comparison learning according to the present invention. Detailed Implementation
[0031] To make the above-mentioned objects, features and advantages of the present invention more apparent and understandable, the specific embodiments of the present invention will be described in detail below with reference to the accompanying drawings.
[0032] Many specific details are set forth in the following description in order to provide a full understanding of the invention. However, the invention may also be practiced in other ways different from those described herein, and those skilled in the art can make similar extensions without departing from the spirit of the invention. Therefore, the invention is not limited to the specific embodiments disclosed below.
[0033] Secondly, the term "an embodiment" or "embodiment" as used herein refers to a specific feature, structure, or characteristic that may be included in at least one implementation of the present invention; the phrase "in an embodiment" appearing in different places in this specification does not all refer to the same embodiment, nor is it a single or selective embodiment that is mutually exclusive with other embodiments.
[0034] Example 1 Reference Figures 1-4 The first embodiment of the present invention provides a smart contract security analysis method based on neighbor comparison learning. The method first converts the smart contract source code into a contract graph, and then performs feature learning and classification through a graph neural network model that integrates dynamic edge semantic correction and neighbor comparison learning. Step S1: Function-level slicing and parsing First, lexical and syntactic analysis is performed on the input Solidity smart contract source code. Then, using existing code analysis tools (such as Slither) or a custom parser, the contract is segmented according to the `function` keyword, forming a set of function-level basic units. Each function As an independent contextual unit for subsequent analysis; Step S2: Rule-based multi-type node identification; This step aims to identify three types of nodes from the function set: critical nodes, ordinary nodes, and fallback nodes; the specific rules and implementation details are as follows: Critical node identification: Each function is scanned based on a preset vulnerability pattern library; functions, statements, or variables that meet the rules shown in Table 1 below will be marked as critical nodes; Identification of ordinary and irrelevant nodes: For code units that do not meet the critical node rules, their dependencies with critical nodes are determined through control flow analysis (CFA) and data flow analysis (DFA). If there is a direct or indirect control flow edge or data flow edge between the node and any critical node, the node is marked as an ordinary node. If there is no control flow or data flow dependency between the node and any critical node, and the node does not participate in the semantic context of function execution (i.e., it has no actual semantic contribution or is an isolated node), the node is marked as an irrelevant node and removed during graph construction to reduce noise and computational redundancy. Table 1 Key Node Identification Rules:
[0036] Step S3: Contract graph construction; This step transforms the nodes identified in the previous step into a graph structure, as illustrated in the attached diagram. Figure 2 ; Node definition and characterization: Each node Each node contains four features: ID (unique identifier), TYPE (node type: critical, normal, or fallback), CALLER (call function), and ASTEmb (the embedded representation of the AST subtree corresponding to the node). Edge definition and construction: Based on the semantic facts of the code, three types of edges are constructed: control flow edges, data flow edges, and fallback edges. Control flow edges are established when there are explicit control dependencies, such as while, for, and function call order. Data flow edges are established when there are data dependencies, such as variable assignment and reading. Fallback edges are established when there are external call instructions such as call.value. The characteristics of an edge are: starting node ( ), Termination Node ( ), Order, and Type; The specific edge type definitions are shown in Table 2; Table 2 Edge Type Definitions:
[0037] Ultimately, the formal definition of the contract graph is: ,in, It is a set of nodes. It is a set of edges; Step S4: Neighbor update, graph feature aggregation, and classification model construction; This step is the core of the model, and its structural diagram is attached. Figure 4 ; Graph Attention Networks (GATs) calculate the attention weights of neighbors based on the feature representations of nodes and their neighbors, and then update the node's own feature representation through weighted aggregation; however, contract graphs... The problem arises from sparse graph structure and feature drift caused by noisy edges. This embodiment introduces semantic feature similarity and graph topological distance to update neighbor nodes, which can explicitly constrain the semantic and structural consistency of the node embedding space. The specific implementation is as follows: S41: Initial feature representation: Regarding the contract diagram For each node to its original features (e.g., ASTEmb) and location encoding The nodes are pieced together and projected into the hidden space. Initial feature representation in the hidden space The expression is: ; ; in, Original features For position encoding, It is a concatenated representation of the original features and positional codes. It is layer normalization. and These are the learnable weight matrix and the bias term, respectively. For nodes The initial feature representation; S42: Neighbor node set update: S421: Semantic Neighbors: Computational Nodes With all other nodes in the graph Semantic feature similarity; when the similarity is greater than or equal to the threshold At that time, Join semantic neighbor set Semantic feature similarity The calculation formula is: ; in, For nodes Feature representation, For nodes Feature representation; S422: Structural Neighbors: Based on graph topological distance (shortest path) To select a node Structural neighbors; when the distance is less than or equal to a threshold At that time, Join Structural Neighbor Sets Topological distance The calculation formula is: ; node final neighbor set It is the union of semantic neighbors and structural neighbors, i.e. ; S43: Graph attention network incorporating dynamic edge semantic correction: S431: Edge-type-aware attention computation: updating nodes based on semantic and structural neighbors. After obtaining the neighbor set, for the updated node pair In order to measure nodes For nodes To address the criticality of this invention, edge type awareness and hierarchical aggregation mechanism, as well as dynamic edge semantic correction mechanism, are introduced in the attention calculation stage. Specifically, for each attention head and each edge Each type of edge (including control flow edges, data flow edges, and backoff edges) is assigned a separate dedicated transformation matrix. Attention Vector This approach integrates edge features and sequence information into the attention score calculation to achieve differentiated information modeling; attention score The calculation formula is: ; in, , ; Where k is the attention head number, ; , respectively Nodes in a layered network Feature representation, nodes Feature representation; This is a transformation matrix specific to edge type r; It is the attention vector of edge type r under the k-th attention head. For edge feature mapping, For sequential encoding mapping, This represents vector concatenation. For activation functions; S432: Dynamic Edge Semantic Correction: To measure the true semantic importance of each edge, an edge semantic network is introduced to generate edge semantic scores based on edge features and node similarity. To enhance the model's ability to perceive the overall semantic state of the graph; edge semantic scoring The calculation formula is: ; in, , Here are the weight matrices for the first and second layers. , which are the bias vectors of the first and second layers. It is a non-linear activation function. This is the output layer weight matrix. Encode edge features; Subsequently, edge semantic scoring will be performed. Mapped to dynamic edge weights The dynamic edge weights are updated smoothly using an exponential moving average: ; in, For smoothing coefficients, , For trainable bias terms, For activation functions; Correcting unnormalized attention scores using dynamic edge weights: + ; in, For bias terms; S433: Attention Weight Normalization and Feature Aggregation: For Nodes All neighboring nodes The attention vector is normalized to obtain the final attention weights. Unlike traditional graph attention networks that only perform uniform normalization among neighbors of the same type, this embodiment adopts a grouping normalization strategy based on edge type differentiation and hierarchical aggregation, as shown in the formula: ; in, Represents a node All neighboring nodes; During the normalization process, the weight balance of different edge types and node levels (key nodes and ordinary nodes) is considered simultaneously, so that the model can distinguish the importance of different semantic relationships when aggregating neighbor features. Through this mechanism, the feature representation of key nodes will receive higher attention weights, and the context information of ordinary nodes will be orderly fused into the key node representation after normalization, effectively reducing the interference of irrelevant neighbors and noisy edges. Using normalized attention weights Feature representation of neighboring nodes Perform weighted aggregation and obtain nodes through a nonlinear activation function. New feature representation The formula is: ; in, ( ) is a non-linear activation function. express Feature representation of neighboring nodes of a layer For the first The linear transformation weight matrix corresponding to each attention head; S44: Classification Model The nodes obtained through the optimized graph attention network New feature representation The classification model is obtained by inputting the multilayer perceptron; the expression of the classification model is: ; in, , , , Here are the learnable parameters of the MLP, and ReLU is the activation function. The softmax activation function is used. For category values; The formula outputs This indicates the probability that the contract has a vulnerability. This indicates the existence of a vulnerability; This indicates that no vulnerabilities exist; Step S5: Model training and vulnerability detection; This step trains the model using a joint loss function; Loss function design: The classification model is continuously trained using a total classification loss function based on neighbor comparison learning. The goal is to minimize the difference between predicted values and true labels. The parameters of the classification model are continuously adjusted to obtain the final trained model. This trained model is then used for vulnerability classification, enabling smart contract security analysis. (Total classification loss function) Learning loss by comparing with neighbors and classification loss The weighted average is calculated using the following formula: ; in, , This is an adjustable parameter used to balance the two losses; Neighbor comparison learning loss This loss is designed to bring positive sample pairs closer together and push negative sample pairs further apart, in order to learn a more discriminative graphical representation. The calculation formula is as follows: ; Among them, semantic neighbor comparison loss Loss compared with structural neighbors The calculation method is as follows: ; ; in, For temperature coefficient, () represents the cosine similarity. It is the set of positive samples of semantic neighbors (sampled from its corresponding set of neighbors). The set of negative samples from semantic neighbors (sampled from the set of non-neighbors). For nodes Feature representation; It is the set of positive samples of structural neighbors (sampled from its corresponding set of neighbors). The set of negative samples from the structural neighbors (sampled from the set of non-neighbors); Classification loss : Use binary cross-entropy loss; ; in, It is the first The probability that a given contract sample is classified as positive (i.e., has a vulnerability). It is the first The true labels of each contract sample The number of contract samples used in training; Model Training and Detection: Minimizing the Total Loss Using the Adam Optimizer The model parameters are iteratively optimized on the training set; after training, the hyperparameters are adjusted using the validation set, and finally the performance is evaluated on the test set. The trained model is then used to perform automated vulnerability detection on unknown smart contracts. The smart contract security analysis system based on neighbor comparison learning of the present invention includes the following modules: Graph construction module: calls the code parser and static analysis tools to implement the functions of steps S1 to S3 and outputs the contract graph G; Graph Neural Network Module: Implements neighbor update, dynamic edge semantic correction GAT and MLP classifier in step S4 based on frameworks such as PyTorch Geometric or DGL; The neighbor comparison learning module is responsible for sampling and loss of positive and negative sample pairs during training. The calculations provide support; Vulnerability detection module: Integrates a pre-trained model, provides a user interface, takes smart contract source code as input, and outputs a vulnerability detection report.
[0038] Example 2 This is the second embodiment of the present invention. The difference between this embodiment and the first embodiment is that, in order to verify the effectiveness of the method of the present invention, this embodiment was experimentally tested and compared with the ten most advanced vulnerability detection schemes under the same dataset. The experimental results are shown in Table 3. Table 3: Performance data comparison between the present invention and the prior art:
[0039] As shown in Table 3, the experimental results demonstrate that the accuracy of the proposed method reaches 90.57%, which is 8.22% higher than the current best method. Furthermore, the accuracy and recall rates are improved by 0.07% and 10.15% respectively compared to the highest values in existing technologies. In addition, the F1-score of the proposed model is 6.94% higher than the highest value in existing technologies. These data fully demonstrate the effectiveness and advancement of the proposed method in the field of smart contract security analysis.
[0040] In summary, this invention, in terms of data processing, automatically distinguishes between key nodes, ordinary nodes, and fallback nodes by performing function slicing and graph-structured modeling on the smart contract source code. Furthermore, it utilizes Abstract Syntax Trees (ASTs) to embed supplementary semantic information of nodes, thereby improving the model's coverage of contract semantics and execution logic while maintaining lightweight design. Simultaneously, this invention proposes a neighbor comparison learning module that jointly models semantic and structural neighbors, effectively mitigating the performance degradation caused by the sparsity of smart contract data and reducing interference introduced by noisy edges and irrelevant nodes. This design allows the model to more fully utilize implicit relationships in the graph, thus exhibiting stronger robustness and generalization ability in vulnerability detection tasks.
[0041] It should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and are not intended to limit it. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can be made to the technical solutions of the present invention without departing from the spirit and scope of the technical solutions of the present invention, and all such modifications or substitutions should be covered within the scope of the claims of the present invention.
Claims
1. A smart contract security analysis method based on neighbor contrast learning, characterized in that: The method comprises the following steps: Step S1: function-level slicing and parsing of the input smart contract source code, the source code is divided according to the function keywords to form a set of function-level basic units; Step S2: based on the preset identification rule, the function set is traversed, the functions, statements or variables that meet the vulnerability-related conditions are marked as key nodes, the functions, statements or variables that have control flow or data flow dependence with the key nodes but are not directly involved in the vulnerability triggering are marked as ordinary nodes, a backtracking node is introduced to model the security risk under the special execution path, and irrelevant nodes that do not meet the above conditions are removed to reduce noise; Step S3: based on the abstract syntax tree embedding feature, the key nodes, ordinary nodes and backtracking nodes are converted into a graph structure, and a contract graph is constructed based on the node features and edge definitions, wherein the contract graph retains the syntax and semantic relationship, including control flow edges, data flow edges and backtracking edges, to capture the structure and semantic information of the contract code; Step S4: for the sparsity and noise interference of the contract graph, the neighbor node set is updated based on the semantic feature similarity and graph topology distance, the updated neighbor features are aggregated and updated by a graph attention network fused with a dynamic edge semantic correction mechanism, and a classification model is constructed by combining a multilayer perception mechanism, so as to realize the semantic consistency and structural consistency alignment of node embedding; Step S5: the classification model is trained by using a total loss function fused with neighbor contrast learning loss and classification loss, wherein the neighbor contrast learning optimizes the discriminability of sparse graph representation through positive and negative sample pairs, and combines the classification loss to minimize the difference between the prediction and the real label, so as to realize the smart contract vulnerability detection.
2. The neighbor contrastive learning based smart contract security analysis method of claim 1, wherein: In the step S2, the preset identification rule includes: there are fund transfer calls, external call instructions, time-dependent logic or loop structures in the function nodes; the statement nodes contain balance modification, time condition judgment, high complexity loop or external interaction; the variable nodes are fund state variables, timestamp variables or shared state variables; the backtracking node is dedicated to simulating the backtracking function path under the call.value and other transfer calls.
3. The neighbor contrastive learning based smart contract security analysis method of claim 2, wherein: In the step S3, all nodes contain four features: ID, TYPE, CALLER and ASTEmb; the control flow edge is established when there is an explicit control dependence including while, for or function call sequence; the data flow edge is established when there is a data dependence including variable assignment or reading; the backtracking edge is established from the call node to the backtracking node when there is an external call instruction including call.value; each edge includes start node, end node, sequence and type attributes.
4. The neighbor contrastive learning based smart contract security analysis method of claim 3, wherein: The updating of the neighbor node set in the step S4 includes: calculating the semantic feature similarity between nodes, and including the corresponding node in the semantic neighbor when the similarity is greater than or equal to a preset threshold; calculating the graph topology distance, and including the corresponding node in the structural neighbor when the distance is less than or equal to a preset threshold; the final neighbor set is the union set of the semantic neighbor and the structural neighbor; and the dynamic edge semantic correction mechanism generates a dynamic edge weight by edge feature encoding and node similarity, and is used for correcting the attention weight in the graph attention network.
5. The neighbor contrastive learning based smart contract security analysis method of claim 4, wherein: The dynamic edge semantic correction mechanism is implemented by an edge semantic scoring network, which comprehensively considers the edge feature encoding and the feature representation similarity of the nodes before and after the edge, generates a dynamic edge weight to correct the attention weight in the graph attention network.
6. The neighbor contrastive learning based smart contract security analysis method of claim 5, wherein: The graph attention network adopts a grouping normalization strategy based on edge type differentiation and hierarchical aggregation to aggregate neighbor features; and the multi-layer perception classification model maps the classification output by multi-layer linear transformation and an activation function based on the aggregated node feature representation.
7. The neighbor contrastive learning based smart contract security analysis method of claim 6, wherein: In the step S5, the total loss function is a weighted sum of a neighbor contrast learning loss and a binary cross-entropy classification loss; and the neighbor contrast learning loss is obtained by calculating the contrast losses of the semantic neighbor and the structural neighbor respectively.
8. The neighbor contrastive learning based smart contract security analysis method of claim 7, wherein: Each contrast loss term in the neighbor contrast learning loss is obtained by calculating the ratio of the similarity of the node feature representations in a positive sample pair and a negative sample pair, and introducing a temperature coefficient for adjustment.
9. A system for implementing the method of any one of claims 1 to 8, characterized in that, The method comprises the following steps: a graph construction module, configured to perform steps S1 to S3, and convert the smart contract source code into a contract graph structure that retains the syntax and semantic relationship; a graph neural network module, configured to perform step S4, and aggregate features and construct a classification model by neighbor updating, dynamic edge semantic correction and optimization of the graph attention network; a neighbor contrast learning module, configured to perform the neighbor contrast loss calculation in step S5, and improve the robustness and discriminability of the sparse graph representation by positive and negative sample pairs; a vulnerability detection module, configured to output a smart contract vulnerability classification result based on the trained classification model.