A Smart Contract Vulnerability Detection Method Based on Hierarchical Multi-Granularity Coding
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-15
- Publication Date
- 2026-08-11
AI Technical Summary
[0005]本公开的实施例提供了一种基于分层多粒度编码的智能合约漏洞检测方法、装置及存储介质,以至少解决现有技术中存在的通过深度学习方法对智能合约进行处理,结构性理解不足、关键局部特征淹没和长距离依赖建模困难等的技术问题
[0010] In this embodiment, the source code of the smart contract is first divided into multiple levels to determine input data with a three-layer structure: code segment level, statement block level, and token level. The statement blocks are divided according to code semantic logic, which is more suitable for smart contract vulnerability detection scenarios. The vulnerability detection model performs feature extraction and feature fusion based on the three-layer input data, capturing detailed information at the token level, code semantic information at the statement block level, and information at the code segment level. It fuses token and statement block information within a segment using intra-segment features, obtains mutual information between code segments using cross-segment features, and determines document-level features by combining intra-segment and cross-segment features. Then, based on intra-segment, cross-segment, and document-level features, vulnerability detection is performed on the smart contract to be detected. Therefore, this embodiment not only divides the code features into a unique hierarchical structure to facilitate feature extraction by the vulnerability detection model, but also obtains the interaction and dependency relationships between tokens, statement blocks, and code segments through feature extraction and feature fusion, thereby improving the accuracy of smart contract vulnerability detection using deep learning models.
Smart Images

Figure CN121706106B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of blockchain and smart contract vulnerability detection technology, and in particular to a smart contract vulnerability detection method based on hierarchical multi-granularity coding. Background Technology
[0002] With the development of blockchain technology, smart contracts, as a core component, are widely used in decentralized finance, NFTs, on-chain governance, and other scenarios. However, once deployed, smart contracts cannot be altered, and vulnerabilities can lead to significant economic losses. Therefore, security testing of smart contracts has become a current research hotspot. Traditional vulnerability detection methods, including symbolic execution, fuzzing, and formal verification, generally suffer from low efficiency, high false positive rates, and poor scalability.
[0003] In recent years, deep learning has been increasingly adopted for smart contract vulnerability detection. Compared to traditional methods, deep learning-based approaches can automatically learn complex vulnerability patterns from smart contract data, adapt to constantly evolving attack methods, reduce reliance on expert knowledge, and demonstrate significant advantages in improving detection accuracy, automation, and handling complex contracts. However, current deep learning methods still suffer from problems such as insufficient structural understanding, obscuring key local features, and difficulty in modeling long-distance dependencies. Traditional language models often treat code as a flat sequence, ignoring its hierarchical structure and semantic information. Furthermore, cross-statement dependencies in long contracts are difficult to capture, and truncation often results in the loss of important vulnerability features.
[0004] There are currently no effective solutions to the technical problems existing in the current technology of processing smart contracts using deep learning methods, such as insufficient structural understanding, obscuring of key local features, and difficulty in modeling long-distance dependencies. Summary of the Invention
[0005] The embodiments of this disclosure provide a method, apparatus, and storage medium for detecting smart contract vulnerabilities based on hierarchical multi-granularity coding, which at least solves the technical problems existing in the prior art, such as insufficient structural understanding, overwhelming of key local features, and difficulty in modeling long-distance dependencies when processing smart contracts using deep learning methods.
[0006] According to one aspect of the present disclosure, a smart contract vulnerability detection method based on hierarchical multi-granularity coding is provided, comprising: acquiring the source code of a smart contract to be detected; dividing the source code into multiple code segments using a sliding window method, and dividing each of the multiple code segments into multiple statement blocks based on code semantic logic to obtain input data, wherein each statement block includes several basic code unit tokens; based on the input data, performing feature extraction on the source code through a feature extraction layer in a vulnerability detection model to determine token features corresponding to each token, statement block features corresponding to each statement block, and cross-statement block features corresponding to each code segment; through a feature fusion layer in the vulnerability detection model, determining intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block, determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment, and determining document-level features based on intra-segment features and cross-segment features; and determining a vulnerability detection result based on intra-segment features, cross-segment features, and document-level features using the vulnerability detection model.
[0007] According to another aspect of the present disclosure, a storage medium is also provided, the storage medium including a stored program, wherein, when the program is executed, a processor performs any of the methods described above.
[0008] According to another aspect of the present disclosure, a smart contract vulnerability detection device based on hierarchical multi-granularity coding is also provided, comprising: an acquisition module for acquiring the source code of a smart contract to be detected; a segmentation module for dividing the source code into multiple code segments using a sliding window, and dividing each of the multiple code segments into multiple statement blocks based on code semantic logic to obtain input data, wherein the statement blocks include several basic code units token; a feature extraction module for extracting features from the source code based on the input data using a feature extraction layer in a vulnerability detection model, determining token features corresponding to each token, statement block features corresponding to each statement block, and cross-statement block features corresponding to each code segment; a feature fusion module for determining intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block, and determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment, and determining document-level features based on intra-segment features and cross-segment features; and a vulnerability detection module for determining vulnerability detection results based on intra-segment features, cross-segment features, and document-level features using a vulnerability detection model.
[0009] According to another aspect of the present disclosure, a smart contract vulnerability detection device based on hierarchical multi-granularity coding is also provided, comprising: a processor; and a memory connected to the processor, configured to provide the processor with instructions for processing the following steps: acquiring the source code of the smart contract to be detected; dividing the source code into multiple code segments using a sliding window, and dividing each of the multiple code segments into multiple statement blocks based on code semantic logic to obtain input data, wherein each statement block includes several basic code unit tokens; based on the input data, performing feature extraction on the source code through a feature extraction layer in a vulnerability detection model to determine token features corresponding to each token, statement block features corresponding to each statement block, and cross-statement block features corresponding to each code segment; through a feature fusion layer in a vulnerability detection model, determining intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block, determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment, and determining document-level features based on intra-segment features and cross-segment features; and determining vulnerability detection results based on intra-segment features, cross-segment features, and document-level features through a vulnerability detection model.
[0010] In this embodiment, the source code of the smart contract is first divided into multiple levels to determine input data with a three-layer structure: code segment level, statement block level, and token level. The statement blocks are divided according to code semantic logic, which is more suitable for smart contract vulnerability detection scenarios. The vulnerability detection model performs feature extraction and feature fusion based on the three-layer input data, capturing detailed information at the token level, code semantic information at the statement block level, and information at the code segment level. It fuses token and statement block information within a segment using intra-segment features, obtains mutual information between code segments using cross-segment features, and determines document-level features by combining intra-segment and cross-segment features. Then, based on intra-segment, cross-segment, and document-level features, vulnerability detection is performed on the smart contract to be detected. Therefore, this embodiment not only divides the code features into a unique hierarchical structure to facilitate feature extraction by the vulnerability detection model, but also obtains the interaction and dependency relationships between tokens, statement blocks, and code segments through feature extraction and feature fusion, thereby improving the accuracy of smart contract vulnerability detection using deep learning models. Attached Figure Description
[0011] The accompanying drawings, which are included to provide a further understanding of this disclosure and form part of this application, illustrate exemplary embodiments of this disclosure and are used to explain this disclosure, but do not constitute an undue limitation of this disclosure. In the drawings: Figure 1This is a hardware structure block diagram of a computing device for implementing the method described in Embodiment 1 of this disclosure; Figure 2 This is a flowchart illustrating the smart contract vulnerability detection method based on hierarchical multi-granularity coding according to the first aspect of Embodiment 1 of this disclosure; Figure 3 This is a schematic diagram illustrating the relationship between a statement block and a code segment according to Embodiment 1 of this disclosure; Figure 4A This is a schematic diagram of feature extraction and feature fusion in a vulnerability detection model provided according to Embodiment 1 of this disclosure; Figure 4B This is a schematic diagram of vulnerability detection in a vulnerability detection model provided according to Embodiment 1 of this disclosure; Figure 5A This is a schematic diagram of an obfuscation matrix corresponding to a reentrancy vulnerability, provided according to Embodiment 1 of this disclosure; Figure 5B This is a schematic diagram of a confusion matrix corresponding to an arithmetic vulnerability, provided according to Embodiment 1 of this disclosure; Figure 5C This is a schematic diagram of an obfuscation matrix corresponding to an access control vulnerability, provided according to Embodiment 1 of this disclosure; Figure 5D This is a schematic diagram of an obfuscation matrix corresponding to an unchecked low-level call vulnerability, provided according to Embodiment 1 of this disclosure; Figure 5E This is a schematic diagram of a confusion matrix corresponding to a security contract provided in Embodiment 1 of this disclosure; Figure 6 This is a schematic diagram of a smart contract vulnerability detection device based on hierarchical multi-granularity coding according to the first aspect of Embodiment 2 of this disclosure; and Figure 7 This is a schematic diagram of a smart contract vulnerability detection device based on hierarchical multi-granularity coding, according to the first aspect of Embodiment 3 of this disclosure. Detailed Implementation
[0012] To enable those skilled in the art to better understand the technical solutions of this disclosure, the technical solutions of the embodiments of this disclosure will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are merely some embodiments of this disclosure, and not all embodiments. Based on the embodiments of this disclosure, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this disclosure.
[0013] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this disclosure are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of this disclosure described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0014] Example 1 According to this embodiment, a method embodiment of a smart contract vulnerability detection method based on hierarchical multi-granularity coding is provided. It should be noted that the steps shown in the flowchart in the accompanying drawings can be executed in a computer system such as a set of computer-executable instructions. Although a logical order is shown in the flowchart, in some cases, the steps shown or described may be executed in a different order than that shown here.
[0015] The method embodiments provided in this example can be executed on mobile terminals, computer terminals, servers, or similar computing devices. Figure 1 A hardware structure block diagram of a computing device for implementing a smart contract vulnerability detection method based on hierarchical multi-granularity coding is shown. Figure 1 As shown, a computing device may include one or more processors (processors may include, but are not limited to, microprocessors such as MCUs or programmable logic devices such as FPGAs), a memory for storing data, a transmission device for communication functions, and an input / output interface. The memory, transmission device, and input / output interface are connected to the processor via a bus. In addition, it may also include a display, keyboard, and cursor control device connected to the input / output interface. Those skilled in the art will understand that... Figure 1 The structure shown is for illustrative purposes only and does not limit the structure of the aforementioned electronic device. For example, a computing device may also include... Figure 1 The more or fewer components shown, or having the same Figure 1 The different configurations shown.
[0016] It should be noted that the aforementioned one or more processors and / or other data processing circuits are generally referred to herein as "data processing circuits". These data processing circuits may be embodied, in whole or in part, in software, hardware, firmware, or any other combination thereof. Furthermore, the data processing circuits may be a single, independent processing module, or may be integrated, in whole or in part, into any other element in a computing device. As involved in the embodiments of this disclosure, the data processing circuits serve as processor control (e.g., selection of a variable resistor termination path connected to an interface).
[0017] The memory can be used to store software programs and modules of application software, such as the program instructions / data storage device corresponding to the hierarchical multi-granularity coding-based smart contract vulnerability detection method in this embodiment of the present disclosure. The processor executes various functional applications and data processing by running the software programs and modules stored in the memory, thereby implementing the aforementioned hierarchical multi-granularity coding-based smart contract vulnerability detection method for the application. The memory may include high-speed random access memory, and may also include non-volatile memory, such as one or more magnetic storage devices, flash memory, or other non-volatile solid-state memory. In some instances, the memory may further include memory remotely located relative to the processor, and these remote memories can be connected to the computing device via a network. Examples of such networks include, but are not limited to, the Internet, corporate intranets, local area networks, mobile communication networks, and combinations thereof.
[0018] The transmission device is used to receive or send data via a network. Specific examples of the network described above may include a wireless network provided by the computing device's communication provider. In one example, the transmission device includes a Network Interface Controller (NIC), which can connect to other network devices via a base station to communicate with the Internet. In another example, the transmission device may be a Radio Frequency (RF) module used for wireless communication with the Internet.
[0019] The display can be, for example, a touchscreen liquid crystal display (LCD), which allows users to interact with the user interface of the computing device.
[0020] It should be noted here that, in some optional embodiments, the above... Figure 1 The computing device shown may include hardware elements (including circuitry), software elements (including computer code stored on a computer-readable medium), or a combination of both hardware and software elements. It should be noted that... Figure 1 This is only one instance of a specific particular instance, and is intended to illustrate the types of components that may exist in the aforementioned computing devices.
[0021] Under the aforementioned operating environment, according to the first aspect of this embodiment, a smart contract vulnerability detection method based on hierarchical multi-granularity coding is provided. This method can be... Figure 1 The computing device implementation is shown. Figure 2 A flowchart illustrating the method is shown below. (Refer to...) Figure 2 As shown, the method includes: S202: Obtain the source code of the smart contract to be tested; S204: Divide the source code into multiple code segments by using a sliding window, and based on the semantic logic of the code, divide each of the multiple code segments into multiple statement blocks to obtain input data. The statement blocks include several basic code unit tokens. S206: Based on the input data, the feature extraction layer in the vulnerability detection model is used to extract features from the source code to determine the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. S208: Through the feature fusion layer in the vulnerability detection model, based on the token features corresponding to each token and the statement block features corresponding to each statement block, determine the intra-segment features corresponding to each code segment; based on the cross-statement block features corresponding to each code segment, determine multiple cross-segment features; and based on the intra-segment features and cross-segment features, determine the document-level features. S210: Based on intra-segment features, cross-segment features, and document-level features, determine the vulnerability detection results using the vulnerability detection model.
[0022] In this embodiment, the computing device can perform vulnerability detection on a smart contract using the smart contract vulnerability detection method based on hierarchical multi-granularity coding provided in this embodiment. First, after obtaining the source code of the smart contract to be detected (S202), the computing device can divide the source code into multiple code segments using a sliding window, and based on the semantic logic of the code, divide each of the multiple code segments into multiple statement blocks to obtain input data (S204). The statement blocks include several basic code units (tokens). The basic code units (tokens) mentioned here can refer to words or symbols in the source code, used to represent the most basic meaning in the code.
[0023] Figure 3 A schematic diagram of the hierarchical structure of the input data is shown. See also Figure 3 As shown, after obtaining the source code of the smart contract to be tested, a sliding window segmentation technique can be used in the preprocessing stage to divide each code sequence into multiple fixed-length code segments. The length of each code segment is... And set a certain overlap step size. This ensures semantic continuity between adjacent code segments. Assume the original code length is... Therefore, the code segment can be divided using a sliding window method, calculated as follows: Where n is the number of code segments obtained after the source code is divided by the sliding window. The length of the code segment. This represents the overlap step size between segments. This method ensures that important contextual information is not lost when using deep learning models to detect vulnerabilities in smart contracts.
[0024] See also Figure 3 As shown, each code segment is further divided into multiple statement blocks according to the semantic logic of the code (e.g., function blocks, condition blocks (statement blocks related to conditional statements), loop blocks (statement blocks related to loop statements), etc.). The method of dividing statement blocks will be explained in detail later.
[0025] Through the above methods, we can obtain the following: Figure 3 The data shown consists of three layers: code segment level, statement block level, and token level. These layers are used as input data, meaning that all data input into the vulnerability detection model has been segmented in the manner described above.
[0026] Then, refer to Figure 4A As shown, the computing device extracts features from the source code based on the input data through the feature extraction layer in the vulnerability detection model, and determines the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment (S206).
[0027] Among them, the cross-block features corresponding to the code segment refer to the features determined by comprehensively considering the information of each block contained in the code segment.
[0028] Then, the computing device continues to perform intra-segment (within code segment) feature fusion and cross-segment (cross code segment) feature fusion through the vulnerability detection model. That is, the computing device, through the feature fusion layer in the vulnerability detection model, determines intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block, determines multiple cross-segment features based on the cross-statement block features corresponding to each code segment, and determines document-level features based on intra-segment features and cross-segment features (S208).
[0029] In other words, based on source code divided into multiple hierarchical structures, the computing device determines the features (token features, statement block features, and code segment features) of multiple levels, and then fuses these features according to their hierarchical relationships. First, by using the token features of tokens and the statement block features of statements within the corresponding code segment, the intra-segment features corresponding to that code segment are determined. Then, by using the cross-statement block features corresponding to each code segment, several cross-segment features are determined. These cross-segment features are used to determine the dependencies between code segments.
[0030] Finally, the computing device continues to use the vulnerability detection model to determine the vulnerability detection result based on intra-segment features, cross-segment features, and document-level features (S210). The vulnerability detection result indicates the type of vulnerability present in the smart contract to be detected, such as reentrancy vulnerabilities or privilege escalation vulnerabilities.
[0031] As described in the background section, deep learning has been increasingly used for smart contract vulnerability detection in recent years. Compared to traditional methods, deep learning-based approaches can automatically learn complex vulnerability patterns from smart contract data, adapt to constantly evolving attack methods, reduce reliance on expert knowledge, and demonstrate significant advantages in improving detection accuracy, automation, and handling complex contracts. However, current deep learning methods still suffer from problems such as insufficient structural understanding, obscuring key local features, and difficulty in modeling long-distance dependencies. Traditional language models often treat code as a flat sequence, ignoring its hierarchical structure and semantic information. Furthermore, cross-statement dependencies in long contracts are difficult to capture, and truncation often results in the loss of important vulnerability features.
[0032] In view of this, according to the technical solution of this embodiment, the source code of the smart contract is first divided into multiple levels to determine the input data, which includes a three-layer structure: code segment level, statement block level, and token level. Furthermore, the statement blocks are divided according to the semantic logic of the code, which is more suitable for the scenario of smart contract vulnerability detection. The vulnerability detection model performs feature extraction and feature fusion based on the three-layer input data, capturing detailed information at the token level, code semantic information at the statement block level, and information at the code segment level. It fuses the token and statement block information within a segment through intra-segment feature fusion, obtains the interaction information between code segments through cross-segment features, and determines document-level features by combining intra-segment and cross-segment features. Then, based on the intra-segment, cross-segment, and document-level features, vulnerability detection is performed on the smart contract to be detected. Therefore, this embodiment not only divides the code features into a unique hierarchical structure to facilitate feature extraction by the vulnerability detection model, but also obtains the interaction and dependency relationships between tokens, statement blocks, and code segments through feature extraction and feature fusion, thereby improving the accuracy of smart contract vulnerability detection using deep learning models.
[0033] Optionally, it also includes: segmenting the source code into tokens using a preset tokenizer to obtain the segmentation results.
[0034] In the preprocessing stage, the source code needs to be segmented using a pre-trained tokenizer, specifically the pre-trained CodeBERT tokenizer, to divide the source code into several tokens. The CodeBERT tokenizer is a pre-trained language model for code that can convert code text into a token sequence, facilitating subsequent feature extraction.
[0035] The following is an example of a block containing several tokens: "["function","deposit","(",")","external","payable","{","require","(","msg",."","value",">","0",")",";","balances","[","msg",."","sender","]","+=","msg",."","value",";","}"]". Each " " in this example represents a token. It should be noted that this block is based on the smart contract code segmented in the examples shown later.
[0036] Furthermore, specific methods for dividing statement blocks are given.
[0037] Optionally, based on code semantic logic, each of the multiple code segments is divided into multiple statement blocks to obtain the operation of input data, including: segmenting by a preset segmentation logic adapted to the smart contract to determine multiple statement blocks contained in the corresponding code segment, wherein the statement blocks include: function blocks, condition blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks.
[0038] In other words, each code segment can be divided into several statement blocks, including function blocks, condition blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks. Among them, the segmentation rules based on the preset segmentation logic can be as follows: (1) For F blocks (function blocks): F blocks are generated in units of FunctionDefinition. To avoid duplication with the sub-block structure, F blocks mainly retain signatures, modifiers, state variables, and interaction summaries, while sub-blocks carry some statements in the function. (2) For I blocks (condition blocks): Each IfStatement constitutes a statement block; the then / else bodies are each independent sub-blocks of I blocks or statement blocks parallel to I-blocks. (3) For L blocks (loop blocks): Each For / While / DoWhile constitutes a loop block, with the loop header and loop body separated, and the loop body is recursively segmented. (4) For key semantic segments, namely, X blocks (external call blocks), A blocks (arithmetic blocks), AC blocks (access control blocks), and fund flow blocks: a block is formed when a match is found. (5) Nested processing: Layered segmentation is used instead of "one-size-fits-all". The parent block mainly retains the header / conditional statements; the body statements belong to the child blocks. In addition, the parent-child relationship between statement blocks can also be recorded.
[0039] Optionally, the code segment is segmented using a pre-defined segmentation logic adapted to the smart contract to determine multiple statement blocks contained in the corresponding code segment, including: determining an abstract syntax tree (AST); recursively traversing the nodes in the AST using a pre-defined recursive function, wherein the recursive traversal operation includes: when the pre-defined recursive function hits a pre-defined statement type, generating a statement block corresponding to the pre-defined statement type, the statement block corresponding to the pre-defined statement type includes at least one of an external call block, an arithmetic operation block, an access control block, and a fund flow block; when the node traversed by the pre-defined recursive function is a function node, based on the signature of the function node... The system generates a function block corresponding to a function node, along with decorators, state variables, and interaction summaries, and continues to traverse the child nodes contained in the function body of the function node using a pre-defined recursive function. When the node traversed by the pre-defined recursive function is a condition node, a condition block corresponding to the condition node is generated, and if the condition node has other associated condition nodes, the system continues to traverse those other condition nodes using the pre-defined recursive function. When the node traversed by the pre-defined recursive function is a loop node, a loop block corresponding to the loop head of the loop node is generated, and the system continues to traverse the nodes contained in the loop body of the loop node using the pre-defined recursive function. Furthermore, when the node traversed by the pre-defined recursive function contains child nodes, the system continues to traverse the child nodes of the corresponding node using the same pre-defined recursive function.
[0040] The steps described above illustrate how to recursively extract statement blocks from the source code or code segment of a smart contract. A corresponding pseudocode example is shown below: DFS (node): if node is FunctionDefinition: emit F-block(header_span) For child in body: DFS(child) elif node is IfStatement: emit I-block(cond_span) DFS(node.thenBody) if has else: DFS(node.elseBody) elif node is LoopStatement: emit L-block(loop_header_span) DFS(node.body) elif node matches external_call / arithmetic / access_control: emit X / A / AC-block(token_span) else: for child in node.children: DFS(child) "The DFS function mentioned above is the default recursive function."
[0041] The following smart contract code example illustrates the segmentation of a statement block: "pragmasolidity ^0.8.20; contract Vault { mapping(address =>uint256) public balances; bool internally locked; modifier nonReentrant() { require(!locked, "reentrant"); locked = true) _; locked = false; } function deposit() external payable { require(msg.value>0, "zero"); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) external nonReentrant { require(balances[msg.sender]>= amount, "insufficient"); balances[msg.sender] -= amount; (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "send failed"); } function drain(address[] calldata users) external { for (uint i = 0; i <users.length; i++) { balances[users[i]] = 0; } } }” The smart contract code provided in the embodiments can be divided into the following segments: F1 (function block 1): deposit function header (signature / modifier information digest); I1 (condition block 1): require(msg.value>0); F2 (function block 2): withdraw function header; AC1 (access control block 1): nonReentrant modifier digest; I2 (condition block 2): require(balances[msg.sender]>= amount); X1 (external call block 1): msg.sender.call{value:amount}("") (external low-level call); I3 (condition block 3): require(ok, "send failed"); F3 (function block 3): drain function header; L1 (loop block 1) for loop block: the assignment of balances[users[i]] = 0 in the body serves as the body of L1.
[0042] Optionally, the feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network. Based on the input data, the feature extraction layer in the vulnerability detection model extracts features from the source code to determine the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. This includes: inputting the word segmentation results corresponding to each code segment into the first feature extraction network to obtain the token features corresponding to each token; inputting the word segmentation results corresponding to each statement block into the second feature extraction network to obtain the statement block features corresponding to each statement block; and for each code segment, inputting the statement block features of each statement block contained in the corresponding code segment into the third feature extraction network to obtain the cross-statement block features corresponding to the corresponding code segment.
[0043] Continue to refer to Figure 4A As shown, in the feature extraction layer, three feature extraction networks are used to extract token-level features, statement block-level features, and cross-statement block-level features, respectively.
[0044] The first feature extraction network is the CodeBERT encoder, which uses a pre-trained CodeBERT model to encode each token to capture its basic semantic information. The hidden state is obtained based on the CodeBERT encoder (essentially a stack of Transformer encoder layers composed of multiple self-attention heads) and serves as the token feature. A sequence of tokens arranged sequentially in a code segment can be input into CodeBERT, and the encoder will obtain the token feature corresponding to each token.
[0045] The second feature extraction network is used to determine sentence block features through a multi-head self-attention mechanism. The sequentially ordered token sequence within the sentence block can be input into the second feature extraction network to obtain the corresponding sentence block features. The second feature extraction network includes a multi-head self-attention layer, followed by a residual layer. The formula is as follows: Among them, in the formula This represents the token sequence of the i-th statement block, multiple This represents multi-head self-attention, where mask represents the mask used in the multi-head self-attention mechanism. Let d represent the statement block feature of the i-th statement block, where d is the vector dimension of the feature, and k represents the token in the i-th statement block. express The features of the t-th token corresponding to the i-th statement block, where k represents the number of tokens in the i-th statement block.
[0046] The third feature extraction network is used to extract cross-block features for each code segment. The block features of the blocks contained in the code segment are input into the third feature extraction network in sequence. The third feature extraction network determines the cross-block features of the corresponding code segment through a multi-head self-attention mechanism. The formula is: That is, assuming a code segment contains m statement blocks, the cross-statement block characteristics of the corresponding code segment are... It is obtained through the statement block characteristics of 1 to m statement blocks. This represents a multi-head self-attention mechanism.
[0047] In this way, for example, the X1 external call block of withdraw will form a strong attention weight with its preceding I2 condition block and decorator AC1, explicitly representing the "check-call" dependency relationship.
[0048] Optionally, based on the token characteristics corresponding to each token and the statement block characteristics corresponding to each statement block, the operation for determining the intra-segment characteristics corresponding to each code segment includes: For each statement block, the token features of the tokens contained in the corresponding statement block are fused with the statement block features of the corresponding statement block to obtain the first fused feature corresponding to the corresponding statement block. For each code segment, a multi-head self-attention mechanism is used to further fuse the first fused features corresponding to each statement block contained in the corresponding code segment to determine the segment-specific features corresponding to the corresponding code segment. Based on the cross-block characteristics corresponding to each code segment, determine the operations for multiple cross-segment characteristics, including: Identify multiple paired code segments; and based on the cross-block characteristics of the multiple paired code segments, determine the cross-segment characteristics corresponding to the corresponding paired code segments.
[0049] Further reference Figure 4A As shown, the feature extraction layer is followed by a feature fusion layer. The feature fusion layer achieves intra-segment hierarchical feature fusion, cross-segment hierarchical feature fusion, and document-level fusion. From Figure 4A As can be seen, the first and second feature extraction networks determine token-level and statement block-level features to achieve intra-segment hierarchical feature fusion, while the third feature extraction network determines code segment-level features to achieve cross-segment hierarchical feature fusion. Finally, document-level fusion is performed.
[0050] In the intra-segment hierarchical feature fusion process, token-level features are fused with statement block-level features, and intra-segment hierarchical features are generated based on cross-statement block-level encoding. In the preceding steps, features for each token and each statement block have been extracted. The token-level features are weighted and pooled (based on token-level self-attention) and then fused with the statement block-level features to obtain the feature representation of the corresponding statement block. This feature representation captures the relative importance of key positions (such as require, call{value:…}) within the statement block.
[0051] Specifically, for the first The token sequence in each statement block The token characteristics of a token are represented as follows: By using a self-attention mechanism to perform weighted pooling of tokens within the same statement block, a token-level feature representation of the corresponding statement block can be obtained. : in, The weight of each token is calculated through a self-attention mechanism. The weight is obtained through multi-head self-attention within a statement block. The statement block-level contextual feature representation of the first statement block (i.e., the statement block features obtained by the second feature extraction network). Then, for the second... Token-level feature representation of each statement block With statement block features The fusion is performed to obtain the first fusion feature z. i : By concatenating the first fusion features of all statement blocks within the obtained code segment in the above manner, the intra-segment features of the corresponding code segment can be determined.
[0052] Alternatively, max pooling can be used to first fuse the token features of tokens contained in the same statement block to obtain the first fused feature, and then max pooling can be used to fuse the first fused feature of each statement block contained in the code segment with the corresponding code segment.
[0053] Then, in the cross-segment hierarchical feature fusion, the cross-block features of each code segment determined by the third feature extraction network are used to determine the cross-segment features of multiple pairs of code segments. For example, assuming there are a total of 4 code segments, code segment 1 to code segment 4, each pair of code segments can be matched to obtain the pairing of code segment 1 and code segment 2, code segment 1 and code segment 3, and so on, including the pairing of code segment 3 and code segment 4. Then, the cross-block features of each pair of code segments are fused through an attention mechanism or a max pooling mechanism to obtain the cross-segment features of the corresponding pair of code segments.
[0054] Then, the intra-segment features and cross-segment features of each code segment can be fused (e.g., attention-weighted fusion using an attention mechanism) to obtain document-level features.
[0055] Optionally, the operation of determining document-level features based on intra-segment features and cross-segment features includes: fusing the intra-segment features of each code segment contained in the source code and the cross-segment features of every pair of code segments to determine document-level features.
[0056] Finally, refer to Figure 4B As shown, the intra-segment features of each identified code segment, the cross-segment features of each paired code segment, and the document-level features are input into the final fully connected layer of the vulnerability detection model for classification, thereby achieving the final identification and classification of smart contract vulnerabilities. The formula is as follows: in, It is a linear transformation matrix, typically of shape [formula missing]. , For the number of categories, For the hidden layer dimension. For document-level features, It is a cross-segment feature. Features within a segment. It is a C-dimensional feature.
[0057] Finally, the calculated logits are normalized using the softmax activation function to obtain the probability distribution for each category. The most likely vulnerability type is then determined using the argmax function. The unnormalized logits are then transformed into a probability distribution for each category: Where i represents the i-th category, that is, the i-th vulnerability type.
[0058] The argmax function selects the category corresponding to the highest probability value as the predicted vulnerability type: The training process of the vulnerability detection model in this embodiment will be described below.
[0059] The training samples used in this embodiment were collected from the SmartBugs Wild dataset. Label cleaning and standardization were performed, null values (NaN) or invalid labels were checked and removed, and the labels were converted to a uniform format to ensure that each label corresponds to a unique category. After cleaning, a total of 14,600 contract data entries were obtained, with labels including, for example, four main vulnerability types (reentrancy vulnerabilities, arithmetic vulnerabilities, access control vulnerabilities, and unchecked low-level call vulnerabilities).
[0060] Next, after the source code in each training sample undergoes the preprocessing described above, it is passed through the fully connected layer of the vulnerability detection model to obtain the corresponding classification result. Next, the vulnerability detection model is trained using cross-entropy loss. This loss function measures the difference between the class probability distribution predicted by the vulnerability detection model and the true labels. The cross-entropy loss function is used to calculate the model's classification performance, as shown in the following formula: in, The probability distribution of the true label (one-hot encoding). The category probability predicted by the vulnerability detection model. It represents the number of categories, and the difference between the predicted and true categories is calculated using the cross-entropy loss function.
[0061] To verify the effectiveness of the method provided in this embodiment, experiments were conducted on a widely recognized public dataset of smart contracts.
[0062] Dataset Description: The dataset primarily originates from the SmartBugs Wild dataset and professional contract analysis blogs, ensuring good representativeness and authenticity. Specifically, the dataset contains 14,600 smart contract samples, of which 7,150 contain vulnerabilities. Each sample provides both source code and bytecode representations. Among these, 1,842 contracts have reentrancy vulnerabilities, 1,297 have arithmetic vulnerabilities, 1,740 have access control vulnerabilities, and 1,716 have unchecked low-level call vulnerabilities. All samples are labeled with vulnerability types, providing a standardized data foundation for the training and evaluation of the vulnerability detection model. In the data partitioning phase, a stratified random sampling strategy was used, dividing the dataset into training, validation, and test sets in a 7:1:2 ratio to ensure that the sample distribution of each subset remains consistent with the original dataset. To ensure the reliability and stability of the experimental results, each experiment was repeated five times, and the mean of the five experimental results was used as the model performance evaluation metric.
[0063] The experiment selected four metrics—accuracy (ACC), recall (RE), precision (PRE), and F1 score (F1)—to comprehensively evaluate the performance of the detection method. The ACC metric represents the proportion of correctly predicted samples out of the total sample size, reflecting the overall prediction accuracy of the detection method. The RE metric measures the proportion of correctly identified positive samples out of all actual positive samples, reflecting the detection method's ability to capture positive samples. The PRE metric calculates the proportion of samples predicted as positive that are actually positive, assessing the reliability of the detection method's positive class predictions. The F1 score, as the harmonic mean of precision and recall, balances the detection method's recall and precision in positive class identification, avoiding evaluation bias caused by a single metric.
[0064] Parameter settings: The method in this embodiment is implemented based on the PyTorch deep learning framework. All experiments were run on a high-performance workstation configured with a 3.3 GHz Intel Core i9 processor, an NVIDIA GeForce RTX 4090 graphics processor, and 64GB of memory. Training used the cross-entropy loss function as the optimization objective, combined with the Adam optimization algorithm and learning rate scheduling strategy. Prediction results were calculated through forward propagation, and network parameters were updated through backpropagation to gradually optimize model performance. The model hyperparameter settings are shown in Table 1.
[0065] num_train_epochs 100 per_device_train_batch_size 16 per_device_eval_batch_size 16 save_total_limit 1 load_best_model_at_end True learning_rate 2e-5 warmup_ratio 0.06 weight_decay 0.01 Table 1 Experimental Results Analysis: The final experimental results are shown in Table 2. The results show that the vulnerability detection model performed excellently in all four vulnerability detection tasks, with all indicators reaching high levels. Overall, the model achieved a good balance between precision and recall while maintaining high accuracy, demonstrating strong generalization ability and practicality. Access-control vulnerability detection performed best, with an F1 score of 0.9532 and a precision of 0.9887, indicating that the model was the most stable in identifying access control-related vulnerabilities. The high recall (0.9655) indicates that the model can effectively capture most real access control vulnerabilities, while the high precision (0.9412) means a relatively low false positive rate. Unchecked-calls vulnerability detection also performed well, with an F1 score of 0.9467. Notably, its precision reached 0.9581, the highest among the five categories, indicating that the model is very cautious in judging unchecked-call vulnerabilities, producing the fewest false positives, which is significant for reducing the unnecessary workload of developers. The detection of the "safe" (secure contract) category showed good balance, with precision (0.9544) and recall (0.9538) almost equal, and an F1 score of 0.9541 reflecting the model's stability in identifying safe contracts. Although the precision was slightly lower (0.9531), this may be due to the higher complexity of the safe contract samples. The detection of reentrancy and arithmetic vulnerabilities performed slightly worse but remained reliable. The recall (0.9239) and precision (0.9067) for reentrancy vulnerability detection were relatively low, possibly because reentrancy attack patterns are more complex, involving cross-function call analysis. The arithmetic vulnerability detection showed balanced performance across all metrics, with an F1 score of 0.9222 indicating stable performance when handling numerical computation-related vulnerabilities.
[0066] reentrancy 0.9784 0.9239 0.9067 0.9152 arithmetic 0.9805 0.9135 0.9311 0.9222 Access control 0.9887 0.9655 0.9412 0.9532 Unchecked-calls 0.9877 0.9357 0.9581 0.9467 safe 0.9531 0.9538 0.9544 0.9541 Table 2 In addition, refer to Figure 1 As shown, according to a second aspect of this embodiment, a storage medium is provided. The storage medium includes a stored program, wherein, when the program is executed, a processor performs any of the methods described above.
[0067] Therefore, according to this embodiment, it is possible to effectively extract token-level detailed information, statement block-level semantic information, and code segment-level information from the smart contract source code through the vulnerability detection model. By combining the hierarchical structure and semantic information of the smart contract source code, vulnerability detection can be performed, thereby improving the accuracy of vulnerability detection.
[0068] It should be noted that, for the sake of simplicity, the foregoing method embodiments are all described as a series of actions. However, those skilled in the art should understand that the present invention is not limited to the described order of actions, because according to the present invention, some steps can be performed in other orders or simultaneously. Furthermore, those skilled in the art should also understand that the embodiments described in the specification are preferred embodiments, and the actions and modules involved are not necessarily essential to the present invention.
[0069] Through the above description of the embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus necessary general-purpose hardware platforms. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a storage medium (such as ROM / RAM, magnetic disk, optical disk) and includes several instructions to cause a terminal device (which may be a mobile phone, computer, server, or network device, etc.) to execute the methods described in the various embodiments of the present invention.
[0070] Example 2 Figure 6 A smart contract vulnerability detection device based on hierarchical multi-granularity coding according to the first aspect of this embodiment is shown, which corresponds to the method described according to the first aspect of Embodiment 1. (Reference) Figure 6 As shown, a smart contract vulnerability detection device based on hierarchical multi-granularity coding includes: an acquisition module 601 for acquiring the source code of the smart contract to be detected; a segmentation module 602 for dividing the source code into multiple code segments using a sliding window, and dividing each code segment into multiple statement blocks based on code semantic logic to obtain input data, wherein the statement blocks include several basic code units (tokens); and a feature extraction module 603 for extracting features from the source code based on the input data using the feature extraction layer in the vulnerability detection model, and determining the token features corresponding to each token. The vulnerability detection model includes a statement block feature corresponding to each statement block and a cross-statement block feature corresponding to each code segment; a feature fusion module 604, which is used to determine the intra-segment feature corresponding to each code segment based on the token feature corresponding to each token and the statement block feature corresponding to each statement block through the feature fusion layer in the vulnerability detection model; determine multiple cross-segment features based on the cross-statement block feature corresponding to each code segment; and determine document-level features based on the intra-segment feature and the cross-segment feature; and a vulnerability detection module 605, which is used to determine the vulnerability detection result based on the intra-segment feature, the cross-segment feature, and the document-level feature through the vulnerability detection model.
[0071] Optionally, the segmentation module 602 is used to segment the code according to a preset segmentation logic adapted to the smart contract, and to determine multiple statement blocks contained in the corresponding code segment. The statement blocks include: function blocks, condition blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks.
[0072] Optionally, the partitioning module 602 is used to determine the Abstract Syntax Tree (AST); recursively traversing the nodes in the AST using a preset recursive function, wherein the recursive traversal operation includes: when the preset recursive function hits a preset statement type, generating a statement block corresponding to the preset statement type, the statement block corresponding to the preset statement type includes at least one of external call block, arithmetic operation block, access control block, and fund flow block; when the node traversed by the preset recursive function is a function node, generating a function block corresponding to the function node based on the function node's signature, decorator, state variable, and interaction summary, and continuing to traverse the child nodes contained in the function body of the function node using the preset recursive function; when the node traversed by the preset recursive function is a condition node, generating a condition block corresponding to the condition node, and continuing to traverse other condition nodes related to the condition node using the preset recursive function if the condition node has other related condition nodes; when the node recursively traversed is a loop node, generating a loop block corresponding to the loop head of the loop node, and continuing to traverse the nodes contained in the loop body of the loop node using the preset recursive function.
[0073] Optionally, the segmentation module 602 is also used to segment the source code into several tokens using a preset tokenizer to obtain the segmentation result.
[0074] Optionally, the feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network; the feature extraction module 603 is used to input the word segmentation results corresponding to each code segment into the first feature extraction network to obtain the token feature corresponding to each token, and to input the word segmentation results corresponding to each statement block into the second feature extraction network to obtain the statement block feature corresponding to each statement block, and for each code segment, to input the statement block features of each statement block contained in the corresponding code segment into the third feature extraction network to obtain the cross-statement block feature corresponding to the corresponding code segment.
[0075] Optionally, the feature fusion module 604, for each statement block, fuses the token feature of the token contained in the corresponding statement block with the statement block feature of the corresponding statement block to obtain a first fused feature corresponding to the corresponding statement block; for each code segment, through a multi-head self-attention mechanism, further fuses the first fused features corresponding to each statement block contained in the corresponding code segment to determine the intra-segment feature corresponding to the corresponding code segment, and wherein the operation of determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment includes: determining multiple paired code segments; and determining the cross-segment features corresponding to the corresponding paired code segments based on the cross-statement block features of the multiple paired code segments.
[0076] Optionally, the feature fusion module 604 fuses the intra-segment features of each code segment contained in the source code and the cross-segment features of every pair of code segments to determine document-level features.
[0077] Therefore, according to this embodiment, it is possible to effectively extract token-level detailed information, statement block-level semantic information, and code segment-level information from the smart contract source code through the vulnerability detection model. By combining the hierarchical structure and semantic information of the smart contract source code, vulnerability detection can be performed, thereby improving the accuracy of vulnerability detection.
[0078] Example 3 Figure 7 A smart contract vulnerability detection device based on hierarchical multi-granularity coding according to the first aspect of this embodiment is shown, which corresponds to the method described according to the first aspect of Embodiment 1. (Reference) Figure 7As shown, the machine learning-based smart contract dynamic and static vulnerability detection device includes: a processor 710; and a memory 720 connected to the processor 710, used to provide the processor 710 with instructions to process the following steps: obtaining the source code of the smart contract to be detected; dividing the source code into multiple code segments using a sliding window method, and dividing each of the multiple code segments into multiple statement blocks based on code semantic logic to obtain input data, wherein the statement blocks include several basic code unit tokens; and extracting features from the source code using the feature extraction layer in the vulnerability detection model based on the input data. The vulnerability detection model identifies token features corresponding to each token, statement block features corresponding to each statement block, and cross-statement block features corresponding to each code segment. Using the feature fusion layer in the vulnerability detection model, it determines intra-segment features corresponding to each code segment based on the token features and statement block features, determines multiple cross-segment features based on the cross-statement block features corresponding to each code segment, and determines document-level features based on intra-segment and cross-segment features. Finally, based on the intra-segment, cross-segment, and document-level features, the vulnerability detection model determines the vulnerability detection result.
[0079] Optionally, based on code semantic logic, each of the multiple code segments is divided into multiple statement blocks to obtain the operation of input data, including: segmenting by a preset segmentation logic adapted to the smart contract to determine multiple statement blocks contained in the corresponding code segment, wherein the statement blocks include: function blocks, condition blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks.
[0080] Optionally, the code segment is segmented using a pre-defined segmentation logic adapted to the smart contract to determine multiple statement blocks contained in the corresponding code segment, including: determining an abstract syntax tree (AST); recursively traversing the nodes in the AST using a pre-defined recursive function, wherein the recursive traversal operation includes: when the pre-defined recursive function hits a pre-defined statement type, generating a statement block corresponding to the pre-defined statement type, the statement block corresponding to the pre-defined statement type includes at least one of an external call block, an arithmetic operation block, an access control block, and a fund flow block; when the node traversed by the pre-defined recursive function is a function node, based on the function node... The signature, modifier, state variables, and interaction summary are used to generate a function block corresponding to the function node, and to continue traversing the child nodes contained in the function body of the function node through a preset recursive function; when the node traversed by the preset recursive function is a condition node, a condition block corresponding to the condition node is generated, and if there are other related condition nodes, the other condition nodes are traversed through the preset recursive function; when the node traversed by the recursion is a loop node, a loop block corresponding to the loop head of the loop node is generated, and the nodes contained in the loop body of the loop node are traversed through the preset recursive function.
[0081] Optionally, before dividing the source code into multiple code segments using a sliding window, the method further includes: segmenting the source code into tokens using a preset tokenizer, dividing the source code into several tokens, and obtaining the segmentation results.
[0082] Optionally, the feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network. Based on the input data, the feature extraction layer in the vulnerability detection model extracts features from the source code to determine the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. This includes: inputting the word segmentation results corresponding to each code segment into the first feature extraction network to obtain the token features corresponding to each token; inputting the word segmentation results corresponding to each statement block into the second feature extraction network to obtain the statement block features corresponding to each statement block; and for each code segment, inputting the statement block features of each statement block contained in the corresponding code segment into the third feature extraction network to obtain the cross-statement block features corresponding to the corresponding code segment.
[0083] Optionally, the operation of determining the intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block includes: for each statement block, fusing the token features of the tokens contained in the corresponding statement block and the statement block features of the corresponding statement block to obtain a first fused feature corresponding to the corresponding statement block; for each code segment, further fusing the first fused features corresponding to each statement block contained in the corresponding code segment through a multi-head self-attention mechanism to determine the intra-segment features corresponding to the corresponding code segment, and wherein the operation of determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment includes: determining multiple paired code segments; and determining the cross-segment features corresponding to the corresponding paired code segments based on the cross-statement block features of the multiple paired code segments.
[0084] Optionally, the operation of determining document-level features based on intra-segment features and cross-segment features includes: fusing the intra-segment features of each code segment contained in the source code and the cross-segment features of every pair of code segments to determine document-level features.
[0085] Therefore, according to this embodiment, it is possible to effectively extract token-level detailed information, statement block-level semantic information, and code segment-level information from the smart contract source code through the vulnerability detection model. By combining the hierarchical structure and semantic information of the smart contract source code, vulnerability detection can be performed, thereby improving the accuracy of vulnerability detection.
[0086] The sequence numbers of the above embodiments of the present invention are for descriptive purposes only and do not represent the superiority or inferiority of the embodiments.
[0087] In the above embodiments of the present invention, the descriptions of each embodiment have different focuses. For parts not described in detail in a certain embodiment, please refer to the relevant descriptions of other embodiments.
[0088] In the several embodiments provided in this application, it should be understood that the disclosed technical content can be implemented in other ways. The device embodiments described above are merely illustrative; for example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the displayed or discussed mutual coupling, direct coupling, or communication connection may be through some interfaces; the indirect coupling or communication connection between units or modules may be electrical or other forms.
[0089] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0090] Furthermore, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0091] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, read-only memory (ROM), random access memory (RAM), portable hard drives, magnetic disks, or optical disks.
[0092] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A smart contract vulnerability detection method based on hierarchical multi-granularity coding, characterized in that, include: Obtain the source code of the smart contract to be tested; Based on a preset overlap step, the source code is divided into multiple code segments using a sliding window. Based on the semantic logic of the code, each of the multiple code segments is divided into multiple statement blocks to obtain input data. The statement blocks include several basic code unit tokens, and there is overlap between adjacent code segments. Based on the input data, the source code is subjected to feature extraction through the feature extraction layer in the vulnerability detection model to determine the token feature corresponding to each token, the statement block feature corresponding to each statement block, and the cross-statement block feature corresponding to each code segment. Through the feature fusion layer in the vulnerability detection model, intra-segment features corresponding to each code segment are determined based on the token features corresponding to each token and the statement block features corresponding to each statement block. Multiple cross-segment features are determined based on the cross-statement block features corresponding to each code segment. Finally, document-level features are determined based on the intra-segment features and the cross-segment features. Based on the intra-segment features, cross-segment features, and document-level features, a vulnerability detection model is used to determine the vulnerability detection result. The operation of determining the intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block includes: For each statement block, the token features of the tokens contained in the corresponding statement block are fused with the statement block features of the corresponding statement block to obtain a first fused feature corresponding to the corresponding statement block. For each code segment, the first fused features corresponding to each statement block contained in the corresponding code segment are further fused using a multi-head self-attention mechanism to determine the segment-specific features corresponding to the corresponding code segment. Furthermore, the operation of determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment includes: determining multiple pairs of code segments, wherein the pairs of code segments at least include adjacent code segments; and Based on the cross-statement block features of the multiple paired code segments, the cross-segment features corresponding to the respective paired code segments are determined, and wherein, based on code semantic logic, each of the multiple code segments is divided into multiple statement blocks to obtain the input data, including: The code segment is segmented using a pre-defined segmentation logic adapted to the smart contract, identifying multiple statement blocks within each segment. These statement blocks include: function blocks, conditional blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks. Furthermore, the segmentation, performed using a pre-defined segmentation logic adapted to the smart contract, identifies multiple statement blocks within each segment, including: Determine the Abstract Syntax Tree (AST); The nodes in the abstract syntax tree are recursively traversed using a pre-defined recursive function, wherein the recursive traversal operation includes: When the preset recursive function hits the preset statement type, it generates a statement block corresponding to the preset statement type. The statement block corresponding to the preset statement type includes at least one of the following: external call block, arithmetic operation block, access control block, and fund flow block. When the node traversed by the preset recursive function is a function node, a function block corresponding to the function node is generated based on the function node's signature, decorator, state variable, and interaction summary, and the child nodes contained in the function body of the function node are traversed by the preset recursive function. When the node traversed by the preset recursive function is a condition node, a condition block corresponding to the condition node is generated, and if there are other related condition nodes, the other condition nodes are traversed by the preset recursive function. When the recursive traversal reaches a loop node, a loop block corresponding to the loop head of the loop node is generated, and the nodes contained in the loop body of the loop node are traversed again through the preset recursive function. This process also includes: The source code is segmented into several tokens using a preset word segmenter to obtain the word segmentation result. The feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network. Based on the input data, the source code is subjected to feature extraction through the feature extraction layer in the vulnerability detection model. This process determines the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. The operations include: The word segmentation results corresponding to each code segment are input into the first feature extraction network to obtain the token feature corresponding to each token. The word segmentation results corresponding to each statement block are input into the second feature extraction network to obtain the statement block feature corresponding to each statement block. For each code segment, the statement block features of each statement block contained in the corresponding code segment are input into the third feature extraction network in sequence to obtain the cross-statement block feature corresponding to the corresponding code segment.
2. The method according to claim 1, characterized in that, The operation of determining document-level features based on the intra-segment features and the cross-segment features includes: The document-level features are determined by fusing the intra-segment features of each code segment contained in the source code and the cross-segment features of every pair of code segments.
3. A storage medium, characterized in that, The storage medium includes a stored program, wherein the method described in any one of claims 1 to 2 is generated and executed by a processor when the program is run.
4. A smart contract vulnerability detection device based on hierarchical multi-granularity coding, characterized in that, include: The acquisition module is used to acquire the source code of the smart contract to be tested; The segmentation module is used to divide the source code into multiple code segments by means of a sliding window according to a preset overlap step size, and to divide each of the multiple code segments into multiple statement blocks based on the semantic logic of the code to obtain input data. The statement blocks include several basic code unit tokens, and there is overlap between adjacent code segments. The feature extraction module is used to extract features from the source code based on the input data through the feature extraction layer in the vulnerability detection model, and to determine the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. The feature fusion module is used to determine intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block, through the feature fusion layer in the vulnerability detection model; determine multiple cross-segment features based on the cross-statement block features corresponding to each code segment; and determine document-level features based on the intra-segment features and the cross-segment features. The vulnerability detection module is used to determine the vulnerability detection result based on the intra-segment features, the cross-segment features, and the document-level features, using a vulnerability detection model. The operation of determining the intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block includes: For each statement block, the token features of the tokens contained in the corresponding statement block are fused with the statement block features of the corresponding statement block to obtain a first fused feature corresponding to the corresponding statement block. For each code segment, the first fused features corresponding to each statement block contained in the corresponding code segment are further fused using a multi-head self-attention mechanism to determine the segment-specific features corresponding to the corresponding code segment. Furthermore, the operation of determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment includes: determining multiple pairs of code segments, wherein the pairs of code segments at least include adjacent code segments; and Based on the cross-statement block features of the multiple paired code segments, the cross-segment features corresponding to the respective paired code segments are determined, and wherein, based on code semantic logic, each of the multiple code segments is divided into multiple statement blocks to obtain the input data, including: The code segment is segmented using a pre-defined segmentation logic adapted to the smart contract, identifying multiple statement blocks within each segment. These statement blocks include: function blocks, conditional blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks. Furthermore, the segmentation, performed using a pre-defined segmentation logic adapted to the smart contract, identifies multiple statement blocks within each segment, including: Determine the Abstract Syntax Tree (AST); The nodes in the abstract syntax tree are recursively traversed using a pre-defined recursive function, wherein the recursive traversal operation includes: When the preset recursive function hits the preset statement type, it generates a statement block corresponding to the preset statement type. The statement block corresponding to the preset statement type includes at least one of the following: external call block, arithmetic operation block, access control block, and fund flow block. When the node traversed by the preset recursive function is a function node, a function block corresponding to the function node is generated based on the function node's signature, decorator, state variable, and interaction summary, and the child nodes contained in the function body of the function node are traversed by the preset recursive function. When the node traversed by the preset recursive function is a condition node, a condition block corresponding to the condition node is generated, and if there are other related condition nodes, the other condition nodes are traversed by the preset recursive function. When the recursive traversal reaches a loop node, a loop block corresponding to the loop head of the loop node is generated, and the nodes contained in the loop body of the loop node are traversed again through the preset recursive function. This process also includes: The source code is segmented into several tokens using a preset word segmenter to obtain the word segmentation result. The feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network. Based on the input data, the source code is subjected to feature extraction through the feature extraction layer in the vulnerability detection model. This process determines the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. The operations include: The word segmentation results corresponding to each code segment are input into the first feature extraction network to obtain the token feature corresponding to each token. The word segmentation results corresponding to each statement block are input into the second feature extraction network to obtain the statement block feature corresponding to each statement block. For each code segment, the statement block features of each statement block contained in the corresponding code segment are input into the third feature extraction network in sequence to obtain the cross-statement block feature corresponding to the corresponding code segment.
5. A smart contract vulnerability detection device based on hierarchical multi-granularity coding, characterized in that, include: processor; as well as A memory, connected to the processor, for providing the processor with instructions to perform the following processing steps: Obtain the source code of the smart contract to be tested; Based on a preset overlap step, the source code is divided into multiple code segments using a sliding window. Based on the semantic logic of the code, each of the multiple code segments is divided into multiple statement blocks to obtain input data. The statement blocks include several basic code unit tokens, and there is overlap between adjacent code segments. Based on the input data, the source code is subjected to feature extraction through the feature extraction layer in the vulnerability detection model to determine the token feature corresponding to each token, the statement block feature corresponding to each statement block, and the cross-statement block feature corresponding to each code segment. Through the feature fusion layer in the vulnerability detection model, intra-segment features corresponding to each code segment are determined based on the token features corresponding to each token and the statement block features corresponding to each statement block. Multiple cross-segment features are determined based on the cross-statement block features corresponding to each code segment. Finally, document-level features are determined based on the intra-segment features and the cross-segment features. Based on the intra-segment features, cross-segment features, and document-level features, a vulnerability detection model is used to determine the vulnerability detection result. The operation of determining the intra-segment features corresponding to each code segment based on the token features corresponding to each token and the statement block features corresponding to each statement block includes: For each statement block, the token features of the tokens contained in the corresponding statement block are fused with the statement block features of the corresponding statement block to obtain a first fused feature corresponding to the corresponding statement block. For each code segment, the first fused features corresponding to each statement block contained in the corresponding code segment are further fused using a multi-head self-attention mechanism to determine the segment-specific features corresponding to the corresponding code segment. Furthermore, the operation of determining multiple cross-segment features based on the cross-statement block features corresponding to each code segment includes: determining multiple pairs of code segments, wherein the pairs of code segments at least include adjacent code segments; and Based on the cross-statement block features of the multiple paired code segments, the cross-segment features corresponding to the respective paired code segments are determined, and wherein, based on code semantic logic, each of the multiple code segments is divided into multiple statement blocks to obtain the input data, including: The code segment is segmented using a pre-defined segmentation logic adapted to the smart contract, identifying multiple statement blocks within each segment. These statement blocks include: function blocks, conditional blocks, loop blocks, external call blocks, arithmetic operation blocks, fund flow blocks, and access control blocks. Furthermore, the segmentation, performed using a pre-defined segmentation logic adapted to the smart contract, identifies multiple statement blocks within each segment, including: Determine the Abstract Syntax Tree (AST); The nodes in the abstract syntax tree are recursively traversed using a pre-defined recursive function, wherein the recursive traversal operation includes: When the preset recursive function hits the preset statement type, it generates a statement block corresponding to the preset statement type. The statement block corresponding to the preset statement type includes at least one of the following: external call block, arithmetic operation block, access control block, and fund flow block. When the node traversed by the preset recursive function is a function node, a function block corresponding to the function node is generated based on the function node's signature, decorator, state variable, and interaction summary, and the child nodes contained in the function body of the function node are traversed by the preset recursive function. When the node traversed by the preset recursive function is a condition node, a condition block corresponding to the condition node is generated, and if there are other related condition nodes, the other condition nodes are traversed by the preset recursive function. When the recursive traversal reaches a loop node, a loop block corresponding to the loop head of the loop node is generated, and the nodes contained in the loop body of the loop node are traversed again through the preset recursive function. This process also includes: The source code is segmented into several tokens using a preset word segmenter to obtain the word segmentation result. The feature extraction layer includes a first feature extraction network, a second feature extraction network, and a third feature extraction network. Based on the input data, the source code is subjected to feature extraction through the feature extraction layer in the vulnerability detection model to determine the token features corresponding to each token, the statement block features corresponding to each statement block, and the cross-statement block features corresponding to each code segment. This includes: inputting the word segmentation results corresponding to each code segment into the first feature extraction network to obtain the token features corresponding to each token; inputting the word segmentation results corresponding to each statement block into the second feature extraction network to obtain the statement block features corresponding to each statement block; and for each code segment, inputting the statement block features of each statement block contained in the corresponding code segment into the third feature extraction network in sequence to obtain the cross-statement block features corresponding to the corresponding code segment.