Intelligent contract data analysis method and system based on block chain
By integrating the preprocessing and analysis of blockchain network data, off-chain data, user information data and network environment data in the smart contract data analysis method, dynamically adjusting optimization parameters, solving the problems of data authenticity, integrity and real-time in smart contract data analysis, real-time monitoring and optimization of smart contract performance is achieved.
Patent Information
- Application Number
- CN202411563216.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-11-05
- Publication Date
- 2025-03-18
- Estimated Expiration
- 2044-11-05
AI Technical Summary
The existing smart contract data analysis methods and systems lack effective mechanisms to ensure the authenticity, integrity and real-timeness of data. Especially in the dynamically changing network conditions in the blockchain network environment, optimization parameters cannot be flexibly adjusted, resulting in a degradation of processing performance.
A blockchain-based smart contract data analysis method is proposed. By collecting and preprocessing blockchain network data, off-chain data, user information data and network environment data, analyzing the impact of network environment feature data sets on blockchain network feature data sets and user feature data sets, weighted fusion, training smart contract performance prediction model and optimization detection model, dynamically adjusting parameters such as verification times, shard count and weight factor.
Real-time monitoring and optimization of smart contract performance is realized, parameters can be adjusted dynamically according to real-time network conditions, avoid waste of computing resources, and improve the accuracy and comprehensiveness of processing performance and data analysis.
Smart Images

Figure CN119646428A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of blockchain technology, and more specifically, to a blockchain-based smart contract data analysis method and system. Background Art
[0002] With the rapid development of blockchain technology, smart contracts, as a self-executing protocol, have been widely used in finance, supply chain, Internet of Things and other fields. Smart contracts can automatically execute instructions with preset conditions, reduce human intervention and improve the transparency and security of transactions. However, the complexity and immutability of smart contract data bring challenges to data analysis.
[0003] The patent application with the publication number CN113449034A discloses a smart contract data security management method, system and storage medium based on the blockchain network, including synchronously storing the public key information in the asymmetric public and private keys into the smart contract when generating the smart contract; triggering the data management request, establishing the blockchain network communication, calling the smart contract to generate the verification data, and giving the verification data timeliness management, then transmitting it back to the data management request end and calling the private key, signing the verification data, recombining it with the data to be managed and sending it to the smart contract for verification, and performing matching management operations on the data to be managed according to the verification results; the present invention solves the problem of data changes caused by malicious attacks on contract data due to contract disclosure or other security vulnerabilities, effectively ensuring the security of the data on the chain, and has practical value in a real sense.
[0004] Existing smart contract data analysis methods and systems lack effective mechanisms to ensure the authenticity, integrity and real-time nature of data, and have the following main problems:
[0005] In the blockchain network environment, factors such as network conditions and node performance will change dynamically. If the system fails to consider dynamically adjusting and optimizing parameters such as the number of verifications and the number of shards, it may use a fixed strategy for processing, resulting in unnecessary verification and calculation when the network conditions are good, causing a waste of computing resources. Fixed parameter settings cannot adapt to real-time changes in the network environment, especially when the blockchain network environment fluctuates greatly. The system cannot flexibly adjust the optimization parameters, resulting in a decrease in processing performance.
[0006] Considering only a single or a few factors for evaluation may not accurately reflect the overall performance of the smart contract; without introducing dynamic changes in time points, it is impossible to timely identify performance fluctuations of the contract at different execution stages; during the execution of the contract, the opportunity to discover and solve problems may be missed, and the performance under different conditions cannot be dynamically adjusted or optimized, which limits the use of smart contracts in different application scenarios, especially under high load or complex scenarios, which may cause system crashes or significant performance degradation.
[0007] In view of this, the present invention proposes a blockchain-based smart contract data analysis method and system to solve the above problems. Summary of the invention
[0008] In order to overcome the above-mentioned defects of the prior art and to achieve the above-mentioned purpose, the present invention provides the following technical solution: a smart contract data analysis method based on blockchain, comprising:
[0009] S1. Collect blockchain network data, off-chain data, user information data and network environment data;
[0010] S2. Preprocess the acquired blockchain network data, off-chain data, user information data, and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set, and a network environment feature data set;
[0011] S3. Analyze the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain an impact feature dataset; perform weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset and the user feature dataset to obtain a comprehensive feature dataset;
[0012] S4. Obtain a smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model;
[0013] S5. Compare the predicted smart contract performance index with the preset smart contract performance index threshold to determine whether the smart contract performance meets the standard; if it meets the standard, continuously monitor the execution of the smart contract; if it does not meet the standard, issue a warning message through the smart contract control terminal, automatically generate a warning instruction, and collect the execution data of the smart contract that does not meet the standard;
[0014] S6. Obtain a smart contract optimization detection model based on the execution data of substandard smart contracts, and predict the optimization type of the smart contract through the smart contract optimization detection model; select the corresponding personalized smart contract optimization strategy based on the predicted smart contract optimization type.
[0015] Furthermore, the blockchain network data includes transaction record data, block information data and smart contract data; the transaction record data includes transaction hash, initiator address, recipient address, transaction amount and gas fee; the block information data includes block height, previous block hash and transaction quantity; the smart contract data includes contract address, contract ABI and contract status;
[0016] The off-chain data includes market prices, market transaction volumes, and number of comments related to smart contracts; the user information data includes user behavior data and user identity information data;
[0017] User behavior data includes the user's browsing volume and transaction time in decentralized applications; user identity information data includes the user's digital signature, authentication time and account address; the network environment data includes network communication delay, network bandwidth and packet loss rate during data transmission.
[0018] Furthermore, the method of preprocessing the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set includes:
[0019] S31. Preprocessing of transaction record data in blockchain network data:
[0020] S311. Use the local database provided by the blockchain node Ethereum to process the transaction hash, store the transaction data through the LevelDB in the Ethereum node, and the user queries the transaction hash through the JSON-RPC interface;
[0021] S312, record the initiator address as A se , let the receiver's address be A re , use the hash processing formula to process the initiator address A se and the recipient address A re Unify the format;
[0022] Sort the hashed address set in ascending order. Let the sorted address set be {A′ (1) ,A′ (2) ,...,A′ (m)}; where m is the number of addresses after sorting; A′ (1) is the first hash address after sorting; remove adjacent duplicate addresses from the sorted set in sequence;
[0023] Preset q shards and k hash functions, use the hash function to assign the hashed addresses to different shards, for each address A′ in the deduplicated address set u (a) , calculate its fragment number;
[0024] The preset number of shards q is dynamically adjusted by the shard number adjustment formula, and the shard number adjustment formula is: Where m is the number of sorted addresses; k is the number of types of hash functions; is the rounding function;
[0025] For each hash address A′ (a) , store it in the corresponding hash table according to its shard number, and check each address A′ (a) Check whether the shard number is already in the hash table. If not, add it to the hash table and merge the deduplication results in all shards into the final deduplication address set;
[0026] S313, the sum of the transaction amounts of all users in the entire period is calculated to obtain the total transaction amount S of all users, and the total transaction amount S of all users is divided by the total number of transactions M in the entire period to obtain the average transaction amount of each user in the entire period;
[0027] The volatility of transaction amounts is measured by calculating the standard deviation of transaction amounts;
[0028] S314. Count the total transaction amount within the L-period, divide the total transaction amount within the L-period by the total number of transactions M within the statistical period, and obtain the average gas fee of the user within the L-period;
[0029] S32. Preprocessing of block information data in blockchain network data:
[0030] S321. Arrange the block heights in ascending order by quick sorting, and verify whether the block heights are continuous by checking the continuity condition;
[0031] S322, for each block D c , the block hash value is preset to h′ c , the hash value of the previous block is h′ c -1, verify the hash value h′ of the previous block c -1 is equal to the hash value of the previous block calculated by the hash function;
[0032] S323. The number of block verifications is adjusted by dynamically adjusting the verification formula, wherein the dynamic adjustment verification formula is: Among them, T(m′,h c ) is the number of block verifications; k′ is the block verification interval; ε is the error control parameter; h c is the height of the cth block; c is the block number;
[0033] S324. Use the Pandas library in Python, a data analysis tool, to count the number of transactions in each block, and calculate the average transaction volume, maximum value, and minimum value of each block through the aggregation function in the Pandas library;
[0034] S33. Preprocessing of smart contract data in blockchain network data:
[0035] S331. Record the number of transactions of the initiator address in the blockchain as the transaction nonce. Encode the initiator address and the transaction nonce through RLP encoding, and then calculate the contract address through the hash function H.
[0036] S332. Use the JSON parser to read and parse the ABI data, use the ABI verification tool Truffle blockchain development framework to verify the ABI, check whether the ABI meets the standard format requirements, and use the Python script to filter invalid or damaged ABI data;
[0037] S333. Use MySQL database to classify contract status into different status types, including active, destroyed and frozen types; define the event log of smart contract through Solidity language, and use the event log of smart contract Web3.js to monitor the change of contract status;
[0038] S34. Preprocessing of off-chain data: Obtain the market price, market transaction volume, and number of comments related to the smart contract in real time through the exchange's REST API, and use Python's Pandas library to convert the market price into a non-negative floating point number, and convert the market transaction volume and number of comments into a non-negative integer;
[0039] The market price is converted into a time series format using the functions in the Pandas library, and the average, maximum, and minimum values of the market transaction volume and number of comments are calculated using aggregation functions;
[0040] S35. Preprocessing of user behavior data in user information data: using SQL in MySQL database to query the number of views of users in decentralized applications, using Python's Pandas library to convert the number of views of users in decentralized applications into non-negative integers, and using functions in the Pandas library to uniformly format transaction time into a standard time format;
[0041] S36. Preprocessing the user identity information data in the user information data: generating a unique identifier through a hash function H, obtaining the user's digital signature, using a function in the Pandas library to uniformly format the authentication time into a standard time format, and verifying the format of the account address through the Ethereum address;
[0042] S37. Preprocessing of network environment data:
[0043] S371. It is assumed that the entire blockchain network has v blockchain nodes, and the communication delay between each blockchain node g and other blockchain nodes is T ly,g , the average communication delay of the entire blockchain network is calculated as; the communication delay between blockchain node g and other blockchain nodes is T ly,gObtained through delay calculation formula;
[0044] S372. Preset the bandwidth of each blockchain node to J v ,The bandwidth of the entire blockchain network is calculated using the harmonic mean formula;
[0045] S373. Obtain the total number of data packets sent and the number of data packets successfully received by each blockchain node g in real time through the REST API of the exchange; for each blockchain node g, calculate the packet loss rate of a single blockchain node through the packet loss rate calculation formula;
[0046] Different weights are assigned to the packet loss rate of each blockchain node g, and the weighted average packet loss rate of the entire blockchain network is calculated; the weight factor γg of each blockchain node g is dynamically adjusted through the weight factor adjustment formula;
[0047] The weight factor adjustment formula is: Among them, γ′ g is the weight factor of each blockchain node g after adjustment; T ly,gf is the communication delay from blockchain node g to blockchain node f; T ly,fg is the communication delay from blockchain node f to blockchain node g; v is the number of blockchain nodes;
[0048] S38. Use the LOF algorithm to identify outliers on the processed blockchain network data, off-chain data, user information data, and network environment data, and remove the identified outliers to obtain the processed blockchain network feature data set, off-chain feature data set, user feature data set, and network environment feature data set;
[0049] The obtained blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are normalized by standard deviation and converted into standard normal distribution, and finally the normalized blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are obtained.
[0050] Furthermore, the method of analyzing the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain the impact feature dataset includes:
[0051] Taking network environment characteristics, blockchain network characteristics and user characteristics as input variables, a joint regression model is constructed. By constructing a joint regression model, the impact of the network environment characteristic dataset on the blockchain network characteristic dataset and the user characteristic dataset is analyzed, and finally the affected characteristic dataset is obtained.
[0052] Furthermore, the method of weightedly fusing the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset, and the user feature dataset to obtain a comprehensive feature dataset includes:
[0053] The impact feature dataset, blockchain network feature dataset, off-chain feature dataset and user feature dataset are fused through a weighted model to obtain a comprehensive feature dataset.
[0054] Furthermore, the training method of the smart contract performance prediction model includes:
[0055] Divide the dataset into training set, validation set and test set, train the model and evaluate the model performance; the sample set is a subset of the dataset, each sample set includes a historical comprehensive feature dataset and the corresponding smart contract performance indicators; build a smart contract performance prediction model, which includes an input layer, a hidden layer and an output layer; the hidden layer uses the ReLU activation function;
[0056] The input layer of the model is used to input the historical comprehensive feature data set, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature data set; the output layer of the model is used to output the smart contract performance index, and the number of neurons in the output layer corresponds to the number of prediction targets, and the prediction value is output through one neuron; the smart contract performance prediction model is a fully connected neural network model;
[0057] Use the coefficient of determination to evaluate the difference between the smart contract performance indicators predicted by the model and the actual smart contract performance indicators;
[0058] Use the training set to train the smart contract performance prediction model, and update the model parameters through the back-propagation algorithm to minimize the loss function; use the validation set to evaluate the performance of the smart contract performance prediction model through the determination coefficient;
[0059] The Adam optimization algorithm is used as the optimizer. The model is tuned according to the performance feedback of the validation set. The model parameters are adjusted until the performance is no longer significantly improved or the preset number of iterations is reached.
[0060] Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract performance prediction model to predict the current comprehensive feature data set to obtain the smart contract performance indicators.
[0061] Furthermore, the method of comparing the predicted smart contract performance indicator with the preset smart contract performance indicator threshold to determine whether the smart contract performance meets the standard includes:
[0062] If the predicted smart contract performance index is greater than or equal to the preset smart contract performance index threshold, the smart contract performance is judged to be up to standard;
[0063] If the predicted smart contract performance indicator is less than the preset smart contract performance indicator threshold, the smart contract performance is judged to be substandard.
[0064] Furthermore, the training method of the smart contract optimization detection model includes:
[0065] The substandard smart contract execution data includes the number of repeated code segments in the smart contract, the number of failed smart contract executions, the time required for smart contract execution, and the frequency of errors that occur in smart contract execution;
[0066] The data set is divided into training set, validation set and test set to train the model and evaluate the model performance; the sample set is a subset of the data set, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract;
[0067] The input data of the model is the historical execution data of smart contracts that did not meet the standards; the output label of the model is the optimization type of the smart contract; the smart contract optimization detection model consists of v decision trees. Through Bootstrap sampling, when training each decision tree, a subset is randomly selected from the training set to train the tree, and a subset of features is randomly selected to split the node until the stopping condition is reached; the smart contract optimization detection model is a random forest model;
[0068] Use multi-classification cross entropy as the loss function of the model to measure the difference between the model's predicted value and the actual value;
[0069] Use the training set to train the smart contract optimization detection model, and use the back-propagation algorithm to update the model parameters to minimize the loss function; use the validation set to evaluate the performance of the smart contract optimization detection model by calculating the precision index;
[0070] Adopt the random search hyperparameter optimization method, tune the hyperparameters of the smart contract optimization detection model according to the performance feedback of the validation set, and adjust the model hyperparameter combination until the performance of the model is no longer significantly improved or reaches the preset stopping condition;
[0071] Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract optimization detection model to predict the current substandard smart contract execution data to obtain the optimization type of the smart contract.
[0072] Furthermore, the method of selecting a corresponding personalized smart contract optimization strategy according to the predicted smart contract optimization type includes:
[0073] The optimization strategy of the smart contract optimization type is analyzed through the smart contract performance evaluation model, and the smart contract performance score is calculated according to the smart contract performance evaluation model. The smart contract performance evaluation model is:
[0074] ; Where P is the smart contract performance score; N′ dup N′ is the number of repeated code segments in the smart contract; tal is the total number of code segments in the smart contract; F fal is the number of failed smart contract executions; t is a time point at a certain moment in the smart contract execution process; T ec The time required for smart contract execution; F err is the error frequency in the execution of smart contracts; δ1 is the weight factor for the number of repeated code segments in the smart contract; δ2 is the weight factor for the number of failed smart contract executions; δ3 is the weight factor for the time required for smart contract execution; δ4 is the weight factor for the error frequency in the execution of smart contracts;
[0076] The preset smart contract performance index threshold is divided into low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L ; Compare the calculated smart contract performance score P with the low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L Make a comparison;
[0077] If P<P S , then the smart contract optimization type is determined to be a low-level type, and the smart contract control terminal issues a first-level optimization instruction and automatically generates a low-level smart contract optimization strategy;
[0078] If P S ≤P<P M , then the smart contract optimization type is determined to be intermediate type, and the smart contract control terminal issues a secondary optimization instruction and automatically generates an intermediate type smart contract optimization strategy;
[0079] If P M ≤P<P L , the smart contract optimization type is determined to be advanced type, and the smart contract control terminal issues a third-level optimization instruction to automatically generate an advanced type smart contract optimization strategy.
[0080] A blockchain-based smart contract data analysis system, comprising:
[0081] Data collection module, used to collect blockchain network data, off-chain data, user information data and network environment data;
[0082] The data processing module is used to pre-process the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set;
[0083] The data analysis module analyzes the impact of the network environment feature data set on the blockchain network feature data set and the user feature data set to obtain the impact feature data set; performs weighted fusion on the impact feature data set, the blockchain network feature data set, the off-chain feature data set and the user feature data set to obtain the comprehensive feature data set;
[0084] The smart contract performance prediction module is used to obtain the smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model;
[0085] The smart contract performance evaluation module is used to compare the predicted smart contract performance indicators with the preset smart contract performance indicator thresholds to determine whether the smart contract performance meets the standards; if it meets the standards, the execution of the smart contract is continuously monitored; if it does not meet the standards, an early warning message is issued through the smart contract control terminal, an early warning instruction is automatically generated, and the execution data of the smart contract that does not meet the standards is collected;
[0086] The smart contract performance optimization module is used to obtain a smart contract optimization detection model based on the training of the substandard smart contract execution data, and predict the optimization type of the smart contract through the smart contract optimization detection model; according to the predicted smart contract optimization type, the corresponding personalized smart contract optimization strategy is selected;
[0087] The technical effects and advantages of the blockchain-based smart contract data analysis method and system of the present invention are as follows:
[0088] By using targeted methods to pre-process different types of data (blockchain network data, off-chain data, user information data, network environment data), we ensure the accuracy and consistency of the data; by using algorithms such as hash functions, sharding technology, quick sorting and harmonic mean, we improve the processing efficiency. In response to the dynamic changes in the blockchain network environment, we use dynamic adjustment formulas to optimize parameters such as the number of verifications, the number of shards, and the weight factor, which helps to make flexible adjustments based on real-time network conditions and avoid excessive waste of computing resources;
[0089] The smart contract performance evaluation model takes into account multiple key factors that affect the performance of smart contracts, such as the number of repeated code segments, the number of execution failures, the execution time, and the error frequency. The overall performance of smart contracts is evaluated through multiple dimensions to ensure the comprehensiveness and accuracy of the evaluation results; the weighted sum of various influencing factors can accurately quantify the contribution of each factor to the performance of smart contracts, and then derive the performance score, which is convenient for optimization of specific problems; the model introduces changes in time points during the execution of smart contracts, and can dynamically capture the performance changes of contracts at different execution stages, especially in terms of execution time and error frequency, so that fluctuations in contract performance can be identified in a timely manner and real-time optimization suggestions can be provided. BRIEF DESCRIPTION OF THE DRAWINGS
[0090] Figure 1 This is a flowchart of a smart contract data analysis method based on blockchain of the present invention;
[0091] Figure 2 This is a schematic diagram of the structure of a blockchain-based smart contract data analysis system of the present invention. DETAILED DESCRIPTION
[0092] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0093] Example 1
[0094] See also Figure 1 and Figure 2 As shown, this embodiment provides a smart contract data analysis method based on blockchain, including:
[0095] S1. Collect blockchain network data, off-chain data, user information data and network environment data;
[0096] S2. Preprocess the acquired blockchain network data, off-chain data, user information data, and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set, and a network environment feature data set;
[0097] S3. Analyze the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain an impact feature dataset; perform weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset and the user feature dataset to obtain a comprehensive feature dataset;
[0098] S4. Obtain a smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model;
[0099] S5. Compare the predicted smart contract performance index with the preset smart contract performance index threshold to determine whether the smart contract performance meets the standard; if it meets the standard, continuously monitor the execution of the smart contract; if it does not meet the standard, issue a warning message through the smart contract control terminal, automatically generate a warning instruction, and collect the execution data of the smart contract that does not meet the standard;
[0100] S6. Obtain a smart contract optimization detection model based on the execution data of substandard smart contracts, and predict the optimization type of the smart contract through the smart contract optimization detection model; select the corresponding personalized smart contract optimization strategy based on the predicted smart contract optimization type.
[0101] Blockchain network data includes transaction record data, block information data and smart contract data; transaction record data includes transaction hash, initiator address, recipient address, transaction amount and gas fee; block information data includes block height, previous block hash and transaction quantity; smart contract data includes contract address, contract ABI and contract status;
[0102] Off-chain data includes market prices, market transaction volumes, and number of comments related to smart contracts; user information data includes user behavior data and user identity information data;
[0103] User behavior data includes the user's browsing volume and transaction time in decentralized applications; user identity information data includes the user's digital signature, authentication time and account address; network environment data includes network communication delay, network bandwidth and packet loss rate during data transmission.
[0104] The method of preprocessing the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set includes:
[0105] S31. Preprocessing of transaction record data in blockchain network data:
[0106] S311. Use the local database provided by the blockchain node Ethereum to process the transaction hash, store the transaction data through the LevelDB in the Ethereum node, and the user queries the transaction hash through the JSON-RPC interface;
[0107] S312, record the initiator address as A se , let the receiver's address be A re, use the hash processing formula to process the initiator address A se and the recipient address A re To unify the format, the hash processing formula is: A′ se =H(A se ), where H is the hash function; A′ se is the hashed initiator address; A′ re =H(A re ), where A′ re is the hashed recipient address;
[0108] For the hashed address set {A′1,A′2,...,A′ m} Sort them in ascending order, let the sorted address set be {A′ (1) ,A′ (2) ,...,A′ (m)}; where m is the number of addresses after sorting; A′ (1) is the first hash address after sorting;
[0109] Remove adjacent duplicate addresses from the sorted set in turn:
[0110] u={A′ (a) A′ (a) ≠A′ (a-1) ,a=2,3,...,m}∪{A′ (1)}; where a is the sorted address index; a=2,3,...,m means starting from the second element after sorting, checking whether the adjacent hash values are the same one by one; {A′ (a) A′ (a) ≠A′ (a-1) ,a=2,3,...,m} starts from the second hash address. If the current address is A′ (a) and the previous address A′ (a-1) If they are not equal, then A′ (a) Add to the set after deduplication; u is the set of addresses after deduplication; ∪ is the union;
[0111] Preset q shards and k hash functions, use the hash function to assign the hashed addresses to different shards, for each address A′ in the deduplicated address set u (a) , calculate its fragment number, the calculation formula is: Q(A′ (a) )=H(A′ (a) )modq;Q(A′ (a) ) is the address A′ (a) The fragment number of H(A′ (a) ) is the address A′ (a)The output of the applied hash function H; mod is the modulus operator; q is the preset number of shards;
[0112] The preset number of shards q is dynamically adjusted through the shard number adjustment formula. The shard number adjustment formula is: Where m is the number of sorted addresses; k is the number of types of hash functions; is the rounding function;
[0113] For each hash address A′ (a) , store it in the corresponding hash table according to its shard number, and check each address A′ (a) Check whether the shard number is already in the hash table. If not, add it to the hash table and merge the deduplication results in all shards into the final deduplication address set;
[0114] S313: Count the sum of the transaction amounts of all users in the entire period to obtain the total transaction amount S of all users, and divide the total transaction amount S of all users by the total number of transactions M in the entire period to obtain the average transaction amount per transaction of the users in the entire period. Where B is the transaction amount of each user; S is the total transaction amount of all users;
[0115] The volatility of the transaction amount is measured by calculating the standard deviation of the transaction amount. The standard deviation of the transaction amount is: Among them, σ B is the standard deviation of the transaction amount;
[0116] S314: Count the total transaction amount within the L-segment period The sum of the transaction amounts within the L period Divide by the total number of transactions M in the statistical period to get the average gas fee of the user in the L-segment period. The average gas fee of the user is: Among them, G avg is the average gas fee for the user;
[0117] S32. Preprocessing of block information data in blockchain network data:
[0118] S321. Arrange the block heights in ascending order by quick sorting. The preset block height set is: H′={h1,h2,...,h c ,...,h m′}; where H′ is the block height set; h c is the height of the cth block; m′ is the total number of blocks; c is the block number;
[0119] Verify whether the block height is continuous by checking the continuity condition. The continuity condition is: Among them, is the height of the c+1th block; It is a universal quantity symbol in mathematics, which means it is applicable to all block numbers c;
[0120] S322, for each block D c , the block hash value is preset to h′ c , the hash value of the previous block is h′ c -1, verify the hash value h′ of the previous block c -1 is equal to the hash value of the previous block calculated by the hash function to ensure the integrity of the chain structure of the blockchain, that is, to determine whether the conditions are met: Among them, H(D c-1 ) is the hash value of the c-1th block;
[0121] If h′ c-1 =H(D c-1 ), the link verification is successful; otherwise, the block D c The previous block hash points to an error, and the block is marked as abnormal;
[0122] S323. The number of block verifications is adjusted by dynamically adjusting the verification formula, wherein the dynamic adjustment verification formula is: Among them, T(m′,h c ) is the number of block verifications; k′ is the verification interval of the block; ε is the error control parameter, which is a small constant used to dynamically adjust the verification ratio;
[0123] If ε is a positive value, the number of verifications will decrease, allowing more blocks to be skipped; if ε is a negative value, more blocks will be verified; when ε=0, the formula degenerates into the basic verification interval strategy, that is, verification once every k′ blocks; when ε>0, the number of verified blocks decreases, and more blocks are skipped; conversely, when ε<0, the number of verified blocks increases;
[0124] For example, set the parameters: total number of blocks m′=1000, verification interval k′=10 (verification every 10 blocks), error control parameter ε=0.05;
[0125] Calculate the number of verifications:
[0126] For the first verification (i.e. c=1), the number of verifications calculated by the formula is: That is, during the first verification, 95 blocks need to be verified; as c increases: every k′ blocks, the formula will automatically adjust the verification frequency, and the dynamic control based on ε makes the number of verifications more flexible.
[0127] S324. Use the Pandas library in Python, a data analysis tool, to count the number of transactions in each block, and calculate the average transaction volume, maximum value, and minimum value of each block through the aggregation function in the Pandas library;
[0128] S33. Preprocessing of smart contract data in blockchain network data:
[0129] S331. The number of transactions of the initiator address in the blockchain is recorded as the transaction nonce. The initiator address and the transaction nonce are encoded by RLP encoding, and then the contract address is calculated by the hash function H.
[0130] S332. Use the JSON parser to read and parse the ABI data, use the ABI verification tool Truffle blockchain development framework to verify the ABI, check whether the ABI meets the standard format requirements, and use the Python script to filter invalid or damaged ABI data;
[0131] S333. Use MySQL database to classify contract status into different status types, including active, destroyed and frozen types; define the event log of smart contract through Solidity language, and use the event log of smart contract Web3.js to monitor the change of contract status;
[0132] S34. Preprocessing of off-chain data: Obtain the market price, market transaction volume, and number of comments related to the smart contract in real time through the exchange's REST API, and use Python's Pandas library to convert the market price into a non-negative floating point number, and convert the market transaction volume and number of comments into a non-negative integer;
[0133] The market price is converted into a time series format using the functions in the Pandas library, and the average, maximum, and minimum values of the market transaction volume and number of comments are calculated using aggregation functions;
[0134] S35. Preprocessing of user behavior data in user information data: using SQL in MySQL database to query the number of views of users in decentralized applications, using Python's Pandas library to convert the number of views of users in decentralized applications into non-negative integers, and using functions in the Pandas library to uniformly format transaction time into a standard time format;
[0135] S36. Preprocessing the user identity information data in the user information data: generating a unique identifier through a hash function H, obtaining the user's digital signature, using a function in the Pandas library to uniformly format the authentication time into a standard time format, and verifying the format of the account address through the Ethereum address;
[0136] S37. Preprocessing of network environment data:
[0137] S371. It is assumed that the entire blockchain network has v blockchain nodes, and the communication delay between each blockchain node g and other blockchain nodes is T ly,g , then the average communication delay of the entire blockchain network is: Among them, T avg_ly is the average communication delay of the entire blockchain network; v is the number of blockchain nodes;
[0138] The communication delay T between the blockchain node g and other blockchain nodes ly,g Obtained through the delay calculation formula, the delay calculation formula is: T ly,g =T tr,g +T pr,g +T qu,g ; Among them, T tr,g is the transmission delay of the data packet from the sender to the receiver; T pr,g T is the device processing delay; qu,g is the queuing delay of the data packet in the router;
[0139] S372. Preset the bandwidth of each blockchain node to J v , the bandwidth of the entire blockchain network is calculated using the harmonic mean formula: Among them, J ef The bandwidth of the entire blockchain network;
[0140] S373. Obtain the total number of data packets sent and the number of data packets successfully received by each blockchain node g in real time through the REST API of the exchange; for each blockchain node g, calculate the packet loss rate of a single blockchain node through the packet loss rate calculation formula;
[0141] The packet loss rate calculation formula is: Among them, P loss,g is the packet loss rate of a single blockchain node; N se,g N is the total number of data packets sent for each blockchain node g; re,g is the number of data packets successfully received by blockchain node g;
[0142] Assigning different weights to the packet loss rate of each blockchain node g, the weighted average packet loss rate of the entire blockchain network is: Among them, P wd_loss is the weighted average packet loss rate of the entire blockchain network; γ g is the weight factor of each blockchain node g;
[0143] The weight factor γ of each blockchain node g is adjusted by the weight factor formula gDynamic adjustment is performed, and the weight factor adjustment formula is: Among them, γ′ g is the weight factor of each blockchain node g after adjustment; T ly,gf is the communication delay from blockchain node g to blockchain node f; T ly,fg is the communication delay from blockchain node f to blockchain node g;
[0144] The larger the sum of the denominators in the formula, the more obvious the delay and bandwidth limitation of blockchain node g is; therefore, the weight γ′ of blockchain node g is g The smaller;
[0145] For example, suppose there are three blockchain nodes A, B, and C, and the communication latency and bandwidth between them are shown in the following table:
[0146]
[0147] Calculate the weight of blockchain node A:
[0148] Calculate the weight of blockchain node B:
[0149] Calculate the weight of blockchain node C:
[0150] According to the calculation results, blockchain node A has the highest weight, which means that in this network, blockchain node A has relatively good communication capability and efficiency, and is suitable for taking on more tasks in the network;
[0151] S38. Use the LOF algorithm to identify outliers on the processed blockchain network data, off-chain data, user information data, and network environment data, and remove the identified outliers to obtain the processed blockchain network feature data set, off-chain feature data set, user feature data set, and network environment feature data set;
[0152] The obtained blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are normalized by standard deviation and converted into standard normal distribution, and finally the normalized blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are obtained.
[0153] The method of analyzing the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain the impact feature dataset includes:
[0154] Taking network environment characteristics, blockchain network characteristics and user characteristics as input variables, a joint regression model is constructed. By constructing a joint regression model, the impact of the network environment characteristic dataset on the blockchain network characteristic dataset and the user characteristic dataset is analyzed, and finally the affected characteristic dataset is obtained.
[0155] Methods for weighting and fusing the impact feature dataset, blockchain network feature dataset, off-chain feature dataset, and user feature dataset to obtain a comprehensive feature dataset include:
[0156] The impact feature dataset, blockchain network feature dataset, off-chain feature dataset and user feature dataset are fused through a weighted model to form a comprehensive feature dataset. The impact feature dataset is recorded as E1, the blockchain network feature dataset is recorded as E2, the off-chain feature dataset is recorded as E3, and the user feature dataset is recorded as E4;
[0157] The weighted model is: WS=E1·ω1+E2·ω2+E3ω3+E4·ω4; where ω1 is the weight coefficient affecting the feature data set; ω2 is the weight coefficient of the blockchain network feature data set; ω3 is the weight coefficient of the off-chain feature data set; and ω4 is the weight coefficient of the user feature data set.
[0158] The training methods of smart contract performance prediction models include:
[0159] Divide the dataset into training set, validation set and test set, train the model and evaluate the model performance; the sample set is a subset of the dataset, each sample set includes a historical comprehensive feature dataset and the corresponding smart contract performance indicators; build a smart contract performance prediction model, which includes an input layer, a hidden layer and an output layer; the hidden layer uses the ReLU activation function;
[0160] The input layer of the model is used to input the historical comprehensive feature data set, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature data set; the output layer of the model is used to output the smart contract performance index, and the number of neurons in the output layer corresponds to the number of prediction targets, and the prediction value is output through one neuron; the smart contract performance prediction model is a fully connected neural network model;
[0161] Use the coefficient of determination to evaluate the difference between the smart contract performance indicators predicted by the model and the actual smart contract performance indicators;
[0162] The coefficient of determination is: in, The sum of squares of the differences between the smart contract performance indicators predicted by the model and the actual smart contract performance indicators; is the sum of the squares of the differences between the actual smart contract performance indicator and the average of all smart contract performance indicators; iis the actual performance indicator of the i-th smart contract; is the performance indicator of the i-th smart contract predicted by the model; is the average value of all smart contract performance indicators; n is the total number of smart contracts;
[0163] Use the training set to train the smart contract performance prediction model, and update the model parameters through the back-propagation algorithm to minimize the loss function; use the validation set to evaluate the performance of the smart contract performance prediction model through the determination coefficient;
[0164] The Adam optimization algorithm is used as the optimizer. The model is tuned according to the performance feedback of the validation set. The model parameters are adjusted until the performance is no longer significantly improved or the preset number of iterations is reached.
[0165] Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract performance prediction model to predict the current comprehensive feature data set to obtain the smart contract performance indicators.
[0166] The method of comparing the predicted smart contract performance index with the preset smart contract performance index threshold to determine whether the smart contract performance meets the standard includes:
[0167] If the predicted smart contract performance index is greater than or equal to the preset smart contract performance index threshold, the smart contract performance is judged to be up to standard;
[0168] If the predicted smart contract performance indicator is less than the preset smart contract performance indicator threshold, the smart contract performance is judged to be substandard.
[0169] The training methods for the smart contract optimization detection model include:
[0170] The substandard smart contract execution data includes the number of repeated code segments in the smart contract, the number of failed smart contract executions, the time required for smart contract execution, and the frequency of errors that occur in smart contract execution;
[0171] The data set is divided into training set, validation set and test set to train the model and evaluate the model performance; the sample set is a subset of the data set, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract;
[0172] The input data of the model is the historical execution data of smart contracts that did not meet the standards; the output label of the model is the optimization type of the smart contract; the smart contract optimization detection model consists of v decision trees. Through Bootstrap sampling, when training each decision tree, a subset is randomly selected from the training set to train the tree, and a subset of features is randomly selected to split the node until the stopping condition is reached; the smart contract optimization detection model is a random forest model;
[0173] Multi-classification cross entropy is used as the loss function of the model to measure the difference between the predicted value and the actual value of the model; the multi-classification cross entropy loss function is:
[0174] Where L is the average loss of the dataset; N is the total number of samples in the dataset; B is the number of optimization types of smart contracts; p i′b′ is the true label of the optimization type of the i′th sample for the b′th smart contract; p i′b′ The probability that the i′th sample predicted by the model belongs to the optimization type of the b′th smart contract;
[0175] Use the training set to train the smart contract optimization detection model, and use the back-propagation algorithm to update the model parameters to minimize the loss function; use the validation set to evaluate the performance of the smart contract optimization detection model by calculating the precision index;
[0176] Adopt the random search hyperparameter optimization method, tune the hyperparameters of the smart contract optimization detection model according to the performance feedback of the validation set, and adjust the model hyperparameter combination until the performance of the model is no longer significantly improved or reaches the preset stopping condition;
[0177] Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract optimization detection model to predict the current substandard smart contract execution data to obtain the optimization type of the smart contract.
[0178] According to the predicted smart contract optimization type, the method of selecting the corresponding personalized smart contract optimization strategy includes:
[0179] The optimization strategy of the smart contract optimization type is analyzed through the smart contract performance evaluation model, and the smart contract performance score is calculated according to the smart contract performance evaluation model. The smart contract performance evaluation model is:
[0180]
[0181] ; Where P is the smart contract performance score; N′ dup N′ is the number of repeated code segments in the smart contract; tal is the total number of code segments in the smart contract; F fal is the number of failed smart contract executions; t is a time point at a certain moment in the smart contract execution process; T ec The time required for smart contract execution; F erris the error frequency in the execution of smart contracts; δ1 is the weight factor for the number of repeated code segments in the smart contract; δ2 is the weight factor for the number of failed smart contract executions; δ3 is the weight factor for the time required for smart contract execution; δ4 is the weight factor for the error frequency in the execution of smart contracts;
[0182] As the number of repeated code segments increases, the negative impact on performance increases in a nonlinear manner. If there are more repeated codes, the impact on performance will be greater; when the proportion of repeated codes to the total code volume is large, it means that the code quality is low, which will affect the efficiency of the contract. A large number of failures indicates that the execution reliability of the contract is poor and needs to be retried or corrected. The longer the execution time, the lower the efficiency of the contract. The error frequency reflects the probability of problems occurring during the execution of the contract. When the error frequency increases, the speed of performance degradation will show an exponential growth. The more errors there are, the lower the performance will be, and the more frequent the errors, the more serious the impact will be.
[0183] The smart contract performance evaluation model is in fractional form. The larger the weighted sum of the independent variables in the denominator, the worse the performance of the contract that does not meet the standard. The smaller the final calculated P value, the lower the overall performance of the contract.
[0184] The preset smart contract performance index threshold is divided into low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L ; Compare the calculated smart contract performance score P with the low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L Make a comparison;
[0185] If P ≈ P S , then the smart contract optimization type is determined to be a low-level type, and the smart contract control terminal issues a first-level optimization instruction to automatically generate a low-level smart contract optimization strategy; the low-level smart contract optimization strategy includes optimizing the code structure, reducing the number of redundant code segments, increasing the contract retry mechanism, reducing the number of execution failures, introducing dynamic sharding or parallel computing, shortening the execution time, strengthening the error detection and correction mechanism, and reducing the error frequency;
[0186] If P S ≤P<P M , the smart contract optimization type is determined to be intermediate type, and the smart contract control terminal issues a secondary optimization instruction to automatically generate an intermediate type smart contract optimization strategy; the intermediate type smart contract optimization strategy includes further optimizing the contract through the code analysis tool Solhint, reducing duplicate code, improving the contract execution logic, adjusting the execution path of the smart contract, and using redundant calculations and off-chain verification technology to reduce the error frequency;
[0187] If P M ≤P<P L , the smart contract optimization type is determined to be advanced type, and the smart contract control terminal issues a third-level optimization instruction to automatically generate an advanced type smart contract optimization strategy; the advanced type smart contract optimization strategy includes continuing to optimize the current architecture through the SonarQube optimization tool, reducing the number of repeated code segments, redesigning the storage mode of the contract, moving some transactions to off-chain processing, reducing on-chain congestion, allowing the contract to interact with other blockchains, and reducing the frequency of errors;
[0188] The preset smart contract performance indicator threshold is set by the staff, and different smart contract performance indicators are collected through the smart contract control terminal, and the average value of multiple smart contract performance indicators is taken as the preset smart contract performance indicator threshold;
[0189] This embodiment uses targeted methods to pre-process different types of data (blockchain network data, off-chain data, user information data, network environment data) to ensure data accuracy and consistency; hash functions, sharding technology, quick sorting, and harmonic mean algorithms are used to improve processing efficiency. In response to the dynamic changes in the blockchain network environment, a dynamic adjustment formula is used to optimize parameters such as the number of verifications, the number of shards, and the weight factor, which helps to make flexible adjustments based on real-time network conditions and avoid excessive waste of computing resources;
[0190] The smart contract performance evaluation model takes into account multiple key factors that affect the performance of smart contracts, such as the number of repeated code segments, the number of execution failures, the execution time, and the error frequency. The overall performance of smart contracts is evaluated through multiple dimensions to ensure the comprehensiveness and accuracy of the evaluation results; the weighted sum of various influencing factors can accurately quantify the contribution of each factor to the performance of smart contracts, and then derive the performance score, which is convenient for optimization of specific problems; the model introduces changes in time points during the execution of smart contracts, and can dynamically capture the performance changes of contracts at different execution stages, especially in terms of execution time and error frequency, so that fluctuations in contract performance can be identified in a timely manner and real-time optimization suggestions can be provided.
[0191] Example 2
[0192] See also Figure 2 As shown, this embodiment is a blockchain-based smart contract data analysis system, including:
[0193] Data collection module, used to collect blockchain network data, off-chain data, user information data and network environment data;
[0194] The data processing module is used to pre-process the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set;
[0195] The data analysis module analyzes the impact of the network environment feature data set on the blockchain network feature data set and the user feature data set to obtain the impact feature data set; performs weighted fusion on the impact feature data set, the blockchain network feature data set, the off-chain feature data set and the user feature data set to obtain the comprehensive feature data set;
[0196] The smart contract performance prediction module is used to obtain the smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model;
[0197] The smart contract performance evaluation module is used to compare the predicted smart contract performance indicators with the preset smart contract performance indicator thresholds to determine whether the smart contract performance meets the standards; if it meets the standards, the execution of the smart contract is continuously monitored; if it does not meet the standards, an early warning message is issued through the smart contract control terminal, an early warning instruction is automatically generated, and the execution data of the smart contract that does not meet the standards is collected;
[0198] The smart contract performance optimization module is used to obtain a smart contract optimization detection model based on the training of substandard smart contract execution data, and predict the optimization type of the smart contract through the smart contract optimization detection model; according to the predicted smart contract optimization type, the corresponding personalized smart contract optimization strategy is selected.
[0199] Since the electronic device introduced in this embodiment is an electronic device used to implement a blockchain-based smart contract data analysis method and system in the embodiment of this application, based on the blockchain-based smart contract data analysis method and system introduced in the embodiment of this application, the technical personnel of this field can understand the specific implementation of the electronic device of this embodiment and its various variations, so how the electronic device implements the method in the embodiment of this application is not introduced in detail here. As long as the technical personnel of this field implement the electronic device used by the blockchain-based smart contract data analysis method and system in the embodiment of this application, it belongs to the scope of protection of this application.
[0200] The above formulas are all dimensionless and numerical calculations. The formula is a formula for the most recent real situation obtained by collecting a large amount of data and performing software simulation. The preset parameters and thresholds in the formula are set by technicians in this field according to actual conditions.
[0201] The above is only a preferred embodiment of the present invention, and the protection scope of the present invention is not limited to the above embodiments. All technical solutions under the concept of the present invention belong to the protection scope of the present invention. It should be pointed out that for ordinary technical users in this technical field, some improvements and modifications without departing from the principle of the present invention should also be regarded as the protection scope of the present invention.
Claims
1. A smart contract data analysis method based on blockchain, characterized in that: include: S1. Collect blockchain network data, off-chain data, user information data and network environment data; S2. Preprocess the acquired blockchain network data, off-chain data, user information data, and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set, and a network environment feature data set; S3. Analyze the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain an impact feature dataset; perform weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset and the user feature dataset to obtain a comprehensive feature dataset; S4. Obtain a smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model; S5. Compare the predicted smart contract performance index with the preset smart contract performance index threshold to determine whether the smart contract performance meets the standard; if it meets the standard, continue to monitor the execution of the smart contract; If the standards are not met, a warning message will be issued through the smart contract control terminal, a warning instruction will be automatically generated, and the execution data of the smart contract that does not meet the standards will be collected; S6. Obtain a smart contract optimization detection model based on the execution data of substandard smart contracts, and predict the optimization type of the smart contract through the smart contract optimization detection model; select the corresponding personalized smart contract optimization strategy based on the predicted smart contract optimization type.
2. According to a blockchain-based smart contract data analysis method according to claim 1, it is characterized in that: The blockchain network data includes transaction record data, block information data and smart contract data; the transaction record data includes transaction hash, initiator address, recipient address, transaction amount and gas fee; the block information data includes block height, previous block hash and transaction quantity; the smart contract data includes contract address, contract ABI and contract status; The off-chain data includes market prices, market transaction volumes, and number of comments related to smart contracts; the user information data includes user behavior data and user identity information data; User behavior data includes the user's browsing volume and transaction time in decentralized applications; user identity information data includes the user's digital signature, authentication time and account address; the network environment data includes network communication delay, network bandwidth and packet loss rate during data transmission.
3. According to a blockchain-based smart contract data analysis method according to claim 2, it is characterized in that: The method of preprocessing the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set includes: S31. Preprocessing of transaction record data in blockchain network data: S311. Use the local database provided by the blockchain node Ethereum to process the transaction hash, store the transaction data through the LevelDB in the Ethereum node, and the user queries the transaction hash through the JSON-RPC interface; S312. Record the initiator's address as A se , let the receiver's address be A re , use the hash processing formula to process the initiator address A se and the recipient address A re Unify the format; Sort the hashed address set in ascending order. Let the sorted address set be {A′ (1) ,A′ (2) ,...,A′ (m) }; where m is the number of addresses after sorting; A′ (1) is the first hash address after sorting; remove adjacent duplicate addresses from the sorted set in sequence; Preset q shards and k hash functions, use the hash function to assign the hashed addresses to different shards, for each address A′ in the deduplicated address set u (a) , calculate its fragment number; The preset number of shards q is dynamically adjusted by the shard number adjustment formula, and the shard number adjustment formula is: Where m is the number of sorted addresses; k is the number of types of hash functions; is the rounding function; For each hash address A′ (a) , store it in the corresponding hash table according to its shard number, and check each address A′ (a) Check whether the shard number is already in the hash table. If not, add it to the hash table and merge the deduplication results in all shards into the final deduplication address set; S313, the sum of the transaction amounts of all users in the entire period is calculated to obtain the total transaction amount S of all users, and the total transaction amount S of all users is divided by the total number of transactions M in the entire period to obtain the average transaction amount of each user in the entire period; The volatility of transaction amounts is measured by calculating the standard deviation of transaction amounts; S314. Count the total transaction amount within the L-period, divide the total transaction amount within the L-period by the total number of transactions M within the statistical period, and obtain the average gas fee of the user within the L-period; S32. Preprocessing of block information data in blockchain network data: S321. Arrange the block heights in ascending order by quick sorting, and verify whether the block heights are continuous by checking the continuity condition; S322, for each block D c , the block hash value is preset to h′ c , the hash value of the previous block is h′ c -1, verify the hash value h′ of the previous block c -1 is equal to the hash value of the previous block calculated by the hash function; S323. The number of block verifications is adjusted by dynamically adjusting the verification formula, wherein the dynamic adjustment verification formula is: Among them, T(m′,h c ) is the number of block verifications; k′ is the block verification interval; ε is the error control parameter; h c is the height of the cth block; c is the block number; S324. Use the Pandas library in Python, a data analysis tool, to count the number of transactions in each block, and calculate the average transaction volume, maximum value, and minimum value of each block through the aggregation function in the Pandas library; S33. Preprocessing of smart contract data in blockchain network data: S331. The number of transactions of the initiator address in the blockchain is recorded as the transaction nonce. The initiator address and the transaction nonce are encoded by RLP encoding, and then the contract address is calculated by the hash function H. S332. Use the JSON parser to read and parse the ABI data, use the ABI verification tool Truffle blockchain development framework to verify the ABI, check whether the ABI meets the standard format requirements, and use the Python script to filter invalid or damaged ABI data; S333. Use MySQL database to classify contract status into different status types, including active, destroyed and frozen types; define the event log of smart contract through Solidity language, and use the event log of smart contract Web3.js to monitor the change of contract status; S34. Preprocessing of off-chain data: Obtain the market price, market transaction volume, and number of comments related to the smart contract in real time through the exchange's REST API, and use Python's Pandas library to convert the market price into a non-negative floating point number, and convert the market transaction volume and number of comments into a non-negative integer; The market price is converted into a time series format using the functions in the Pandas library, and the average, maximum, and minimum values of the market transaction volume and number of comments are calculated using aggregation functions; S35. Preprocessing of user behavior data in user information data: using SQL in MySQL database to query the number of views of users in decentralized applications, using Python's Pandas library to convert the number of views of users in decentralized applications into non-negative integers, and using functions in the Pandas library to uniformly format transaction time into a standard time format; S36. Preprocessing the user identity information data in the user information data: generating a unique identifier through a hash function H, obtaining the user's digital signature, using a function in the Pandas library to uniformly format the authentication time into a standard time format, and verifying the format of the account address through the Ethereum address; S37. Preprocessing of network environment data: S371. It is assumed that the entire blockchain network has v blockchain nodes, and the communication delay between each blockchain node g and other blockchain nodes is T ly,g , the average communication delay of the entire blockchain network is calculated as; the communication delay between blockchain node g and other blockchain nodes is T ly,g Obtained through delay calculation formula; S372. Preset the bandwidth of each blockchain node to J v ,The bandwidth of the entire blockchain network is calculated using the harmonic mean formula; S373. Obtain the total number of data packets sent and the number of data packets successfully received by each blockchain node g in real time through the REST API of the exchange; for each blockchain node g, calculate the packet loss rate of a single blockchain node through the packet loss rate calculation formula; Different weights are assigned to the packet loss rate of each blockchain node g, and the weighted average packet loss rate of the entire blockchain network is calculated; the weight factor γg of each blockchain node g is dynamically adjusted through the weight factor adjustment formula; The weight factor adjustment formula is: Among them, γ′ g is the weight factor of each blockchain node g after adjustment; T ly,gf is the communication delay from blockchain node g to blockchain node f; T ly,fg is the communication delay from blockchain node f to blockchain node g; v is the number of blockchain nodes; S38. Use the LOF algorithm to identify outliers on the processed blockchain network data, off-chain data, user information data, and network environment data, and remove the identified outliers to obtain the processed blockchain network feature data set, off-chain feature data set, user feature data set, and network environment feature data set; The obtained blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are normalized by standard deviation and converted into standard normal distribution, and finally the normalized blockchain network feature dataset, off-chain feature dataset, user feature dataset and network environment feature dataset are obtained.
4. According to a blockchain-based smart contract data analysis method according to claim 3, it is characterized in that: The method of analyzing the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset to obtain the impact feature dataset includes: Taking network environment characteristics, blockchain network characteristics and user characteristics as input variables, a joint regression model is constructed. By constructing a joint regression model, the impact of the network environment characteristic dataset on the blockchain network characteristic dataset and the user characteristic dataset is analyzed, and finally the affected characteristic dataset is obtained.
5. According to the blockchain-based smart contract data analysis method of claim 4, it is characterized in that: The method of weightedly fusing the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset, and the user feature dataset to obtain a comprehensive feature dataset includes: The impact feature dataset, blockchain network feature dataset, off-chain feature dataset and user feature dataset are fused through a weighted model to obtain a comprehensive feature dataset.
6. According to a blockchain-based smart contract data analysis method according to claim 5, it is characterized in that: The training method of the smart contract performance prediction model includes: Divide the dataset into training set, validation set and test set, train the model and evaluate the model performance; The sample set is a subset of the data set. Each sample set includes a historical comprehensive feature data set and corresponding smart contract performance indicators. A smart contract performance prediction model is constructed. The model includes an input layer, a hidden layer, and an output layer. The hidden layer uses the ReLU activation function. The input layer of the model is used to input the historical comprehensive feature data set, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature data set; the output layer of the model is used to output the smart contract performance index, and the number of neurons in the output layer corresponds to the number of prediction targets, and the prediction value is output through one neuron; the smart contract performance prediction model is a fully connected neural network model; Use the coefficient of determination to evaluate the difference between the smart contract performance indicators predicted by the model and the actual smart contract performance indicators; Use the training set to train the smart contract performance prediction model, and update the model parameters through the back-propagation algorithm to minimize the loss function; use the validation set to evaluate the performance of the smart contract performance prediction model through the determination coefficient; The Adam optimization algorithm is used as the optimizer. The model is tuned according to the performance feedback of the validation set. The model parameters are adjusted until the performance is no longer significantly improved or the preset number of iterations is reached. Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract performance prediction model to predict the current comprehensive feature data set to obtain the smart contract performance indicators.
7. The method for analyzing smart contract data based on blockchain according to claim 6, characterized in that: The method of comparing the predicted smart contract performance indicator with the preset smart contract performance indicator threshold to determine whether the smart contract performance meets the standard includes: If the predicted smart contract performance index is greater than or equal to the preset smart contract performance index threshold, the smart contract performance is judged to be up to standard; If the predicted smart contract performance indicator is less than the preset smart contract performance indicator threshold, the smart contract performance is judged to be substandard.
8. A blockchain-based smart contract data analysis method according to claim 7, characterized in that: The training method of the smart contract optimization detection model includes: The substandard smart contract execution data includes the number of repeated code segments in the smart contract, the number of failed smart contract executions, the time required for smart contract execution, and the frequency of errors that occur in smart contract execution; The data set is divided into training set, validation set and test set to train the model and evaluate the model performance; the sample set is a subset of the data set, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract; The input data of the model is the historical execution data of smart contracts that did not meet the standards; the output label of the model is the optimization type of the smart contract; the smart contract optimization detection model consists of v decision trees. Through Bootstrap sampling, when training each decision tree, a subset is randomly selected from the training set to train the tree, and a subset of features is randomly selected to split the node until the stopping condition is reached; the smart contract optimization detection model is a random forest model; Use multi-classification cross entropy as the loss function of the model to measure the difference between the model's predicted value and the actual value; Use the training set to train the smart contract optimization detection model, and use the back-propagation algorithm to update the model parameters to minimize the loss function; use the validation set to evaluate the performance of the smart contract optimization detection model by calculating the precision index; Adopt the random search hyperparameter optimization method, tune the hyperparameters of the smart contract optimization detection model according to the performance feedback of the validation set, and adjust the model hyperparameter combination until the performance of the model is no longer significantly improved or reaches the preset stopping condition; Use the test set to evaluate the performance of the model in the prediction task, and use the trained smart contract optimization detection model to predict the current substandard smart contract execution data to obtain the optimization type of the smart contract.
9. The method for analyzing smart contract data based on blockchain according to claim 8, characterized in that: The method of selecting a corresponding personalized smart contract optimization strategy according to the predicted smart contract optimization type includes: The optimization strategy of the smart contract optimization type is analyzed through the smart contract performance evaluation model, and the smart contract performance score is calculated according to the smart contract performance evaluation model. The smart contract performance evaluation model is: ; Where P is the smart contract performance score; N′ dup N′ is the number of repeated code segments in the smart contract; tal is the total number of code segments in the smart contract; F fal is the number of failed smart contract executions; t is a time point at a certain moment in the smart contract execution process; T ec The time required for smart contract execution; F err is the error frequency in the execution of smart contracts; δ1 is the weight factor for the number of repeated code segments in the smart contract; δ2 is the weight factor for the number of failed smart contract executions; δ3 is the weight factor for the time required for smart contract execution; δ4 is the weight factor for the error frequency in the execution of smart contracts; The preset smart contract performance index threshold is divided into low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L ; Compare the calculated smart contract performance score P with the low performance index threshold P S , medium performance index threshold P M and high performance index threshold P L Make a comparison; If P<P S , then the smart contract optimization type is determined to be a low-level type, and the smart contract control terminal issues a first-level optimization instruction and automatically generates a low-level smart contract optimization strategy; If P S ≤P<P M , then the smart contract optimization type is determined to be intermediate type, and the smart contract control terminal issues a secondary optimization instruction and automatically generates an intermediate type smart contract optimization strategy; If P M ≤P<P L , the smart contract optimization type is determined to be advanced type, and the smart contract control terminal issues a third-level optimization instruction to automatically generate an advanced type smart contract optimization strategy.
10. A blockchain-based smart contract data analysis system, used to implement a blockchain-based smart contract data analysis method according to any one of claims 1 to 9, characterized in that: include: Data collection module, used to collect blockchain network data, off-chain data, user information data and network environment data; The data processing module is used to pre-process the acquired blockchain network data, off-chain data, user information data and network environment data to obtain a blockchain network feature data set, an off-chain feature data set, a user feature data set and a network environment feature data set; The data analysis module analyzes the impact of the network environment feature data set on the blockchain network feature data set and the user feature data set to obtain the impact feature data set; performs weighted fusion on the impact feature data set, the blockchain network feature data set, the off-chain feature data set and the user feature data set to obtain the comprehensive feature data set; The smart contract performance prediction module is used to obtain the smart contract performance prediction model based on the comprehensive feature data set training, and predict the smart contract performance indicators based on the smart contract performance prediction model; The smart contract performance evaluation module is used to compare the predicted smart contract performance indicators with the preset smart contract performance indicator thresholds to determine whether the smart contract performance meets the standards; if it meets the standards, the execution of the smart contract is continuously monitored; If the standards are not met, a warning message will be issued through the smart contract control terminal, a warning instruction will be automatically generated, and the execution data of the smart contract that does not meet the standards will be collected; The smart contract performance optimization module is used to obtain a smart contract optimization detection model based on the training of the substandard smart contract execution data, and predict the optimization type of the smart contract through the smart contract optimization detection model; according to the predicted smart contract optimization type, the corresponding personalized smart contract optimization strategy is selected; The modules are connected to each other via wired and / or wireless means.
Citation Information
Patent Citations
Internet-of-Things platform based on block chain
CN111447066A
Intelligent contract data safety management method and system based on block chain network, and storage medium
CN113449034A
Data processing method, data processing device, data processing system and electronic equipment
CN113779642A
Distributed node intrusion situation awareness method based on block chain
CN116405187A
Block chain sharing-based edge cloud service parallel resource allocation method
CN116599966A