Contract attack detection method and device based on symbolic execution and graph neural network
By constructing a contract call information graph using symbolic execution and graph neural networks, and combining it with deployer characteristics, the problem of high false positive rates and inconsistent detection of smart contract attacks is solved, enabling automatic identification and efficient detection of multiple attack modes.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- ZHEJIANG UNIV
- Filing Date
- 2026-05-12
- Publication Date
- 2026-06-12
AI Technical Summary
Existing technologies suffer from high false positive rates, inconsistent detection results, difficulty in covering diverse attack methods, and lack of analysis of the on-chain behavior of contract deployers when identifying smart contract attacks, resulting in high false negative rates.
By extracting the control flow and data flow information of the contract through symbolic execution, a contract call information graph is constructed. Graph neural networks are used to learn the contract structure and behavioral characteristics. Combined with the on-chain metadata characteristics of the deployer, automatic detection of attack contracts is achieved.
It reduces the false alarm rate, improves the consistency of detection results, can automatically identify multiple attack types, and significantly improves detection performance.
Smart Images

Figure CN122197005A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of blockchain security and smart contract analysis, specifically to a method and apparatus for detecting contract attacks based on symbolic execution and graph neural networks. Background Technology
[0002] Attack contracts are a key component of decentralized finance (DeFi) attacks. Attackers steal assets by exploiting security vulnerabilities in target contracts by writing smart contracts containing attack logic (i.e., attack contracts). Attackers typically encapsulate the complete attack logic within a single attack contract, completing all attack operations within a single transaction by calling the entry function of the attack contract. Attack contracts typically have the following characteristics: few callable functions, numerous external calls, limited event logs, and the need for flash loan callbacks or reentrancy callbacks. There is usually a time window between the deployment of the attack contract and the actual launch of the attack; identifying attack contracts within this window can provide early warnings to potential victims, reducing or avoiding losses.
[0003] Currently, methods for identifying attacked contracts mainly face the following technical challenges:
[0004] 1. Existing metadata-based detection methods have a high false alarm rate.
[0005] Existing rule-based detection methods primarily identify attack contracts by analyzing metadata such as static addresses, function signatures, and event topics. However, this metadata is easily modified or disguised by attackers, leading to unreliable detection results and a high false positive rate. While security companies' monitoring products can issue alerts for most attacks, they generate over 10,000 alerts daily, a large number of which are false positives, requiring manual screening and proving difficult to automate.
[0006] 2. Existing detection methods based on instruction sequences are greatly affected by differences in compilers.
[0007] Another approach directly uses the disassembled opcode sequence as input to the classifier. However, different versions of the Solidity compiler and compilation parameters (such as optimization options and via-IR mode) can significantly affect the generated bytecode. Contracts with the same logic will produce different instruction sequences when compiled using different compilers, leading to inconsistent detection results and limiting the model's generalization ability.
[0008] 3. The attack methods are diverse and difficult to cover comprehensively with rules.
[0009] DeFi attacks exploit a variety of vulnerabilities, including flash loan attacks, reentrancy attacks, price manipulation, and privilege escalation, with significant differences in the behavioral patterns of the attacked contracts. Traditional rule-based methods struggle to enumerate all possible attack patterns, resulting in a high false negative rate.
[0010] 4. Existing methods lack the ability to analyze the on-chain behavior of contract deployers.
[0011] Attackers exhibit significantly different on-chain behavior compared to legitimate contract deployers. For example, attackers typically use newly created, one-off accounts, with funds primarily sourced from mixing services or exchanges requiring no identity verification. Their deployment transaction numbers are extremely low, and they launch attacks very quickly after deployment. Existing methods do not fully utilize these on-chain behavioral characteristics of attackers, thus impacting detection effectiveness. Summary of the Invention
[0012] To address the shortcomings of existing technologies, this invention proposes a contract attack detection method and apparatus based on symbolic execution and graph neural networks. By performing symbolic execution on the bytecode of smart contracts, the control flow and data flow information of the contracts are extracted, and a Contract Invocation Graph (CIG) is constructed. The graph neural network is then used to learn the structural and behavioral characteristics of the contracts, and combined with the on-chain metadata characteristics of the deployer, automatic detection of attacking contracts is achieved.
[0013] The objective of this invention is achieved through the following technical solution:
[0014] A contract attack detection method based on symbolic execution and graph neural networks includes:
[0015] S1: Obtain the bytecode of the smart contract;
[0016] S2: Perform symbolic execution on the bytecode, using a depth-first search strategy to simulate the stack, memory, and storage state of the Ethereum Virtual Machine, traverse all possible execution paths in the smart contract, and record the data propagation path through taint tracing; when external call instructions and log instructions are executed, extract call and event information to generate call chain data;
[0017] S3: Construct an original contract call information graph based on the call chain data, including root nodes, function nodes, call nodes, event nodes, control flow nodes, control flow edges, and data flow edges;
[0018] S4: Perform iterative simplification on the original contract call information graph, removing redundant control flow nodes and edges;
[0019] S5: Encode the features of each node in the simplified contract call information graph, extract the corresponding semantic features according to the node type, and generate a node feature vector; obtain the on-chain metadata of the deployer of the smart contract to be detected, encode the on-chain metadata, and generate a deployer feature vector.
[0020] S6: Construct and train a graph embedding network and a classification network. The input of the graph embedding network is a simplified contract call information graph, node feature vectors, and edge type information, and the output is a graph-level feature vector. The input of the classification network is a joint feature vector obtained by concatenating the graph-level feature vector and the deployer feature vector, and the output is the classification result of whether the smart contract is an attack contract or a normal contract.
[0021] S7: Execute S1~S5 on the smart contract to be tested, and use the trained graph embedding network and classification network to output the classification result of the smart contract to be tested.
[0022] Further, step S2 includes the following sub-steps:
[0023] S2.1: Disassemble the runtime bytecode, convert the runtime bytecode into EVM opcodes and operand sequences; and divide the instruction sequence into multiple basic blocks according to branch instructions and termination instructions. Each basic block is a continuous instruction sequence with a single entry point and a single exit point.
[0024] S2.2: Symbolic execution is performed on the deployed bytecode, extracting the storage write values generated during execution as the initial storage state; starting from the first basic block, a depth-first search strategy is used to traverse all branch paths, simulating the stack, memory, and storage state of the Ethereum Virtual Machine; taint tracking is performed during execution, recording the propagation path of data between the stack, memory, and storage, thereby accurately reconstructing the source of parameters from external calls; if the target basic block has been visited and the values of the first few elements of the stack are the same, and the number of repeated visits exceeds a threshold, the exploration of the current branch is terminated to avoid infinite execution caused by loops; and when a critical instruction is executed, the engine extracts the corresponding information and generates a node.
[0025] S2.3: Group all node information in the execution path according to the function entry point, and summarize all extracted nodes and their predecessor and successor relationships and data dependencies to form call chain data.
[0026] Furthermore, in S1, the deployment bytecode and runtime bytecode of the smart contract are obtained based on the contract address through the remote procedure call interface of the blockchain node or the application programming interface of the blockchain explorer.
[0027] Furthermore, in S1, while obtaining the deployment bytecode and runtime bytecode, the smart contract creation transaction information is also obtained, including the deployer address, the creation transaction sequence number, and the timestamp of the deployment block.
[0028] Furthermore, the node creation process of the original contract call information graph is as follows:
[0029] (1) Create an empty root node as the unique entry point of the entire graph, with node ID 0;
[0030] (2) For each function entry in the call chain data, create a function node; the function node records its corresponding function signature;
[0031] For each external call operation in the call chain data, a call node is created; the call node records its opcode type and the target information associated with that opcode;
[0032] For each log operation in the call chain data, create an event node; the event node records its opcode type.
[0033] In the execution path of a function, control flow nodes are created at the starting point of the basic block and the conditional jump point.
[0034] Furthermore, the edge creation process of the original contract call information graph is as follows:
[0035] Establish control flow edges from the root node to each function node; within the execution path of the same function, establish control flow edges according to the execution order of the nodes;
[0036] When the source of the call parameters of a calling node is determined by taint tracing to be the return data of another calling node, a data flow edge is established from the source calling node to the current calling node; similarly, when the source of the topic parameters of an event node is the return data of a certain calling node, a data flow edge is also established.
[0037] Furthermore, the node feature vector is composed of the following eight feature segments: node type feature segment, function type feature segment, call opcode feature segment, target address type feature segment, signature group feature segment, signature type feature segment, event opcode feature segment, and control opcode feature segment.
[0038] Furthermore, the deployer feature vector is composed of the following three feature segments: funding source feature segment, deployment transaction sequence number feature segment, and time difference feature segment.
[0039] A contract attack detection device based on symbolic execution and graph neural networks, the device comprising:
[0040] The bytecode acquisition unit is used to acquire the deployment bytecode and runtime bytecode of the smart contract, as well as the metadata information of the deployment transaction.
[0041] The symbolic execution unit is used to perform symbolic execution on the runtime bytecode, and uses a depth-first search strategy to simulate the stack, memory and storage state of the Ethereum Virtual Machine, and records the data propagation path through taint tracing; when external call instructions and log instructions are executed, call and event information is extracted to generate call chain data;
[0042] The graph construction unit is used to construct the original contract call information graph based on the call chain data, create root nodes, function nodes, call nodes, event nodes and control flow nodes, and establish control flow edges and data flow edges;
[0043] The graph simplification unit is used to remove redundant control flow nodes and edges through iterative simplification processing to obtain a simplified contract call information graph.
[0044] The feature encoding unit is used to extract the corresponding semantic features of each node in the simplified contract call information graph and generate a node feature vector; at the same time, it obtains the on-chain metadata of the deployer and encodes it to generate a deployer feature vector.
[0045] The classification and detection unit is used to input the simplified contract call information graph, node feature vectors, and edge type information into the graph embedding network based on the pre-trained graph embedding network and classification network. It extracts graph-level feature vectors through the edge-aware message passing mechanism, and then concatenates the graph-level feature vectors with the deployer feature vectors and inputs them into the trained classification network to output the classification result.
[0046] Furthermore, it also includes a model selection unit for managing multiple candidate graph embedding networks trained with multiple different random seeds, providing the graph embedding network with the best attack detection strategy, the best normal recognition strategy, or the fusion strategy.
[0047] The beneficial effects of this invention are as follows:
[0048] 1. This invention extracts the control flow and data flow structure information of a contract through symbolic execution, constructs a contract call information graph, and uses a graph neural network to learn attack patterns from the structural features of the contract. Compared with methods based on static metadata, this invention extracts the inherent execution logic structure of the contract, making it difficult for attackers to change the graph structure without altering the attack logic, thus resulting in a lower false positive rate.
[0049] 2. The symbolic execution of this invention simulates execution at the bytecode level, extracting the execution logic structure of the contract (external calls, events, control flow relationships), rather than the instruction sequence itself. Although different compilers generate different instruction sequences, the execution logic structure of the contract remains unchanged. Therefore, the detection results of this invention are not affected by compiler version and parameters.
[0050] 3. This invention uses graph neural networks for end-to-end training, automatically learning distinguishable features from a large number of call information graphs of attack contracts and normal contracts, without the need for manual definition of detection rules. This method can discover hidden attack behavior patterns and effectively cover a variety of attack types such as flash loan attacks, reentrancy attacks, and price manipulation.
[0051] 4. This invention introduces deployer feature encoding to characterize the on-chain behavior of contract deployers from three dimensions: funding source category, deployment transaction sequence number, and time difference. These features complement the graph structure features and are jointly input into the classification network for end-to-end training, significantly improving detection performance. Attached Figure Description
[0052] Figure 1 This is a flowchart illustrating the contract attack detection method based on symbolic execution and graph neural networks according to an embodiment of the present invention.
[0053] Figure 2 This is a schematic diagram of the symbol execution process in an embodiment of the present invention.
[0054] Figure 3 This is a schematic diagram illustrating the process of constructing and simplifying the contract call information graph in an embodiment of the present invention.
[0055] Figure 4 This is a schematic diagram of the node feature encoding structure in an embodiment of the present invention.
[0056] Figure 5 This is a schematic diagram of the deployer feature encoding structure in an embodiment of the present invention.
[0057] Figure 6 This is a schematic diagram of the graph embedding network and classification network in an embodiment of the present invention.
[0058] Figure 7 This is a schematic diagram of a contract attack detection device based on symbolic execution and graph neural networks according to an embodiment of the present invention. Detailed Implementation
[0059] The present invention will be described in detail below with reference to the accompanying drawings and preferred embodiments. The purpose and effects of the present invention will become clearer. It should be understood that the specific embodiments described herein are merely for explaining the present invention and are not intended to limit the present invention.
[0060] On the one hand, such as Figure 1 As shown, this embodiment of the invention provides a contract attack detection method based on symbolic execution and graph neural networks, including the following steps one through seven.
[0061] Step 1: Obtain the bytecode of the smart contract.
[0062] On Ethereum and other EVM-compatible blockchains, each smart contract contains two bytecode segments upon deployment: creation bytecode and runtime bytecode. The creation bytecode executes once during the contract creation transaction, initializing the contract state and returning the runtime bytecode. The runtime bytecode is the code stored on the blockchain after the contract is deployed; all subsequent calls to the contract execute the runtime bytecode.
[0063] This step uses the remote procedure call (RPC) interface of the blockchain node or the application programming interface (API) of the blockchain explorer to obtain the deployment bytecode and runtime bytecode of the contract based on the contract address. Simultaneously, it obtains the contract's creation transaction information, including the deployer address, the creation transaction nonce, and the timestamp of the deployed block, which will be used for deployer feature encoding in subsequent step five.
[0064] Step 2: Perform symbolic execution on the runtime bytecode, using a depth-first search strategy to simulate the stack, memory, and storage state of the Ethereum Virtual Machine, traverse all possible execution paths in the smart contract, and record the data propagation path through taint tracing; when external call instructions and log instructions are executed, extract the call and event information to generate call chain data.
[0065] This step performs symbolic execution on the obtained runtime bytecode, simulating the EVM's execution environment and extracting the complete execution behavior of the contract. For example... Figure 2 As shown, the symbol execution process includes the following sub-steps:
[0066] S2.1: Disassembly and Basic Block Division:
[0067] The runtime bytecode is disassembled, and the runtime bytecode is converted into EVM opcodes and operand sequences. The instruction sequence is divided into multiple basic blocks (BBs) according to branch instructions (JUMP, JUMPI) and termination instructions (STOP, REVERT, RETURN). Each basic block is a continuous sequence of instructions with a single entry and a single exit.
[0068] In the EVM, an opcode occupies 1 byte, and PUSH1 to PUSH32 instructions are followed by operands of 1 to 32 bytes. After partitioning, the basic block sequence is obtained: BB1, BB2, ..., BB32. n .
[0069] S2.2: Depth-first search execution:
[0070] Symbolic execution is performed on the deployed bytecode, and the storage write values generated during its execution are extracted as the initial storage state. Starting from the first basic block BB1, a depth-first search strategy is used to simulate the execution of runtime bytecode instructions one by one, maintaining the simulated stack, memory, and storage states, and importing the initial storage state into the simulated storage. During the simulated execution, taint tracking is performed to record the propagation path of data between the stack, memory, and storage, thereby accurately reconstructing the source of parameters from external calls. If the target basic block has been accessed and the values of the first few elements of the stack are the same, and the number of repeated accesses exceeds a threshold, the exploration of the current branch is terminated to avoid infinite execution caused by loops. When a critical instruction is executed, the engine extracts the corresponding information and generates a node.
[0071] The execution engine maintains three simulation state stacks, memory state, and storage state as follows:
[0072] Stack: Simulates the operand stack of the EVM, with a maximum depth of 1024. Each stack element, in addition to storing the actual value, also records the instruction instance information that generated that value, used for taint tracking.
[0073] Memory: Byte-addressable memory that simulates the EVM. Each memory region records the instruction instances stored therein and their offset information.
[0074] Storage: Simulates the persistent key-value storage of the EVM. The engine first performs symbolic execution on the deployed bytecode, extracts the storage write values generated during its execution (such as the contract owner address set in the constructor, initial parameters, etc.), and imports them as the initial storage state for runtime bytecode execution.
[0075] During execution, when a branch instruction `JUMP` is encountered, the top element of the stack is read as the jump target address, and execution jumps to the corresponding `JUMPDEST` instruction to continue. When a branch instruction `JUMPI` is encountered, a complete copy of the current execution state (including stack, memory, and stored state) is saved, and the state of the jump path is stored in the unexplored list. Execution continues along the sequential path. When a path is completed, the saved state is retrieved from the unexplored list to continue exploration.
[0076] To avoid infinite execution caused by loops, the engine checks at each jump whether the target basic block has been visited by the current path and whether the first few elements of the stack have the same value. If the number of repeated visits exceeds the threshold (default 100 times), the exploration of the current branch is terminated. At the same time, an execution time limit is set for a single contract (default 10 seconds). After the timeout, execution is terminated and the extracted partial results are returned.
[0077] To enable taint tracking, during simulation execution, the engine appends an instruction instance tag to each piece of data pushed onto the stack, recording the instruction type, location, and associated address information that generated the data. When data participates in arithmetic or logical operations, the result inherits the instruction instance tag of the operand. When data is written to memory via MSTORE or to storage via SSTORE, the corresponding instruction instance information is simultaneously recorded in memory or storage. When data is subsequently read via MLOAD or SLOAD, its instruction instance tag is restored. In this way, the complete propagation path of any data from its generation to its use can be traced.
[0078] Specifically, for external call instructions (such as CALL), their return data can be copied into memory using the RETURNDATACOPY instruction. The engine establishes a mapping from the RETURNDATACOPY operation to the corresponding CALL instruction, allowing subsequent instructions that use the return data to trace back to the original external call.
[0079] When the key instructions shown in Table 1 are executed, the engine extracts the corresponding information and generates nodes. Specifically: when an external call instruction is executed, the engine uses taint marking to reconstruct the source information of the call target address, function signature, and call parameters from the simulation state, and generates a call node; when a log instruction is executed, the engine extracts the event topic information and generates an event node.
[0080] Table 1 Key Instruction List
[0081]
[0082] S2.3: Call chain generation:
[0083] All node information in the execution path is grouped according to the function entry point, and all extracted nodes, their predecessors and successors, and data dependencies are summarized to form call chain data.
[0084] The function entry point is identified as follows: In the bytecode function dispatcher, the EQ instruction compares the first 4 bytes of CALLDATALOAD(0) with the hard-coded function signature to identify each function entry point.
[0085] Furthermore, the engine supports the identification of flash loan callback functions. Common flash loan callbacks in attack contracts include callback functions from various flash loan providers. The engine maintains a database containing over 2,000 known callback signatures. When a signature in the function dispatcher matches a known callback signature, the function entry is marked as a flash loan callback type.
[0086] Step 3: Construct the Raw Contract Information Graph (RCIG) based on the call chain data. The Raw Contract Information Graph includes five types of nodes: root node, function node, call node, event node, and control flow node, as well as two types of edges: control flow edge and data flow edge.
[0087] like Figure 3 As shown, the node construction process of the original contract call information graph is as follows:
[0088] (1) Create an empty root node (ROOT) as the only entry point for the entire graph, with node ID 0.
[0089] (2) For each function entry in the call chain data, create a function node (FUNCTION); the function node records its corresponding function signature. Callable functions are obtained by identifying the signature comparison logic of the function dispatcher in the bytecode.
[0090] For each external call operation in the call chain data, a call node (INVOCATION) is created; the call node records its opcode type (CALL / STATICCALL / DELEGATECALL / CALLCODE / CREATE / CREATE2 / SELFDESTRUCT) and the target information associated with that opcode (such as target address, function signature, creation code or receiving address, etc.).
[0091] For each log operation in the call chain data, create an event node (EVENT); the event node records its opcode type (LOG0 / LOG1 / LOG2 / LOG3 / LOG4).
[0092] In the execution path of a function, control flow nodes (CONTROL) are created for the basic block start point (BB_START) and the conditional jump point (JUMPI).
[0093] The process of creating edges in the original contract call information graph is as follows:
[0094] (1) Control flow edge (CONTROL_FLOW): Establish control flow edges from the root node to each function node; in the execution path of the same function, establish control flow edges according to the execution order of the nodes.
[0095] (2) Data flow edge (DATA_FLOW): When the source of the call parameter of the calling node is determined by taint tracing to be the return data of another calling node, a data flow edge is established from the source calling node to the current calling node; similarly, when the source of the topic parameter of the event node is the return data of a certain calling node, a data flow edge is also established.
[0096] Step 4: Iteratively simplify the original contract call information graph by removing redundant control flow nodes and edges to obtain the simplified contract call information graph.
[0097] Because symbolic execution records a large number of basic block start points and conditional jump points, the original contract call information graph has a huge number of control flow nodes, most of which do not contain critical call or event information. This step simplifies the original contract call information graph to obtain a simplified contract call information graph (CIG).
[0098] like Figure 3 As shown, the following three operations are performed iteratively on the original contract call information graph until the node set and edge set of the graph no longer change after a certain iteration (i.e., a fixed point is reached):
[0099] Rule 1 (Shrinking of Direct Control Flow Nodes): If a control flow node v has an in-degree of 1 and an out-degree of 1, and its unique parent node is u and its unique child node is w, then delete v and the edges (u, v) and (v, w), and add a new edge (u, w); the type of the new edge inherits from the original in-edge (u, v). When u = w (i.e., the operation will create a self-loop), this shrinking operation is not performed.
[0100] Rule 2 (Deletion of Leaf Control Flow Nodes): If the out-degree of a control flow node is 0, then delete the node and all its incoming edges.
[0101] Rule 3 (Removal of Duplicate Edges): For any pair of nodes (u, v) with multiple parallel edges of the same type, only one is retained.
[0102] Execution order and termination: Each iteration follows the order "Rule 1 → Rule 2 → Rule 3", applying the rule to all currently satisfying nodes or edges in the graph once. The iteration terminates when neither the node set nor the edge set has changed after a certain iteration. Since each execution of Rule 1 and Rule 2 reduces at least one node, and each execution of Rule 3 reduces at least one edge, and the graph is finite, the iteration must converge within a finite number of steps.
[0103] The simplified CIG retains the key control flow nodes related to external calls and event logs, while removing a large number of redundant intermediate control flow nodes. The graph size is typically reduced to 10% to 30% of the original graph.
[0104] Step 5: Encode the features of each node in the simplified contract call information graph, extract the corresponding semantic features according to the node type, and generate a node feature vector; obtain the on-chain metadata of the deployer of the smart contract to be detected, encode the on-chain metadata, and generate a deployer feature vector.
[0105] (a) Node feature vectors
[0106] like Figure 4 As shown, the node feature vector is 44-dimensional, composed of 8 feature segments:
[0107] (1) Node type feature segment (6-dimensional, offset 0-5): One-hot encoding is performed on 5 node types and the default unknown category, for a total of 6 categories: UNKNOWN(0), ROOT(1), FUNCTION(2), INVOCATION(3), EVENT(4), CONTROL(5). Among them, UNKNOWN is the default category for encoding, and the nodes in the actual graph are the latter 5 types.
[0108] (2) Function type feature segment (3D, offset 6-8): Only valid for function nodes. The function category is determined by matching the function signature with a known flash loan callback signature library (containing callback function signatures of 7 flash loan providers) and a suspicious function signature library. The matching results are encoded into 3 categories: no match (0), normal function (1), flash loan callback or suspicious function (2), using one-hot encoding.
[0109] (3) Call opcode feature segment (7-dimensional, offset 9-15): Valid only for the calling node. One-hot encoding is performed on 7 types of call opcodes: CALL, STATICCALL, DELEGATECALL, CALLCODE, CREATE, CREATE2, and SELFDESTRUCT. Different opcode types reflect different ways the contract interacts with the outside world.
[0110] (4) Target Address Type Feature Segment (5-dimensional, offset 16-20): Valid only for the calling node. The category of the target contract is determined by matching the target address with a known contract address database. Known contract categories include: asset contracts (such as ERC-20 standard contracts), decentralized exchange contracts, lending contracts, and other categories. Encoded into 5 categories using one-hot encoding.
[0111] (5) Signature group feature segment (2D, offset 21-22): Only valid for the calling node. The signature is divided into two categories: common attack entry points and ordinary functions, and one-hot encoding is used.
[0112] (6) Signature Type Feature Segment (13-dimensional, offset 23-35): Valid only for the calling node. The corresponding DeFi operation type is identified through database matching of function signatures. The Ethereum signature database contains approximately 1.3 million function signatures, of which approximately 60,000 cover common DeFi operations such as deposits, withdrawals, exchanges, and transfers. Signature types include 13 categories. Since a function signature may correspond to multiple operation types, multi-hot encoding is used, resulting in a 13-dimensional signature.
[0113] (7) Event opcode feature segment (5-dimensional, offset 36-40): Only valid for event nodes. One-hot encoding is performed on the 5 log opcodes: LOG0, LOG1, LOG2, LOG3, and LOG4.
[0114] (8) Control opcode feature segment (3D, offset 41-43): Only valid for control flow nodes. One-hot encoding is performed for 3 control flow types: LOOP_ENTRY (loop entry), BB_START (basic block start), and JUMPI (conditional jump).
[0115] For each node, only the feature segments of its corresponding type contain valid values, and the remaining feature segments are filled with zeros.
[0116] (ii) Deployer Feature Vector
[0117] The on-chain behavior of attackers differs significantly from that of normal contract deployers. This step obtains the deployer's on-chain metadata, encoded as a 46-dimensional deployer feature vector. For example... Figure 5 As shown, the deployer feature vector is composed of three feature segments:
[0118] (1) Funds Source Feature Segment (8-dimensional, offset 0-7): Track the first incoming transaction of the deployer's account, match the sender address with the known address tag library, and determine the fund source category. The definitions of the 8 categories are shown in Table 2.
[0119] Table 2. List of Funding Sources
[0120]
[0121] The funding source uses one-hot encoding with 8 dimensions.
[0122] (2) Deployment Transaction Nonce Feature Segment (13-dimensional, offset 8-20): The nonce of the deployment transaction reflects the trading activity level of the deployer's account before deployment. Attackers typically use newly created one-time accounts to deploy attack contracts, resulting in extremely low deployment transaction nonces (usually 0-5). Non-uniform binning encoding is used.
[0123] Binning intervals: [0,1), [1,2), [2,3), [3,4), [4,5), [5,6), [6,10), [10,15), [15,20), [20,50), [50,75), [75,100), [100,+∞)
[0124] In this system, each value from 0 to 5 occupies a unique interval to precisely distinguish the attacker's low-order features. One-hot encoding is used, with a dimension of 13.
[0125] (3) Time Difference Feature Segment (25-dimensional, offset 21-45): The time difference is defined as the timestamp of the contract deployment block minus the timestamp of the deployer's first transaction block, reflecting the lifespan of the deployer's account. The time difference is converted into hours and binned hourly from 0 to 24 hours, with those exceeding 24 hours placed in the last interval. One-hot encoding is used, with a dimension of 25.
[0126] Step Six: Construct and train a graph embedding network and a classification network. The input to the graph embedding network is a simplified contract call information graph, node feature vectors, and edge type information, and the output is a graph-level feature vector. The input to the classification network is a joint feature vector obtained by concatenating the graph-level feature vector and the deployer feature vector, and the output is the classification result of whether the smart contract is an attack contract or a normal contract.
[0127] like Figure 6 As shown, the simplified contract call information graph, node feature vectors, and edge type information are input into the trained graph embedding network. The embedding vectors of each node are iteratively updated through a message passing mechanism to extract graph-level feature vectors. The graph-level feature vectors are then concatenated with the deployer feature vectors and input into the trained classification network to output the classification result of whether the smart contract to be detected is an attack contract or a normal contract.
[0128] Since the original contract call information graph is a directed graph, the root node, as the entrance to the graph, only sends edges to its child nodes and does not receive edges from its child nodes. To enable the root node to receive information from all successor nodes through message passing, all directed edges in the simplified contract call information graph are converted into bidirectional edges. That is, an additional reverse edge (v, u) is added to each edge (u, v), while the edge type remains unchanged.
[0129] The graph embedding network of this invention can adopt a Structure2Vec (S2V) network architecture, a Graph Isomorphism Network (GIN), a Graph Attention Network (GAT), or a GraphSAGE network. Of these four architectures...
[0130] The Structure2Vec network architecture distinguishes between control flow edges and data flow edges by using edge features to participate in message passing.
[0131] Graph Isomorphic Network (GIN): It uses a multilayer perceptron to aggregate neighbor features, and ignores edge type information through batch normalization and ReLU activation.
[0132] Graph Attention Network (GAT): Employs a multi-head attention mechanism to assign different weights to different neighbors, and adaptively aggregates neighbor information through attention coefficients.
[0133] GraphSAGE network: It adopts a sampling and aggregation strategy, which aggregates the neighbor's average and then concatenates it with its own features.
[0134] The following section uses the Structure2Vec network architecture as an example to introduce the message passing mechanism and graph-level feature extraction.
[0135] Graph embedding networks are edge-aware message-passing networks. Let the graph G = (V,E), and the initial feature vector of node i be... The edge type of edge (i,j) is obtained by one-hot encoding to obtain the edge feature vector. (The 3D shape corresponds to three edge types: control flow edge, data flow edge, and default type). The embedding vector μ of node i. i Initialized as a zero vector, and updated after T iterations:
[0136]
[0137] Where, μ i (t) Let be the embedding vector of node i after the t-th iteration; N(i) is the set of neighboring nodes of node i; e ij The edge feature vector is obtained by one-hot encoding of the edge (i,j). The edge types include three types: control flow edge, data flow edge, and default type; x i Let be the initial feature vector of node i. Weight matrix for neighbor embedding aggregation; This is the weight matrix for the edge feature mapping; d is the weight matrix of its own feature mapping; d is the dimension of the embedding vector, which defaults to 64; σ is the ReLU non-linear activation function; T is the number of message passing iterations, which defaults to 5.
[0138] Each iteration uses an independent weight matrix, resulting in a total of 3T sets of learnable parameters.
[0139] The initial embedding vector is set to zero. The hierarchical structure of CIG ensures that the root node has aggregated information from all successor nodes after T message passes. Therefore, the embedding vector μ0 of the root node is used directly. ⁽ᵀ⁾ As a feature representation of the entire graph This method of reading the root node is superior to mean pooling because:
[0140] (1) CIG is composed of heterogeneous nodes, and mean pooling will dilute key information;
[0141] (2) The root node is an artificially inserted entry point of the graph, which is naturally suitable as a representative of the whole graph.
[0142] While the Graph Isomorphic Network (GIN), Graph Attention Network (GAT), and GraphSAGE network architectures do not use edge type information, they can still learn effective attack patterns from the graph's topology and node characteristics. Users can choose the appropriate architecture based on their specific needs.
[0143] The classification network is a multi-layer fully connected network that jointly uses feature vectors. The input classification network is represented as:
[0144]
[0145] When the classification network is a three-layer fully connected network, its structure is shown in Table 3:
[0146] Table 3. Structure of the classification network
[0147]
[0148] The two nodes in the output layer correspond to the probabilities of normal contracts (category 0) and attack contracts (category 1), respectively. The category with the higher probability is taken as the final classification result. The dropout rate is 0.3 by default.
[0149] The graph embedding network and classification network are trained end-to-end using the cross-entropy loss function.
[0150]
[0151] Where θ represents all learnable parameters, and G i For the contract call information graph of the i-th training sample, R D,i For its deployer feature vector, y i For real labels, M G For graph embedding networks, M C For classification networks.
[0152] Since the number of normal contracts in the training data far exceeds the number of attack contracts, a class-weighted cross-entropy loss function can be used, assigning higher loss weights to the attack class. The Adam optimizer is used with a learning rate of 0.001 and a weight decay of 0.0001, trained for 300 epochs.
[0153] It should be noted that the graph embedding network and classification network of the device described in this invention can be pre-trained offline outside the device. After training is completed, the network parameters are loaded into the device and called by the classification and detection unit. Those skilled in the art can choose to integrate the training process into the device or deploy it on a separate training server according to actual deployment needs.
[0154] Step 7: Perform steps 1 to 5 on the smart contract to be tested, and use the trained graph embedding network and classification network to output the classification result of the smart contract.
[0155] On the other hand, embodiments of the present invention also provide a contract attack detection device based on symbolic execution and graph neural networks, such as... Figure 7 As shown, it includes:
[0156] The bytecode acquisition unit is used to acquire the deployment bytecode and runtime bytecode of the smart contract, as well as the metadata information of the deployment transaction.
[0157] The symbolic execution unit is used to perform symbolic execution on runtime bytecode. It uses a depth-first search strategy to simulate the stack, memory, and storage state of the Ethereum Virtual Machine and records the data propagation path through taint tracing. When external call instructions and log instructions are executed, call and event information is extracted to generate call chain data.
[0158] The graph construction unit is used to construct the original contract call information graph based on the call chain data, create root nodes, function nodes, call nodes, event nodes and control flow nodes, and establish control flow edges and data flow edges.
[0159] The graph simplification unit is used to remove redundant control flow nodes and edges through iterative simplification processing, resulting in a simplified contract call information graph.
[0160] The feature encoding unit is used to extract the corresponding semantic features of each node in the simplified contract call information graph and generate a node feature vector; at the same time, it obtains the on-chain metadata of the deployer and encodes it to generate a deployer feature vector.
[0161] The classification and detection unit is used to input the simplified contract call information graph, node feature vectors, and edge type information into the graph embedding network. It extracts graph-level feature vectors through an edge-aware message passing mechanism, and then concatenates the graph-level feature vectors with the deployer feature vectors before inputting them into the classification network to output the classification results.
[0162] The model selection unit manages multiple candidate graph embedding networks trained with multiple different random seeds, providing a graph embedding network that satisfies the optimal attack detection strategy, the optimal normal recognition strategy, or the fusion strategy.
[0163] (1) Best Attack Detection Strategy (BESTATTACK): Select the candidate model with the highest accuracy on the attack contract test set. Suitable for scenarios that require maximizing attack detection coverage.
[0164] (2) Best Normal Recognition Strategy: Select the candidate model with the lowest false positive rate on a large-scale contract dataset. Suitable for scenarios where it is necessary to minimize false positives.
[0165] (3) Merged Strategy: The prediction results of all candidate models are aggregated, and an attack flag is only output when all models identify the target contract as an attack contract. This voting mechanism significantly reduces the false positive rate and is suitable for scenarios that are extremely sensitive to false positives.
[0166] To verify the beneficial effects of the contract attack detection method and apparatus based on symbolic execution and graph neural networks of the present invention, the following three sets of experiments were designed.
[0167] Dataset: 918 attack contracts were collected from a publicly available DeFi attack event database, and 10,451 normal contracts were collected from sources such as high-frequency on-chain call contracts and contracts from various project categories, covering contracts on multiple EVM-compatible blockchains from 2020 to 2026. The symbolic execution and graph construction process of this invention was executed on all 11,369 contracts, of which 9,245 successfully completed all processing steps and generated valid contract call information graphs (845 attack contracts and 8,400 normal contracts). These were then stratified and divided into a training set (7,396 contracts, including 676 attack contracts) and a test set (1,849 contracts, including 169 attack contracts) at an 80:20 ratio, ensuring that the ratio of attack contracts to normal contracts was consistent between the training and test sets.
[0168] Experiment 1: Comparison Experiment of Different Graph Neural Network Architectures
[0169] This experiment verifies the universality of the graph construction and feature encoding framework of this invention for different graph neural network architectures.
[0170] Experimental setup: Four graph neural network architectures (S2V, GIN, GAT, GraphSAGE) were trained separately. For each architecture, 55 models were independently trained using 55 different random seeds, with each model trained for 300 epochs. The hidden dimension d=64, message passing iterations T=5, batch size 64, and dropout rate 0.3.
[0171] Evaluation metrics: The “Average TPR” and “Average FPR” in the table are the mean values of 55 independent models, reflecting the stability of the method under different random initialization conditions; the “Best Overall Score” (Score = TPR - 2×FPR) shows the upper limit of performance that a single model can achieve.
[0172] The experimental results are shown in Table 4.
[0173] Table 4 Evaluation metrics results for four graph neural network architectures
[0174]
[0175] As shown in Table 4, all four graph neural network architectures can effectively identify attack contracts within the framework of this invention, with average false positive rates all below 2%, verifying the universality of the graph construction and feature encoding methods of this invention for different graph neural network architectures. Among them, GAT achieved the lowest average false positive rate (0.83%) and the highest overall score (0.659), indicating that the attention mechanism helps to adaptively aggregate information from different neighboring nodes, reducing false positives. GIN achieved the highest single-model attack detection rate (71.01%), suitable for scenarios prioritizing detection coverage. Different architectures are suitable for different downstream application needs.
[0176] Experiment 2: Ablation Experiment
[0177] This experiment verifies the contribution of the deployer feature encoding module to the detection performance by removing the deployer feature.
[0178] Experimental setup: Using the same dataset and evaluation method as Experiment 1, we selected the S2V and GIN architectures, training in two configurations: the complete model (including deployer features) and the configuration with deployer features removed (using only graph structure and node features). Each configuration was trained independently using 55 random seeds, and the remaining hyperparameters were consistent with Experiment 1.
[0179] The experimental results are shown in Table 5.
[0180] Table 5. Evaluation metrics for S2V and GIN architectures under conditions including and without deployer characteristics.
[0181]
[0182] As shown in Table 5, after removing the deployer features, the average true positive rate of S2V decreased from 64.39% to 54.6% (a decrease of 9.8 percentage points), and the average true positive rate of GIN decreased from 66.00% to 58.3% (a decrease of 7.7 percentage points). The best overall scores decreased by 0.036 and 0.064, respectively. Both architectures showed a consistent performance decline trend, verifying that the deployer features (funding source, transaction sequence number, time difference) provide important supplementary information for identifying attack contracts and are complementary to graph structure features. Furthermore, while the deployer features significantly improved the true positive rate, the impact on the false positive rate varied depending on the architecture, indicating that the main contribution of the deployer features is to enhance the ability to identify attack contracts.
[0183] Experiment 3: Compiler Robustness Experiment
[0184] This experiment verifies that the present invention is unaffected by differences in compiler versions.
[0185] Experimental setup: Solidity source code (PoC) containing 270 attack events was collected and compiled using 43 Solidity compiler versions (0.6.0 to 0.8.22). Each version employed various optimization settings (no optimization, 200 optimization rounds, 1000 optimization rounds, etc.), resulting in hundreds of different compilation results for each PoC. The complete detection process of this invention (symbolic execution → graph construction → feature encoding → model inference) was executed on each compilation result, and the detection consistency of different compilation results was compared.
[0186] Experimental Results: In 270 Proof-of-Concept (PoC) tests, over 265 contracts (more than 98%) maintained completely consistent test results across all compiled variants. Even when the same contract was compiled using different compiler versions and optimization parameters, although the generated bytecode differed (instruction count and arrangement varied), the contract call information graph extracted through symbolic execution remained structurally consistent—the target address of external calls, function signatures, and data flow relationships did not change with the compiler version. A very small number of inconsistencies arose from bytecode differences generated by individual compiler versions, leading to slight variations in the path coverage of the symbolic execution engine; these did not affect the overall conclusions.
[0187] Results Analysis: This verifies the effectiveness of the technical approach of this invention, which is based on the execution logic structure (rather than the instruction sequence) for detection. Since symbolic execution extracts the external call behavior and event information of the contract, rather than the instruction sequence itself, differences in compiler version and optimization parameters do not affect the detection results, thus solving the technical problem of existing instruction sequence-based methods being affected by compiler differences.
[0188] It will be understood by those skilled in the art that the above descriptions are merely preferred examples of the invention and are not intended to limit the invention. Although the invention has been described in detail with reference to the foregoing examples, those skilled in the art can still modify the technical solutions described in the foregoing examples or make equivalent substitutions for some of the technical features. All modifications and equivalent substitutions made within the spirit and principles of the invention should be included within the scope of protection of the invention.
Claims
1. A contract attack detection method based on symbolic execution and graph neural networks, characterized in that, include: S1: Obtain the bytecode of the smart contract; S2: Perform symbolic execution on the bytecode, using a depth-first search strategy to simulate the stack, memory, and storage state of the Ethereum Virtual Machine, traverse all possible execution paths in the smart contract, and record the data propagation path through taint tracing; when external call instructions and log instructions are executed, extract call and event information to generate call chain data; S3: Construct an original contract call information graph based on the call chain data, including root nodes, function nodes, call nodes, event nodes, control flow nodes, control flow edges, and data flow edges; S4: Perform iterative simplification on the original contract call information graph, removing redundant control flow nodes and edges; S5: Encode the features of each node in the simplified contract call information graph, extract the corresponding semantic features according to the node type, and generate a node feature vector; obtain the on-chain metadata of the deployer of the smart contract to be detected, encode the on-chain metadata, and generate a deployer feature vector. S6: Construct and train a graph embedding network and a classification network. The input of the graph embedding network is a simplified contract call information graph, node feature vectors, and edge type information, and the output is a graph-level feature vector. The input of the classification network is a joint feature vector obtained by concatenating the graph-level feature vector and the deployer feature vector, and the output is the classification result of whether the smart contract is an attack contract or a normal contract. S7: Execute S1~S5 on the smart contract to be tested, and use the trained graph embedding network and classification network to output the classification result of the smart contract to be tested.
2. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, S2 includes the following sub-steps: S2.1: Disassemble the runtime bytecode, convert the runtime bytecode into EVM opcodes and operand sequences; and divide the instruction sequence into multiple basic blocks according to branch instructions and termination instructions. Each basic block is a continuous instruction sequence with a single entry point and a single exit point. S2.2: Perform symbolic execution on the deployed bytecode and extract the storage write values generated during its execution as the initial storage state; Starting from the first basic block, a depth-first search strategy is used to traverse all branch paths, simulating the stack, memory, and storage state of the Ethereum Virtual Machine; During execution, taint tracking is performed to record the propagation path of data between the stack, memory, and storage, thereby accurately reconstructing the source of parameters from external calls; If the target basic block has been visited and the values of the first few elements of the stack are the same, and the number of repeated visits exceeds the threshold, the exploration of the current branch will be terminated to avoid infinite execution caused by loops; and when a key instruction is executed, the engine extracts the corresponding information and generates a node. S2.3: Group all node information in the execution path according to the function entry point, and summarize all extracted nodes and their predecessor and successor relationships and data dependencies to form call chain data.
3. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, In S1, the deployment bytecode and runtime bytecode of the smart contract are obtained based on the contract address through the remote procedure call interface of the blockchain node or the application programming interface of the blockchain explorer.
4. The contract attack detection method based on symbolic execution and graph neural networks according to claim 3, characterized in that, In S1, while obtaining the deployment bytecode and runtime bytecode, the smart contract creation transaction information is also obtained, including the deployer address, creation transaction sequence number, and deployment block timestamp.
5. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, The node creation process of the original contract call information graph is as follows: (1) Create an empty root node as the unique entry point of the entire graph, with node ID 0; (2) For each function entry in the call chain data, create a function node; the function node records its corresponding function signature; For each external call operation in the call chain data, create a call node; The calling node records its opcode type and the target information associated with that opcode; For each log operation in the call chain data, create an event node; Event nodes record their opcode types; In the execution path of a function, control flow nodes are created at the starting point of the basic block and the conditional jump point.
6. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, The edge creation process of the original contract call information graph is as follows: Establish control flow edges from the root node to each function node; within the execution path of the same function, establish control flow edges according to the execution order of the nodes; When the source of the call parameters of a calling node is determined by taint tracing to be the return data of another calling node, a data flow edge is established from the source calling node to the current calling node; similarly, when the source of the topic parameters of an event node is the return data of a certain calling node, a data flow edge is also established.
7. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, The node feature vector is composed of the following eight feature segments: node type feature segment, function type feature segment, call opcode feature segment, target address type feature segment, signature group feature segment, signature type feature segment, event opcode feature segment, and control opcode feature segment.
8. The contract attack detection method based on symbolic execution and graph neural networks according to claim 1, characterized in that, The deployer feature vector is composed of the following three feature segments: funding source feature segment, deployment transaction sequence feature segment, and time difference feature segment.
9. A contract attack detection device based on symbolic execution and graph neural networks, characterized in that, The device includes: The bytecode acquisition unit is used to acquire the deployment bytecode and runtime bytecode of the smart contract, as well as the metadata information of the deployment transaction. The symbolic execution unit is used to perform symbolic execution on the runtime bytecode, and uses a depth-first search strategy to simulate the stack, memory and storage state of the Ethereum Virtual Machine, and records the data propagation path through taint tracing; when external call instructions and log instructions are executed, call and event information is extracted to generate call chain data; The graph construction unit is used to construct the original contract call information graph based on the call chain data, create root nodes, function nodes, call nodes, event nodes and control flow nodes, and establish control flow edges and data flow edges; The graph simplification unit is used to remove redundant control flow nodes and edges through iterative simplification processing to obtain a simplified contract call information graph. The feature encoding unit is used to extract the corresponding semantic features of each node in the simplified contract call information graph and generate a node feature vector; at the same time, it obtains the on-chain metadata of the deployer and encodes it to generate a deployer feature vector. The classification and detection unit is used to input the simplified contract call information graph, node feature vectors, and edge type information into the graph embedding network based on the pre-trained graph embedding network and classification network. It extracts graph-level feature vectors through the edge-aware message passing mechanism, and then concatenates the graph-level feature vectors with the deployer feature vectors and inputs them into the trained classification network to output the classification result.
10. The contract attack detection device based on symbolic execution and graph neural networks according to claim 9, characterized in that, It also includes a model selection unit for managing multiple candidate graph embedding networks trained with multiple different random seeds, providing the graph embedding network with the best attack detection strategy, the best normal recognition strategy, or the fusion strategy.