A blockchain-based smart contract data analysis method and system
By preprocessing blockchain network data and fusing feature data sets, training smart contract performance prediction and optimization detection models, the problems of resource waste and performance degradation in smart contract data analysis are solved, and dynamic optimization and real-time performance evaluation are achieved.
Patent Information
- Application Number
- CN202411563216.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-11-05
- Publication Date
- 2025-09-12
- Estimated Expiration
- 2044-11-05
AI Technical Summary
Existing smart contract data analysis methods and systems lack effective mechanisms to ensure the authenticity, integrity and real-time nature of data, and are unable to adapt to the dynamic changes in the blockchain network environment, resulting in waste of computing resources and performance degradation, especially under high load or complex scenarios, which may cause system crashes.
By collecting blockchain network data, off-chain data, user information data and network environment data, pre-processing and then fusing feature data sets, training smart contract performance prediction models and optimization detection models, dynamically adjusting the number of verifications and shards, and using weighted fusion and neural network models for performance evaluation and optimization.
It realizes dynamic optimization of smart contract performance in the blockchain network environment, reduces the waste of computing resources, improves the comprehensiveness and accuracy of evaluation results, and can promptly identify performance fluctuations and provide real-time optimization suggestions.
Smart Images

Figure CN119646428B_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 self-executing protocols, have been widely used in various fields, including finance, supply chain, and the Internet of Things. Smart contracts can automatically execute instructions based on pre-set conditions, reducing human intervention while improving transaction transparency and security. However, the complexity and immutability of smart contract data pose challenges to data analysis.
[0003] The patent application publication number CN113449034A discloses a smart contract data security management method, system and storage medium based on a blockchain network, including synchronously storing the public key information in the asymmetric public and private keys when generating a smart contract; triggering a data management request, establishing blockchain network communication, calling the smart contract to generate verification data, and after assigning timeliness management to the verification data, returning it 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 based on 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 on-chain data, 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 suffer from the following major problems:
[0005] In a blockchain network environment, factors such as network conditions and node performance change dynamically. Without considering dynamic adjustment and optimization of parameters such as the number of verifications and the number of shards, the system may use a fixed strategy for processing, resulting in unnecessary verification and calculations even when network conditions are good, resulting in 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 reduced 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, opportunities to discover and solve problems may be missed, and performance under different conditions cannot be dynamically adjusted or optimized, which limits the effectiveness of smart contracts in different application scenarios, especially in 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 achieve the above-mentioned objectives, the present invention provides the following technical solution: a blockchain-based smart contract data analysis method, 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset;
[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 dataset training, and predict smart contract performance indicators based on the smart contract performance prediction model;
[0013] S5. 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 so, continuously monitor the execution of the smart contract; if not, issue a warning message through the smart contract control terminal, automatically generate warning instructions, and collect execution data of the substandard smart contract;
[0014] S6. Obtain a smart contract optimization detection model based on training data from substandard smart contract executions, and predict the optimization type of the smart contract through the smart contract optimization detection model; select a 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset 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'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's 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 sorted addresses; A′ (1) is the first hash address after sorting; remove adjacent duplicate addresses from the sorted set in sequence;
[0023] Preset the number of 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, which 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 of all shards into the final deduplication address set;
[0026] S313. Calculate the sum of all users' transaction amounts during the entire period to obtain a total transaction amount S for all users. Divide the total transaction amount S by the total number of transactions M during the entire period to obtain an average transaction amount per user during 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, and divide the total transaction amount within the L-period by the total number of transactions M within the statistical period to obtain the average gas fee for 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. 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 using the aggregation functions in the Pandas library.
[0034] S33. Preprocessing of smart contract data in blockchain network data:
[0035] S331. The number of transactions of the initiator's address in the blockchain is recorded as the transaction nonce. The initiator's address and the transaction nonce are encoded using RLP encoding, and then the contract address is calculated using the hash function H.
[0036] S332. Use a JSON parser to read and parse ABI data. Use the ABI verification tool, the Truffle blockchain development framework, to verify the ABI to check whether the ABI conforms to standard format requirements. Use a Python script to filter invalid or damaged ABI data.
[0037] S333. Use the MySQL database to classify contract status into different status types, including active, destroyed, and frozen. Define the event log of the smart contract in Solidity and use Web3.js to monitor changes in the contract status.
[0038] S34. Preprocessing of off-chain data: Obtain market prices, market trading volumes, and number of comments related to smart contracts in real time through the exchange's REST API. Use Python's Pandas library to convert market prices into non-negative floating-point numbers, and market trading volumes and number of comments into non-negative integers.
[0039] Use functions in the Pandas library to convert market prices into time series format, and use aggregation functions to calculate the average, maximum, and minimum values of market transaction volume and number of comments;
[0040] S35. Preprocessing the user behavior data in the user information data: Use SQL in the MySQL database to query the number of views of the user in the decentralized application, use the Python Pandas library to convert the number of views of the user in the decentralized application into a non-negative integer, and use functions in the Pandas library to uniformly format the transaction time into a standard time format;
[0041] S36. Preprocessing the user identity information data in the user information data: Generate a unique identifier using the hash function H, obtain the user's digital signature, use functions in the Pandas library to uniformly format the authentication time into a standard time format, and verify the format of the account address using 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 the 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, in real time, the total number of data packets sent and the number of data packets successfully received by each blockchain node g through the exchange's REST API; for each blockchain node g, calculate the packet loss rate of the individual blockchain node using the packet loss rate calculation formula;
[0046] Assign different weights to the packet loss rate of each blockchain node g, and calculate the weighted average packet loss rate of the entire blockchain network; dynamically adjust the weight factor γg of each blockchain node g 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 dataset, off-chain feature dataset, user feature dataset, and network environment feature dataset;
[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 impact 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] The dataset is divided into training, validation, and test sets to train the model and evaluate its performance. The sample set is a subset of the dataset, and each sample set includes a historical comprehensive feature dataset and corresponding smart contract performance indicators. A smart contract performance prediction model is constructed, which includes an input layer, a hidden layer, and an output layer. The hidden layer uses the ReLU activation function.
[0056] The model's input layer is used to input a historical comprehensive feature dataset, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature dataset. The model's output layer is used to output smart contract performance indicators. The number of neurons in the output layer corresponds to the number of prediction targets, and the predicted value is output through a single 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] The smart contract performance prediction model is trained using the training set and the model parameters are updated through the back-propagation algorithm to minimize the loss function. The performance of the smart contract performance prediction model is evaluated using the coefficient of determination using the validation set.
[0059] The Adam optimization algorithm is used as the optimizer. The model is tuned based on the performance feedback of the validation set. The model parameters are adjusted until the performance no longer improves significantly 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 a preset smart contract performance indicator threshold to determine whether the smart contract performance meets the threshold includes:
[0062] If the predicted smart contract performance indicator is greater than or equal to the preset smart contract performance indicator threshold, the smart contract performance is determined 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 during smart contract execution;
[0066] The dataset is divided into training, validation, and test sets to train the model and evaluate its performance. The sample set is a subset of the dataset, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract.
[0067] The model's input data is historical substandard smart contract execution data; the model's output label is the smart contract's optimization type. The smart contract optimization detection model consists of v decision trees. Bootstrap sampling is used to train each decision tree by randomly selecting a subset from the training set to train the tree. A subset of features is randomly selected to split nodes until a stopping condition is met. The smart contract optimization detection model is a random forest model.
[0068] Use multi-class 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 backpropagation 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 metric.
[0070] Using the random search hyperparameter optimization method, the hyperparameters of the smart contract optimization detection model are tuned based on the performance feedback of the validation set. The model hyperparameter combination is adjusted until the model performance no longer improves significantly or the preset stopping condition is reached.
[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 based on 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]
[0075] ; 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 in the smart contract execution process; T ec The time required for smart contract execution; F err is the error frequency in smart contract execution; δ1 is the weighting factor for the number of repeated code segments in the smart contract; δ2 is the weighting factor for the number of failed smart contract executions; δ3 is the weighting factor for the time required for smart contract execution; δ4 is the weighting factor for the error frequency in smart contract execution;
[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 indicator 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 indicator threshold P L Make a comparison;
[0077] If P < P S , then the smart contract optimization type is determined to be low-level, 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 , then the smart contract optimization type is determined to be advanced type, and the smart contract control terminal issues a three-level optimization instruction and automatically generates 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset;
[0083] The data analysis module analyzes 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; performs weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset, and the user feature dataset to obtain the comprehensive feature dataset;
[0084] The smart contract performance prediction module is used to train a smart contract performance prediction model based on a comprehensive feature data set, and predict 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 the standards are met, the execution of the smart contract is continuously monitored. If the standards are not met, 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 substandard smart contract is collected.
[0086] The smart contract performance optimization module is used to train a smart contract optimization detection model based on substandard smart contract execution data. The smart contract optimization detection model predicts the optimization type of the smart contract. Based on the predicted smart contract optimization type, the module selects the corresponding personalized smart contract optimization strategy.
[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 pre-processing methods for different types of data (blockchain network data, off-chain data, user information data, and network environment data), we ensure data accuracy and consistency; through hash functions, sharding technology, quick sorting, and harmonic mean algorithms, we improve 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 flexibly adjust according to real-time network conditions and avoid excessive waste of computing resources.
[0089] The smart contract performance evaluation model considers several key factors that influence smart contract performance, such as the number of repeated code segments, execution failures, execution time, and error frequency. It evaluates the overall performance of smart contracts across multiple dimensions to ensure comprehensiveness and accuracy. By weighting and summing each influencing factor, it accurately quantifies each factor's contribution to smart contract performance, deriving a performance score that facilitates targeted optimization. The model also incorporates changes in the timing of smart contract execution, dynamically capturing performance changes at different stages, particularly in terms of execution time and error frequency. This allows for timely identification of contract performance fluctuations and provides real-time optimization recommendations. BRIEF DESCRIPTION OF THE DRAWINGS
[0090] Figure 1 This is a flowchart of a blockchain-based smart contract data analysis method 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 clearly and completely describe the technical solutions in the embodiments of the present invention in conjunction with the accompanying drawings. 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 making creative efforts 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 blockchain-based smart contract data analysis method, 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset;
[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 dataset training, and predict smart contract performance indicators based on the smart contract performance prediction model;
[0099] S5. 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 so, continuously monitor the execution of the smart contract; if not, issue a warning message through the smart contract control terminal, automatically generate warning instructions, and collect execution data of the substandard smart contract;
[0100] S6. Obtain a smart contract optimization detection model based on training data from substandard smart contract executions, and predict the optimization type of the smart contract through the smart contract optimization detection model; select a 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 number of views and transaction times of users 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset 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'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's 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’s 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 sorted addresses; A′ (1) is the first hash address after sorting;
[0109] Remove adjacent duplicate addresses from the sorted set in sequence:
[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 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 the number of 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 of all shards into the final deduplication address set;
[0114] S313. Calculate the sum of all users' transaction amounts during the entire period to obtain the total transaction amount S of all users. Divide the total transaction amount S of all users by the total number of transactions M during the entire period to obtain the average transaction amount per user during 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 transaction amount is measured by calculating the standard deviation of transaction amount. The standard deviation of transaction amount is: Among them, σ B is the standard deviation of transaction amount;
[0116] S314. Count the total transaction amount within the L period The total transaction amount 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 period. The average gas fee of the user is: Among them, G avg is the average gas fee for users;
[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 that the block height is continuous by checking the continuity condition. The continuity condition is: Where, 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 Whether -1 is equal to the hash value of the previous block calculated by the hash function to ensure the integrity of the blockchain chain structure, 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. 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, a small constant used to dynamically adjust the verification ratio;
[0123] If ε is a positive value, the number of verifications will be reduced, allowing more blocks to be skipped; if ε is a negative value, more blocks will be verified; when ε = 0, the formula degenerates to the basic verification interval strategy, that is, verification once every k′ blocks; when ε>0, the number of blocks verified will be reduced, and more blocks will be skipped; conversely, when ε<0, the number of blocks verified will increase;
[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 using the aggregation functions in the Pandas library.
[0128] S33. Preprocessing of smart contract data in blockchain network data:
[0129] S331. The number of transactions of the initiator's address in the blockchain is recorded as the transaction nonce. The initiator's address and the transaction nonce are encoded using RLP encoding, and then the contract address is calculated using the hash function H.
[0130] S332. Use a JSON parser to read and parse ABI data. Use the ABI verification tool, the Truffle blockchain development framework, to verify the ABI to check whether the ABI conforms to standard format requirements. Use a Python script to filter invalid or damaged ABI data.
[0131] S333. Use the MySQL database to classify contract status into different status types, including active, destroyed, and frozen. Define the event log of the smart contract using the Solidity language, and use the smart contract event log Web3.js to monitor changes in contract status.
[0132] S34. Preprocessing of off-chain data: Obtain market prices, market trading volumes, and number of comments related to smart contracts in real time through the exchange's REST API. Use Python's Pandas library to convert market prices into non-negative floating-point numbers, and market trading volumes and number of comments into non-negative integers.
[0133] Use functions in the Pandas library to convert market prices into time series format, and use aggregation functions to calculate the average, maximum, and minimum values of market transaction volume and number of comments;
[0134] S35. Preprocessing the user behavior data in the user information data: Use SQL in the MySQL database to query the number of views of the user in the decentralized application, use the Python Pandas library to convert the number of views of the user in the decentralized application into a non-negative integer, and use functions in the Pandas library to uniformly format the transaction time into a standard time format;
[0135] S36. Preprocessing the user identity information data in the user information data: Generate a unique identifier using the hash function H, obtain the user's digital signature, use functions in the Pandas library to uniformly format the authentication time into a standard time format, and verify the format of the account address using 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 The device processing delay; T 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, in real time, the total number of data packets sent and the number of data packets successfully received by each blockchain node g through the exchange's REST API; for each blockchain node g, calculate the packet loss rate of the individual blockchain node using 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 to 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 gPerform dynamic adjustment, 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 impact and bandwidth limitation of blockchain node g are; 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, indicating that in this network, blockchain node A has relatively good communication capabilities 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 dataset, off-chain feature dataset, user feature dataset, and network environment feature dataset;
[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] Analyze the impact of the network environment feature dataset on the blockchain network feature dataset and the user feature dataset, and obtain the affected feature datasets in the following ways:
[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 impact characteristic dataset is obtained.
[0155] Methods for weighted fusion of 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 denoted as E1, the blockchain network feature dataset is denoted as E2, the off-chain feature dataset is denoted as E3, and the user feature dataset is denoted as E4.
[0157] The weighted model is: WS=E1·ω1+E2·ω2+E3ω3+E4·ω4; among them, ω1 is the weight coefficient of the influencing feature dataset; ω2 is the weight coefficient of the blockchain network feature dataset; ω3 is the weight coefficient of the off-chain feature dataset; ω4 is the weight coefficient of the user feature dataset.
[0158] The training methods for smart contract performance prediction models include:
[0159] The dataset is divided into training, validation, and test sets to train the model and evaluate its performance. The sample set is a subset of the dataset, and each sample set includes a historical comprehensive feature dataset and corresponding smart contract performance indicators. A smart contract performance prediction model is constructed, which includes an input layer, a hidden layer, and an output layer. The hidden layer uses the ReLU activation function.
[0160] The model's input layer is used to input a historical comprehensive feature dataset, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature dataset. The model's output layer is used to output smart contract performance indicators. The number of neurons in the output layer corresponds to the number of prediction targets, and the predicted value is output through a single 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 squared 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; 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] The smart contract performance prediction model is trained using the training set and the model parameters are updated through the back-propagation algorithm to minimize the loss function. The performance of the smart contract performance prediction model is evaluated using the coefficient of determination using the validation set.
[0164] The Adam optimization algorithm is used as the optimizer. The model is tuned based on the performance feedback of the validation set. The model parameters are adjusted until the performance no longer improves significantly 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 predicted smart contract performance indicators are compared with the preset smart contract performance indicator thresholds. Methods for determining whether the smart contract performance meets the thresholds include:
[0167] If the predicted smart contract performance indicator is greater than or equal to the preset smart contract performance indicator threshold, the smart contract performance is determined 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 during smart contract execution;
[0171] The dataset is divided into training, validation, and test sets to train the model and evaluate its performance. The sample set is a subset of the dataset, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract.
[0172] The model's input data is historical substandard smart contract execution data; the model's output label is the smart contract's optimization type. The smart contract optimization detection model consists of v decision trees. Bootstrap sampling is used to train each decision tree by randomly selecting a subset from the training set to train the tree. A subset of features is randomly selected to split nodes until a stopping condition is met. The smart contract optimization detection model is a random forest model.
[0173] Multi-class cross entropy is used as the loss function of the model to measure the difference between the model's predicted value and the actual value; the multi-class 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 backpropagation 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 metric.
[0176] Using the random search hyperparameter optimization method, the hyperparameters of the smart contract optimization detection model are tuned based on the performance feedback of the validation set. The model hyperparameter combination is adjusted until the model performance no longer improves significantly or the preset stopping condition is reached.
[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] Based on the predicted smart contract optimization type, the methods for selecting the corresponding personalized smart contract optimization strategy include:
[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 in the smart contract execution process; T ec The time required for smart contract execution; F erris the error frequency in smart contract execution; δ1 is the weighting factor for the number of repeated code segments in the smart contract; δ2 is the weighting factor for the number of failed smart contract executions; δ3 is the weighting factor for the time required for smart contract execution; δ4 is the weighting factor for the error frequency in smart contract execution;
[0182] As the number of repeated code segments increases, the negative impact on performance increases nonlinearly. If there is a lot of repeated code, the impact on performance will be greater; if it accounts for a large proportion of the total code volume, it means the code quality is low, which will affect the efficiency of the contract. A high number of failures indicates poor contract execution reliability, requiring retries or corrections. Longer execution times mean lower contract efficiency. The error frequency reflects the probability of problems occurring during contract execution. When the error frequency increases, the rate of performance degradation will show an exponential growth. The more errors, the lower the performance, and the more frequent the errors, the more severe the impact.
[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 contract performance that does not meet the standards. 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 indicator 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 indicator threshold P L Make a comparison;
[0185] If P ≈ P S , the smart contract optimization type is determined to be low-level, and the smart contract control terminal issues a first-level optimization instruction, automatically generating 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, adding a 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. The smart contract control terminal issues a secondary optimization instruction and automatically generates an intermediate smart contract optimization strategy. The intermediate 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 smart contract execution path, and using redundant calculations and off-chain verification technology to reduce the frequency of errors.
[0187] If P M ≤P<P L , the smart contract optimization type is determined to be advanced, and the smart contract control terminal issues a three-level optimization instruction, automatically generating an advanced smart contract optimization strategy. The advanced smart contract optimization strategy includes continuing to optimize the current architecture through the SonarQube optimization tool, reducing the number of duplicate code segments, redesigning the contract storage model, moving some transactions to off-chain processing to reduce 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 pre-processing methods for different types of data (blockchain network data, off-chain data, user information data, and network environment data) to ensure data accuracy and consistency. It also improves processing efficiency through algorithms such as hash functions, sharding, quick sorting, and harmonic mean. 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. This helps to flexibly adjust according to real-time network conditions and avoid excessive waste of computing resources.
[0190] The smart contract performance evaluation model considers several key factors that influence smart contract performance, such as the number of repeated code segments, execution failures, execution time, and error frequency. It evaluates the overall performance of smart contracts across multiple dimensions to ensure comprehensiveness and accuracy. By weighting and summing each influencing factor, it accurately quantifies each factor's contribution to smart contract performance, deriving a performance score that facilitates targeted optimization. The model also incorporates changes in the timing of smart contract execution, dynamically capturing performance changes at different stages, particularly in terms of execution time and error frequency. This allows for timely identification of contract performance fluctuations and provides real-time optimization recommendations.
[0191] Example 2
[0192] See also Figure 2 As shown, this embodiment provides 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset;
[0195] The data analysis module analyzes 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; performs weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset, and the user feature dataset to obtain the comprehensive feature dataset;
[0196] The smart contract performance prediction module is used to train a smart contract performance prediction model based on a comprehensive feature data set, and predict 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 the standards are met, the execution of the smart contract is continuously monitored. If the standards are not met, 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 substandard smart contract is collected.
[0198] The smart contract performance optimization module is used to obtain a smart contract optimization detection model based on training data from substandard smart contract executions, and predict the optimization type of the smart contract through the smart contract optimization detection model; based on 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, those skilled in the art 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 will not be described in detail here. As long as those skilled in the art implement the electronic device used in the blockchain-based smart contract data analysis method and system in the embodiment of this application, they all fall within the scope of protection of this application.
[0200] The above formulas are all dimensionless and numerical calculations. The formulas are obtained by collecting a large amount of data and performing software simulation to obtain the most recent real situation. The preset parameters and thresholds in the formulas are set by technicians in this field according to actual conditions.
[0201] The above description is merely a preferred embodiment of the present invention. The scope of protection of the present invention is not limited to the above embodiment. All technical solutions based on the principles of the present invention are within the scope of protection of the present invention. It should be noted that for users of ordinary skill in the art, various improvements and modifications that do not depart from the principles of the present invention should also be considered within the scope of protection of the present invention.
Claims
1. A blockchain-based smart contract data analysis method, 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset; Blockchain network data includes transaction record data, block information data, and smart contract data; The preprocessing of block information data in the blockchain network data includes: The number of block verifications is adjusted by dynamically adjusting the verification formula. The dynamic adjustment verification formula is: ;in, The number of times the block is verified; is the verification interval of the block; is the error control parameter; For the The height of the block; is the block number, is the total number of blocks; The preprocessing of network environment data includes: Get each blockchain node in real time through the exchange's REST API The total number of packets sent and the number of packets successfully received; for each blockchain node , calculate the packet loss rate of a single blockchain node using the packet loss rate calculation formula; For each blockchain node The packet loss rate of each blockchain node is assigned different weights, and the weighted average packet loss rate of the entire blockchain network is calculated; the weight factor adjustment formula is used to adjust the packet loss rate of each blockchain node. The weight factor Make dynamic adjustments; The weight factor adjustment formula is: ;in, For each blockchain node after adjustment The weight factor of For the blockchain node To the blockchain node Communication delay; For the blockchain node To the blockchain node Communication delay; is the number of blockchain nodes, The bandwidth of each blockchain node; 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 dataset training, and predict smart contract performance indicators based on the smart contract performance prediction model; S5. 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 so, continuously monitor the execution of the smart contract; if not, issue a warning message through the smart contract control terminal, automatically generate warning instructions, and collect execution data of the substandard smart contract; S6. Obtain a smart contract optimization detection model based on training data from substandard smart contract executions, and predict the optimization type of the smart contract through the smart contract optimization detection model; select a corresponding personalized smart contract optimization strategy based on the predicted smart contract optimization type.
2. A blockchain-based smart contract data analysis method according to claim 1, characterized in that: The transaction record data includes the transaction hash, initiator address, recipient address, transaction amount and gas fee; the block information data includes the block height, previous block hash and transaction quantity; the smart contract data includes the 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. A blockchain-based smart contract data analysis method according to claim 2, 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset includes: S21. Preprocessing of transaction record data in blockchain network data: S211. Process the transaction hash using the local database provided by the Ethereum blockchain node. The transaction data is stored in LevelDB in the Ethereum node. Users query the transaction hash through the JSON-RPC interface. S212, record the initiator address as , and record the receiver address as , use the hashing formula to process the initiator's address and the recipient's address Unify the format; Sort the hashed address set in ascending order. Let the sorted address set be ;in, is the number of addresses after sorting; is the first hash address after sorting; remove adjacent duplicate addresses from the sorted set in sequence; Preset The number of shards and A hash function is used to assign hashed addresses to different shards. Each address in , calculate its fragment number; The preset number of shards is adjusted by the shard number adjustment formula Perform dynamic adjustment, the shard quantity adjustment formula is: ;in, is the number of addresses after sorting; is the number of types of hash functions; is the rounding function; For each hash address , store it in the corresponding hash table according to its shard number, and check each address Check whether the shard number is already in the hash table. If not, add it to the hash table and merge the deduplication results of all shards into the final deduplication address set; S213. Calculate the sum of all users' transaction amounts during the entire period to obtain the total transaction amount of all users. , the total transaction amount of all users Divide by the total number of transactions in the entire statistical period , get 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; S214, Statistics The total transaction amount within the period will be The total transaction amount in the period divided by the total number of transactions in the statistical period ,get The average gas fee for users during the period; S22. Preprocessing of block information data in the blockchain network data further includes: S221. Arrange the block heights in ascending order by quick sorting, and verify whether the block heights are continuous by checking the continuity condition; S222. For each block , the block hash value is preset to , the hash value of the previous block is , verify the previous block hash value Is it equal to the hash value of the previous block calculated by the hash function? S223. 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 using the aggregation function in the Pandas library. S23. Preprocessing of smart contract data in blockchain network data: S231, record the number of transactions of the initiator's address in the blockchain as the transaction nonce, encode the initiator's address and transaction nonce through RLP encoding, and then use the hash function to Calculate the contract address; S232. Use a JSON parser to read and parse ABI data. Use the ABI verification tool, the Truffle blockchain development framework, to verify the ABI to check whether the ABI conforms to standard format requirements. Use a Python script to filter invalid or corrupted ABI data. S233. Use the MySQL database to classify contract status into different status types, including active, destroyed, and frozen. Define the event log of the smart contract using the Solidity language, and use the smart contract event log Web3.js to monitor changes in contract status. S24. Preprocessing of off-chain data: Obtain market prices, market trading volumes, and number of comments related to smart contracts in real time through the exchange's REST API. Use Python's Pandas library to convert market prices into non-negative floating-point numbers, and market trading volumes and number of comments into non-negative integers. Use functions in the Pandas library to convert market prices into time series format, and use aggregation functions to calculate the average, maximum, and minimum values of market transaction volume and number of comments; S25. Preprocessing the user behavior data in the user information data: Use SQL in the MySQL database to query the number of user views in the decentralized application, use the Python Pandas library to convert the number of user views in the decentralized application into a non-negative integer, and use functions in the Pandas library to uniformly format transaction times into a standard time format; S26. Preprocessing of user identity information data in user information data: using a hash function Generate a unique identifier, obtain the user's digital signature, use functions in the Pandas library to format the authentication time into a standard time format, and verify the format of the account address using the Ethereum address; S27. Preprocessing of network environment data further includes: S271, the entire blockchain network is pre-set blockchain nodes, each blockchain node The communication delay with other blockchain nodes is , the average communication delay of the entire blockchain network is calculated to be ; Blockchain nodes Communication delay with other blockchain nodes Obtained through the delay calculation formula; S272. The bandwidth of each blockchain node is preset to ,The bandwidth of the entire blockchain network is calculated using the harmonic mean formula; S28. 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 dataset, off-chain feature dataset, user feature dataset, and network environment feature dataset; 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. A blockchain-based smart contract data analysis method according to claim 3, 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 feature dataset on the blockchain network feature dataset and the user feature dataset is analyzed, and finally the impact feature dataset is obtained.
5. The blockchain-based smart contract data analysis method according to claim 4, 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. A blockchain-based smart contract data analysis method according to claim 5, 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 dataset. Each sample set includes a historical comprehensive feature dataset 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 model's input layer is used to input a historical comprehensive feature dataset, and the number of neurons in the input layer matches the number of features in the historical comprehensive feature dataset. The model's output layer is used to output smart contract performance indicators. The number of neurons in the output layer corresponds to the number of prediction targets, and the predicted value is output through a single 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; The smart contract performance prediction model is trained using the training set and the model parameters are updated through the back-propagation algorithm to minimize the loss function. The performance of the smart contract performance prediction model is evaluated using the coefficient of determination using the validation set. The Adam optimization algorithm is used as the optimizer. The model is tuned based on the performance feedback of the validation set. The model parameters are adjusted until the performance no longer improves significantly 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. A blockchain-based smart contract data analysis method 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 threshold includes: If the predicted smart contract performance indicator is greater than or equal to the preset smart contract performance indicator threshold, the smart contract performance is determined 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. The method for analyzing smart contract data based on blockchain 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 smart contract execution failures, the time required for smart contract execution, and the frequency of errors that occur in smart contract execution; The dataset is divided into training, validation, and test sets to train the model and evaluate its performance. The sample set is a subset of the dataset, and each sample set includes historical substandard smart contract execution data and the optimization type of the corresponding smart contract. The model's input data is historical substandard smart contract execution data; the model's output label is the smart contract's optimization type. The smart contract optimization detection model consists of v decision trees. Bootstrap sampling is used to train each decision tree by randomly selecting a subset from the training set to train the tree. A subset of features is randomly selected to split nodes until a stopping condition is met. The smart contract optimization detection model is a random forest model. Use multi-class 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 backpropagation 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 metric. Using the random search hyperparameter optimization method, the hyperparameters of the smart contract optimization detection model are tuned based on the performance feedback of the validation set. The model hyperparameter combination is adjusted until the model performance no longer improves significantly or the preset stopping condition is reached. 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 blockchain-based smart contract data analysis method according to claim 8, characterized in that: The method for selecting a corresponding personalized smart contract optimization strategy based on 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: ;in, Score smart contract performance; The number of repeated code segments in the smart contract; is the total number of code segments in the smart contract; The number of failed smart contract executions; A time point at a certain moment in the execution of a smart contract; The time required for smart contract execution; The frequency of errors that occur during smart contract execution; The weight factor for the number of repeated code segments in the smart contract; The weight factor for the number of failed smart contract executions; The weight factor for the time required for smart contract execution; is the weight factor of the error frequency in smart contract execution; Divide the preset smart contract performance indicator threshold into a low performance indicator threshold , medium performance indicator threshold and high performance indicator thresholds ; The calculated smart contract performance score Low performance index threshold , medium performance indicator threshold and high performance indicator thresholds Make a comparison; like , then the smart contract optimization type is determined to be low-level, and the smart contract control terminal issues a first-level optimization instruction and automatically generates a low-level smart contract optimization strategy; like , 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; like , then the smart contract optimization type is determined to be advanced type, and the smart contract control terminal issues a three-level optimization instruction and automatically generates 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 dataset, an off-chain feature dataset, a user feature dataset, and a network environment feature dataset; The data analysis module analyzes 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; performs weighted fusion on the impact feature dataset, the blockchain network feature dataset, the off-chain feature dataset, and the user feature dataset to obtain the comprehensive feature dataset; The smart contract performance prediction module is used to train a smart contract performance prediction model based on a comprehensive feature data set, and predict 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, an early warning message will be issued through the smart contract control terminal, an early 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 train a smart contract optimization detection model based on substandard smart contract execution data. The smart contract optimization detection model predicts the optimization type of the smart contract. Based on the predicted smart contract optimization type, the module selects the corresponding personalized smart contract optimization strategy. The modules are connected to each other via wired and / or wireless means.
Citation Information
Patent Citations
Intelligent contract data safety management method and system based on block chain network, and storage medium
CN113449034A
Network signal optimization method and system for wireless ad hoc network
CN118714597A