A smart contract security audit method and system based on neural network model
Through the smart contract security audit method based on neural network model, combining dynamic and static data, identifying the operation level and predictive behavior characteristics, the problem of low accuracy of smart contract security audit is solved, and more efficient abnormal state detection and system security improvement are achieved.
Patent Information
- Application Number
- CN202510629461.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-16
- Publication Date
- 2025-09-05
- Estimated Expiration
- 2045-05-16
AI Technical Summary
The security audit methods of existing smart contracts are not accurate, and abnormal states cannot be detected in time, which poses system security risks.
The smart contract security audit method based on neural network model is adopted, and the embedded matrix of the graph attention network is obtained by analyzing the smart contract code, combining the key behavioral characteristics of the smart contract transaction log, and using the level classification model and prediction model to integrate dynamic and static data to identify the running level of the smart contract and predict future behavioral characteristics.
It improves the accuracy of smart contract security audits, promptly detects abnormal states, improves system security, and adapts to complex and dynamic changes in smart contracts.
Smart Images

Figure CN120145405B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of smart contract technology, and in particular to a smart contract security audit method and system based on a neural network model. Background Art
[0002] Smart contracts are automated code that runs on a blockchain. Based on predefined rules and conditions, they implement complex business logic and automated processes on the blockchain. Consequently, smart contracts have greatly expanded the application areas of blockchain technology. However, because smart contracts are represented by program logic structures, they are inevitably subject to flaws and security design deficiencies. In particular, smart contracts are vulnerable to reentrancy vulnerabilities, transaction sequence dependency vulnerabilities, and short address attacks during execution. Therefore, security audits of smart contracts have become a fundamental safeguard for business applications.
[0003] Traditional automated vulnerability detection methods for smart contracts are mainly categorized into symbolic execution, fuzz testing, and formal verification. Symbolic execution vulnerability detection starts at the smart contract bytecode level, capturing traces that match the characteristics of defined vulnerability types through symbolic execution to determine whether the smart contract has a vulnerability. However, this method presents difficulties in solving constraints. Fuzz testing detects vulnerabilities by inputting fuzzed and mutated inputs into a binary interface and analyzing execution logs. However, due to the many different characteristics of smart contracts, test results may not meet expectations. While formal verification can extract deep semantic information from smart contracts, it requires manual analysis, resulting in low detection efficiency.
[0004] Deep learning-based vulnerability detection methods can address the long detection times and low accuracy of traditional automated vulnerability detection methods. However, most existing deep learning-based detection methods directly use smart contract source code, opcode sequences, or bytecode sequences as input to the deep learning model. This ignores the fact that some dynamic behavioral characteristics of smart contracts are closely related to the structure and data flow of the smart contract code, which have varying degrees of impact on smart contract execution. This results in an inability to promptly detect abnormal smart contract states, posing significant risks to system security. Summary of the Invention
[0005] In view of the above analysis, the embodiments of the present invention aim to provide a smart contract security audit method and system based on a neural network model to solve the problem of low accuracy of existing smart contract security audits.
[0006] In one aspect, an embodiment of the present invention provides a smart contract security audit method based on a neural network model, comprising the following steps:
[0007] Analyze the smart contract code to obtain the smart contract graph; pass the smart contract graph into the graph attention network to obtain the embedding matrix of the smart contract graph;
[0008] The key behavioral features at each moment are obtained based on the smart contract transaction log, and are respectively input into the level classification model with the embedding matrix of the smart contract graph to obtain the classification results at each moment;
[0009] Sequence data of key behavior features and classification results are constructed according to the length of the time window, and at the same time, they are input into the prediction model to obtain the predicted behavior features of the next moment, which are then compared with the key behavior features of the next moment for similarity. If the similarity is less than the similarity threshold, the smart contract will be abnormal.
[0010] Based on a further improvement of the above method, the level classification model includes a fusion layer and a multi-layer perceptron in sequence. The fusion layer receives the key behavioral features and the embedding matrix of the smart contract graph, outputs the fusion vector to the multi-layer perceptron, and the multi-layer perceptron outputs the probability distribution of the smart contract operation level.
[0011] Based on the further improvement of the above method, the prediction model adopts a dual-branch LSTM model. Two independent LSTM branches are used to process the sequence data of key behavior features and classification results respectively, and the hidden states of the two LSTM branches are fused. The fused hidden states are mapped to the key behavior feature space through a fully connected layer to obtain the predicted behavior features at the next moment.
[0012] Based on the further improvement of the above method, the fusion layer projects the key behavior features into a query vector, projects the embedding matrix of the smart contract graph into a key matrix and a value matrix, and outputs a fusion vector using the cross-attention mechanism.
[0013] Based on a further improvement of the above method, the key behavioral features are obtained by performing principal component analysis on the historical behavioral data in the smart contract transaction log to obtain a principal component matrix. Based on the principal component matrix, the key behavioral features of the behavioral data at each new moment in the smart contract transaction log are obtained; the behavioral data include: transaction amount, transaction time, GAS limit, GAS consumption, contract type, contract status and storage usage.
[0014] Based on the further improvement of the above method, the smart contract code is analyzed to obtain the smart contract graph, including:
[0015] Convert the smart contract code into an abstract syntax tree, obtain key functions and key variables as nodes based on the abstract syntax tree; obtain the control flow of key functions and the data flow of key variables as edges;
[0016] The node feature matrix is constructed by extracting the attributes of key functions and key variables; the node adjacency matrix is constructed based on nodes and edges; the node feature matrix and the node adjacency matrix form the smart contract graph.
[0017] Based on the further improvement of the above method, the graph attention network includes an embedding layer and multiple graph attention layers in sequence; the embedding layer converts the node feature matrix in the smart contract graph into a high-dimensional embedding matrix through linear transformation and passes it to multiple graph attention layers. Each layer of the multiple graph attention layers includes multiple attention heads. Each attention head calculates the attention weight based on the high-dimensional embedding matrix and the node adjacency matrix, and then updates the embedding vector of each node. The multiple heads are spliced together for use by the next layer. The last layer obtains the embedding vector of each node by averaging the outputs of multiple attention heads, forming the embedding matrix of the smart contract graph.
[0018] Based on the further improvement of the above method, the level classification model and the prediction model are obtained through joint training; during the joint training process, the classification loss is calculated using the cross entropy loss function, and the prediction loss is calculated using the mean square error and then the weighted sum is obtained to obtain the total loss. All parameters of the level classification model and the prediction model are updated by minimizing the total loss.
[0019] Based on further improvements to the above method, during joint training, the historical time series is divided into multiple window samples according to the length of the time window. Each window sample contains the historical key behavior features and their classification labels at multiple moments, as well as the historical key behavior features of the next moment. Each batch contains multiple window samples, and different window samples in the same batch share the embedding matrix of the smart contract graph. When calculating the total loss, the classification loss is calculated for each moment in each window sample in each batch, and the prediction loss is calculated for each window sample in each batch.
[0020] On the other hand, an embodiment of the present invention provides a smart contract security audit system based on a neural network model, comprising:
[0021] The code analysis module is used to analyze the smart contract code to obtain the smart contract graph; the smart contract graph is passed into the graph attention network to obtain the embedding matrix of the smart contract graph;
[0022] The level classification module is used to obtain the key behavioral features at each moment based on the smart contract transaction log, and input them into the level classification model together with the embedding matrix of the smart contract graph to obtain the classification results at each moment;
[0023] The security audit module is used to construct sequence data of key behavior features and classification results according to the length of the time window, and at the same time input the prediction model to obtain the predicted behavior features of the next moment, and then compare the similarity with the key behavior features of the next moment. If the similarity is less than the similarity threshold, the smart contract will be abnormal.
[0024] Compared with the prior art, the present invention can achieve at least one of the following beneficial effects:
[0025] 1. Comprehensively consider the dynamic operation characteristics and static code characteristics of smart contracts, use dynamic key behavioral characteristics to reflect the performance of smart contracts in the actual operation process, use static graph embedding matrix to represent the structure and semantics of smart contract code, and integrate dynamic and static data to timely discover abnormal status of smart contracts, thereby improving the accuracy of smart contract security audits and enhancing system security.
[0026] 2. Use the level classification model to identify the smart contract operation level, which is used as the input of one branch of the prediction model to capture the changing trend of the smart contract operation status over time. By using another branch of the prediction model to capture the dynamic changes of transaction status over time, and through comprehensive consideration of multiple branches, it provides richer information, helps to more accurately predict the behavioral characteristics of smart contracts at future moments, and enables the model to better adapt to the complex dynamic changes in the operation process of smart contracts.
[0027] In the present invention, the above-mentioned technical solutions can be combined with each other to achieve more preferred combinations. Other features and advantages of the present invention will be described in the following description, and some advantages will become apparent from the description or be learned through practice of the present invention. The objectives and other advantages of the present invention can be realized and obtained through the contents particularly pointed out in the description and drawings. BRIEF DESCRIPTION OF THE DRAWINGS
[0028] The accompanying drawings are only used for the purpose of illustrating specific embodiments and are not to be considered as limiting the present invention. Like reference symbols denote like components throughout the accompanying drawings.
[0029] Figure 1 This is a flow chart of a smart contract security audit method based on a neural network model in Example 1 of the present invention;
[0030] Figure 2 Schematic diagram of the joint training process of the level classification model and the prediction model in Example 1 of the present invention;
[0031] Figure 3 This is a schematic diagram of the structure of a smart contract security audit system based on a neural network model in Example 2 of the present invention. DETAILED DESCRIPTION
[0032] The preferred embodiments of the present invention will be described in detail below in conjunction with the accompanying drawings, wherein the accompanying drawings constitute a part of this application and are used together with the embodiments of the present invention to illustrate the principles of the present invention, and are not used to limit the scope of the present invention.
[0033] Example 1
[0034] A specific embodiment of the present invention discloses a smart contract security audit method based on a neural network model, such as Figure 1 As shown, the following steps are included:
[0035] S1. Analyze the smart contract code to obtain the smart contract graph; pass the smart contract graph into the graph attention network to obtain the embedding matrix of the smart contract graph.
[0036] It should be noted that smart contract code is usually written in Solidity and ends in the .sol format. Analyzing the smart contract code to obtain the smart contract graph includes:
[0037] ①Convert the smart contract code into an abstract syntax tree, obtain key functions and key variables as nodes according to the abstract syntax tree; obtain the control flow of key functions and the data flow of key variables as edges;
[0038] ② Construct a node feature matrix by extracting the attributes of key functions and key variables; construct a node adjacency matrix based on nodes and edges; the node feature matrix and the node adjacency matrix form a smart contract graph.
[0039] The Abstract Syntax Tree (AST) is an abstract representation of the grammatical structure of the source code. It represents the grammatical structure of the programming language in a tree-like format, with each node in the tree representing a structure in the source code. The AST contains a complete representation of the entire compilation unit, providing a relatively intuitive representation of the grammatical structure of the source code. Smart contract code can be converted into an AST using the Solidity compiler or the static analysis tool Slither. However, the AST contains excessive redundant information, such as nodes indicating the compiled version, nodes importing external source files, and duplicate variable declarations.
[0040] Therefore, this embodiment traverses the child nodes of the root node, detects the node type nodeType of each child node, takes the node whose node type attribute value is FunctionDefinition as the key function, takes the node whose node type attribute value is StateVariableDeclaration as the key variable, and takes the key function and key variable as nodes.
[0041] Furthermore, control flow is used to define the calling relationships between key functions, such as conditional branches, function calls, and loops; data flow is used to define the read and write relationships between functions and variables (i.e., access and modification of variables), such as variable assignment and function parameter passing. This embodiment uses the static analysis tool Slither to generate a control flow graph for function calls and extract variable read and write operations. Edges are then established between nodes based on the relationships between key functions and between key functions and key variables.
[0042] Furthermore, a node feature matrix is constructed by extracting the attributes of key functions and key variables. Key function attributes include: name, node type, function visibility, and return value type; key variable attributes include: name, node type, variable visibility, and variable type. Word embedding techniques (such as Word2Vec) are then used to convert the name attribute values into vectors, and one-hot encoding is used to map the node type, function / variable visibility, and return value / variable type attribute values to distinct numeric values. The encoded features of each node's attribute values are combined into a feature vector, forming a node feature matrix. Each node corresponds to a feature vector, with each row of the matrix representing a node's feature vector and each column representing a feature dimension.
[0043] Exemplarily, the node types include FunctionDefinition and StateVariableDeclaration. One-hot encoding is used to encode the attribute value of the node type of the function node as [1,0], and the attribute value of the node type of the variable node as [0,1].
[0044] The node adjacency matrix is constructed based on nodes and edges. When there is an edge between nodes, the corresponding element value in the node adjacency matrix is set to 1, otherwise it is 0.
[0045] The constructed node feature matrix and node adjacency matrix constitute the smart contract graph.
[0046] Considering that the feature vector of each node in the node feature matrix only contains its own information and lacks the topological relationship between nodes, which leads to information loss, the graph attention network is used to capture the contextual relationship of the code, obtain the embedding vector of each node in the smart contract graph, and obtain the embedding matrix of the smart contract graph.
[0047] It should be noted that the graph attention network includes an embedding layer and multiple graph attention layers in sequence; the embedding layer converts the node feature matrix in the smart contract graph into a high-dimensional embedding matrix through linear transformation and passes it to multiple graph attention layers. Each layer of the multiple graph attention layers includes multiple attention heads. Each attention head calculates the attention weight based on the high-dimensional embedding matrix and the node adjacency matrix, and then updates the embedding vector of each node. The multiple heads are spliced together for use by the next layer. The last layer obtains the embedding vector of each node by averaging the outputs of multiple attention heads, forming the embedding matrix of the smart contract graph.
[0048] Specifically, each graph attention layer includes: performing a linear transformation on the high-dimensional embedding vector of each node, each attention head calculates the attention weight based on the transformed high-dimensional embedding vector of each node and the node adjacency matrix, normalizes the attention weight through Softmax, and then weights and aggregates the neighbor features. Non-linear activation is applied to obtain the embedding vector of each node as the result of each attention head. The intermediate graph attention layer is sent to the next layer by splicing the results of each attention head. The graph attention layer of the last layer takes the average of the results of each attention head to obtain the embedding vector of each node.
[0049] S2. Obtain the key behavioral features at each moment based on the smart contract transaction log, and input them into the level classification model with the embedding matrix of the smart contract graph to obtain the classification results at each moment.
[0050] It should be noted that the behavioral data extracted from smart contract transaction logs includes: transaction amount, transaction time, GAS (Genesis Asset Share, a unit of measurement for the computing resources required to execute smart contract operations and transactions) limit, GAS consumption, contract type, contract status, and storage usage. The transaction amount reflects the dynamics of the smart contract's processing scale as validation rules in the business logic execute different branches of the smart contract code; transaction time reflects the smart contract's active period; GAS limit matches the worst-case scenario of the smart contract's execution path, and GAS consumption is affected by the complexity of the smart contract code and storage operations. GAS limit and GAS consumption are related to the efficiency and cost of smart contract operation; contract type follows the corresponding specific interface specification; and contract status and storage usage reflect the state changes and resource usage of the contract during operation.
[0051] Furthermore, in order to remove redundant information in the behavioral data, retain the essential information of the data, and improve the quality and effectiveness of the data, historical behavioral data is obtained from the smart contract transaction log, and the principal component matrix is obtained by principal component analysis after preprocessing.
[0052] Specifically, preprocessing includes: removing abnormal data, interpolating or filling missing values, mapping contract types and contract states in historical behavior data to integer values, extracting periodic features of transaction time, converting them to seconds, and mapping them to sine and cosine values to preserve their periodicity; mean-centering and standardizing transaction amounts, GAS limits, GAS consumption, and storage usage to ensure consistent dimensionality of features.
[0053] Based on the preprocessed historical data, the eigenvalues and corresponding eigenvectors of the covariance matrix are calculated. The eigenvalues are sorted from large to small and the minimum number of eigenvalues m when the cumulative variance contribution reaches the threshold is calculated. The eigenvectors corresponding to the first m eigenvalues are selected according to the minimum number of eigenvalues m to form the principal component matrix.
[0054] Furthermore, the new behavioral data at each moment in the smart contract transaction log is obtained and preprocessed as new data. The new data is standardized using the mean and standard deviation of the historical behavioral data. The standardized new data is multiplied by the principal component matrix to obtain the reduced dimensionality data as the key behavioral features of the new data.
[0055] It should be noted that this embodiment comprehensively considers the dynamic operation characteristics and static code characteristics of smart contracts, integrates key behavioral features with the embedding matrix of smart contracts in the level classification model, learns the correlation between the two, and analyzes the degree of impact on the operation of smart contracts.
[0056] The level classification model consists of a fusion layer and a multi-layer perceptron. The fusion layer receives the key behavioral features and the embedding matrix of the smart contract graph, outputs the fusion vector to the multi-layer perceptron, and the multi-layer perceptron outputs the probability distribution of the degree of impact of the fusion vector on the operation of the smart contract.
[0057] The fusion layer projects the key behavior features into a query vector using the following formula, projects the embedding matrix of the smart contract graph into a key matrix and a value matrix, and outputs a fusion vector using the cross-attention mechanism:
[0058] ,
[0059] in, Indicates time The key behavioral characteristics of Dimensions that represent key behavioral characteristics, represents the embedding matrix of the smart contract graph, Represents the number of nodes in the smart contract graph, represents the dimension of the node embedding vector; represents the attention output dimension; 、 and Represent query weight, key weight and value weight respectively; 、 and denote the query vector, key matrix, and value matrix respectively; is a hollow R, representing the set of all real numbers, and the logo in the upper right corner is used to specify the dimension of the vector or matrix; for example, Represents the query vector Every element of is a real number, and it is a dimensional vector; Indicates the query weight for OK A matrix with 1 column and real elements.
[0060] The fusion vector is generated by the following formula:
[0061] ,
[0062] in, Indicates time The fusion vector.
[0063] Furthermore, the fusion vector at each moment is fed into a multi-layer perceptron, which outputs the classification result at each moment. The classification result is output as a probability distribution of the smart contract operation level in the form of probability, representing the degree of impact of the fusion vector on the smart contract operation. The smart contract operation levels include: very high, high, medium, low, and very low. The higher the level, the more normal the operation.
[0064] The dynamic key behavioral features in this step reflect the performance of the smart contract during actual operation, and the static graph embedding matrix represents information such as the structure and semantics of the smart contract code. The fusion of dynamic and static data effectively improves the accuracy of level classification.
[0065] S3. Sequence data of key behavior features and classification results are constructed according to the length of the time window. At the same time, they are input into the prediction model to obtain the predicted behavior features of the next moment, and then compared with the key behavior features of the next moment for similarity. If the similarity is less than the similarity threshold, the smart contract will be abnormal.
[0066] It should be noted that the key behavior features at each moment correspond to classification results and are constructed according to the time window length and the same time series. After construction, they are simultaneously passed to the prediction model to obtain the predicted behavior features for the next moment. According to the method for obtaining the key behavior features at each moment from the smart contract transaction log in step S2, the actual key behavior features at the next moment are obtained. The similarity between the actual key behavior features and the predicted behavior features is calculated. If the calculated similarity exceeds the similarity threshold, the smart contract is operating normally; otherwise, the smart contract has an abnormality.
[0067] The prediction model in this embodiment adopts a dual-branch LSTM model. Two independent LSTM branches process the sequence data of key behavioral features and classification results respectively, while capturing the dynamic changes of transaction conditions over time and the changing trends of the smart contract operation status over time. The hidden states of the two LSTM branches are integrated to provide richer information. Finally, the integrated hidden states are mapped to the key behavioral feature space through a fully connected layer to obtain the predicted behavioral features at the next moment, so that the model can better adapt to the complex dynamic changes during the operation of smart contracts.
[0068] It should be noted that if Figure 2 As shown in Figure 2, the level classification model in step S2 and the prediction model in step S3 are obtained through joint training. During the joint training process, the classification loss is calculated using the cross entropy loss function, and the prediction loss is calculated using the mean squared error. The weighted summation is used to obtain the total loss. All parameters of the level classification model and the prediction model are updated by minimizing the total loss.
[0069] Specifically, during joint training, the historical time series is divided into multiple window samples according to the length of the time window. Each window sample contains the historical key behavioral features of multiple moments, the true target of the next moment, and the classification label. Each batch contains multiple window samples, and different window samples in the same batch share the embedding matrix of the smart contract graph. When calculating the total loss, the classification loss is calculated for each moment in each window sample in each batch, and the prediction loss is calculated for each window sample in each batch.
[0070] Specifically, the historical time series in the smart contract log is: , T represents the total time step. The historical time series is divided according to the length of the sliding time window to obtain multiple window samples. Multiple historical key behavior features in window samples , , the historical key behavior features at each moment also correspond to classification labels, which are used to calculate classification losses; each window sample is based on the data at the last moment Select the key historical behavior features of the next moment , as the true value corresponding to the window sample, used to calculate the prediction loss.
[0071] Furthermore, joint training is performed in batches, where each batch contains B window samples and each window sample contains Key historical behavioral characteristics (from arrive ), different window samples in the same batch share the embedding matrix of the smart contract graph. The probability distribution corresponding to the historical key behavior features at each moment output by the level classification model is constructed as sequence data of the same length as the window sample ,and Pass them to the prediction model together.
[0072] The classification loss is calculated for each moment in each window sample in each batch , the formula is as follows:
[0073] ,
[0074] in, and Respectively represent In the window sample The classification labels of the historical key behavioral features at each moment and the predicted classification labels, represents the cross entropy loss function.
[0075] Calculate the prediction loss for each window sample in each batch , the formula is as follows:
[0076] ,
[0077] in, and Respectively represent The true value and predicted value corresponding to the window sample; represents the mean squared error loss function.
[0078] Furthermore, the total loss of joint training Calculated by the following formula:
[0079] ,
[0080] in, Represents the weight of the classification loss.
[0081] When the joint training is completed, the trained level classification model and prediction model are obtained, and the fusion layer of the level classification model 、 and Since the embedding matrix of the smart contract graph does not change over time, during implementation, only step S1 needs to be executed once to obtain the embedding matrix of the smart contract graph. After that, the key matrix required for the cross attention mechanism in the fusion layer can be calculated Sum Matrix , to improve computational efficiency. When the smart contract code is updated, re-execute step S1 to update the smart contract graph and its embedding matrix, and re-train the joint training to update the key matrix Sum Matrix .
[0082] Compared with existing technologies, this embodiment provides a smart contract security audit method based on a neural network model. It comprehensively considers the dynamic operation characteristics and static code characteristics of smart contracts, uses dynamic key behavioral characteristics to reflect the performance of smart contracts in the actual operation process, and uses a static graph embedding matrix to represent information such as the structure and semantics of the smart contract code. By integrating dynamic and static data, it can promptly detect abnormal states of smart contracts, thereby improving the accuracy of smart contract security audits and enhancing system security. The level classification model is used to identify the operation level of the smart contract, which is used as the input of one branch of the prediction model to capture the changing trend of the smart contract operation status over time. Another branch of the prediction model is used to capture the dynamic changes of transaction status over time. Through comprehensive consideration of multiple branches, it provides richer information, helps to more accurately predict the behavioral characteristics of the smart contract at future moments, and enables the model to better adapt to the complex dynamic changes during the operation of the smart contract.
[0083] Example 2
[0084] Another embodiment of the present invention discloses a smart contract security audit system based on a neural network model, thereby realizing a smart contract security audit method based on a neural network model in Example 1. The specific implementation of each module refers to the corresponding description in Example 1. Figure 3 As shown, the system includes:
[0085] The code analysis module 101 is used to analyze the smart contract code to obtain a smart contract graph; the smart contract graph is input into the graph attention network to obtain an embedding matrix of the smart contract graph;
[0086] A level classification module 102 is configured to obtain key behavioral features at each moment based on the smart contract transaction log, and input them into a level classification model along with the embedding matrix of the smart contract graph to obtain a classification result at each moment;
[0087] The security audit module 103 is used to construct sequence data of key behavior features and classification results according to the length of the time window, and at the same time input the prediction model to obtain the predicted behavior features of the next moment, and then compare the similarity with the key behavior features of the next moment. If the similarity is less than the similarity threshold, the smart contract will be abnormal.
[0088] Since the present embodiment of a smart contract security audit system based on a neural network model and the aforementioned smart contract security audit method based on a neural network model share similarities and can be mutually referenced, the descriptions herein are redundant and will not be repeated here. Since the present system embodiment and the aforementioned method embodiment share the same principles, the present system embodiment also has the corresponding technical effects of the aforementioned method embodiment.
[0089] Those skilled in the art will appreciate that all or part of the process steps of the above-described embodiments can be implemented by instructing related hardware through a computer program, and the program can be stored in a computer-readable storage medium, such as a magnetic disk, an optical disk, a read-only memory, or a random access memory.
[0090] The above description is only a preferred specific embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any changes or substitutions that can be easily thought of by any technician familiar with this technical field within the technical scope disclosed by the present invention should be covered by the scope of protection of the present invention.
Claims
1. A smart contract security audit method based on a neural network model, characterized in that: The following steps are involved: Analyze the smart contract code to obtain a smart contract graph; pass the smart contract graph into the graph attention network to obtain an embedding matrix of the smart contract graph; The key behavioral features at each moment are obtained based on the smart contract transaction log, and are respectively input into the level classification model with the embedding matrix of the smart contract graph to obtain the classification result at each moment; the level classification model sequentially includes a fusion layer and a multi-layer perceptron. The fusion layer receives the key behavioral features and the embedding matrix of the smart contract graph, and outputs the fusion vector to the multi-layer perceptron. The multi-layer perceptron outputs the probability distribution of the smart contract operation level; Sequence data of key behavior features and classification results are constructed separately according to the length of the time window, and simultaneously input into the prediction model to obtain the predicted behavior features of the next moment, which are then compared with the key behavior features of the next moment for similarity. If the similarity is less than the similarity threshold, an abnormality occurs in the smart contract. The prediction model adopts a dual-branch LSTM model, which processes the sequence data of key behavior features and classification results respectively through two independent LSTM branches, fuses the hidden states of the two LSTM branches, and maps the fused hidden states to the key behavior feature space through a fully connected layer to obtain the predicted behavior features of the next moment.
2. The smart contract security audit method based on the neural network model according to claim 1 is characterized in that: The fusion layer projects the key behavior features into a query vector, projects the embedding matrix of the smart contract graph into a key matrix and a value matrix, and outputs a fusion vector using a cross-attention mechanism.
3. The smart contract security audit method based on the neural network model according to claim 1 is characterized in that: The key behavioral features are obtained by performing principal component analysis on the historical behavioral data in the smart contract transaction log to obtain a principal component matrix, and based on the principal component matrix, the key behavioral features of the new behavioral data at each moment in the smart contract transaction log are obtained; The behavioral data includes: transaction amount, transaction time, GAS limit, GAS consumption, contract type, contract status and storage usage.
4. The smart contract security audit method based on the neural network model according to claim 1 is characterized in that: Analyzing the smart contract code to obtain the smart contract graph includes: Convert the smart contract code into an abstract syntax tree, obtain key functions and key variables as nodes according to the abstract syntax tree; obtain the control flow of the key function and the data flow of the key variable as edges; A node feature matrix is constructed by extracting the attributes of key functions and key variables; a node adjacency matrix is constructed based on nodes and edges; and the node feature matrix and the node adjacency matrix constitute a smart contract graph.
5. The smart contract security audit method based on the neural network model according to claim 4 is characterized in that: The graph attention network sequentially includes an embedding layer and multiple graph attention layers; the embedding layer converts the node feature matrix in the smart contract graph into a high-dimensional embedding matrix through linear transformation and passes it to multiple graph attention layers. Each of the multiple graph attention layers includes multiple attention heads. Each attention head calculates the attention weight based on the high-dimensional embedding matrix and the node adjacency matrix, and then updates the embedding vector of each node. The multiple heads are spliced together for use by the next layer. The last layer obtains the embedding vector of each node by averaging the outputs of multiple attention heads to form the embedding matrix of the smart contract graph.
6. The smart contract security audit method based on the neural network model according to claim 1 is characterized in that: The level classification model and prediction model are obtained through joint training; during the joint training process, the classification loss is calculated using the cross entropy loss function, and the prediction loss is calculated using the mean square error and then weighted summed to obtain the total loss, and all parameters of the level classification model and the prediction model are updated by minimizing the total loss.
7. The smart contract security audit method based on the neural network model according to claim 6 is characterized in that: During the joint training, the historical time series is divided into multiple window samples according to the length of the time window. Each window sample contains historical key behavior features and their classification labels at multiple moments, as well as historical key behavior features at the next moment. Each batch contains multiple window samples, and different window samples in the same batch share the embedding matrix of the smart contract graph. When calculating the total loss, the classification loss is calculated for each moment in each window sample in each batch, and the prediction loss is calculated for each window sample in each batch.
8. A smart contract security audit system based on a neural network model, characterized in that: include: Code analysis module, used to analyze smart contract code to obtain smart contract graph; Passing the smart contract graph into the graph attention network to obtain the embedding matrix of the smart contract graph; A level classification module is used to obtain key behavioral features at each moment based on the smart contract transaction log, and input them into the level classification model along with the embedding matrix of the smart contract graph to obtain the classification result at each moment. The level classification model sequentially includes a fusion layer and a multi-layer perceptron. The fusion layer receives the key behavioral features and the embedding matrix of the smart contract graph, and outputs a fusion vector to the multi-layer perceptron. The multi-layer perceptron outputs a probability distribution of the smart contract operation level. The security audit module is used to construct sequence data of key behavior features and classification results according to the length of the time window, and simultaneously input them into the prediction model to obtain the predicted behavior features of the next moment, and then compare the similarity with the key behavior features of the next moment. If the similarity is less than the similarity threshold, the smart contract will be abnormal. The prediction model adopts a dual-branch LSTM model, which processes the sequence data of key behavior features and classification results respectively through two independent LSTM branches, fuses the hidden states of the two LSTM branches, and maps the fused hidden states to the key behavior feature space through a fully connected layer to obtain the predicted behavior features of the next moment.
Citation Information
Patent Citations
Intelligent contract similarity retrieval method and system based on stack instruction sequence
CN111460454A
Method and device for determining compiler version of smart contract, equipment and medium
CN116401156A